If statement in Python

mainpynerds

Main

Posted on March 12, 2024

If statement in Python

In Python, the if statement is the basic tool used to make decisions when two or more alternative actions are to be taken. It is used to evaluate a condition and take an action based on the results of the evaluation.

The following example shows a simple if statements.

x = 10

if x == 10:
    print('x is equal to 10')

Typically, the if statement consists of  a condition, followed by one or more actions to take if the condition is met. The following shows the general syntax of the if statement.

if <condition>:
    <statements>
elif <condition>:
    <statements>
else:
    <statements>

As shown above, an if statement has three primary blocks, if , elif and else, together they may be referred to as conditional expression blocks.

The if block signals the start of an if statement. It contains a condition that must be met in order for the code within the block to be executed.  This block can stand alone in an if statement without elif or else blocks. 

The elif block, also popularly known as the “else-if” block  is used to check for additional conditions if the condition of the initial if block fails. We can have as much elif blocks as necessary but an elif block cannot stand alone , there needs to be a  preceding if block.

The else block gets executed when all the preceding if and elif blocks fails. Similarly an else block cannot stand alone, there must be a preceding if block.  We can only have a single else block in one if statement. 


def check(x):
    if x > 0: 
        print(f"{x} is positive") 
    elif x < 0: 
        print(f"{x} is negative") 
    else: 
        print(f"{x} is zero") 

check(10)
check(-5)
check(0)
check(2)

In the above example, if the value of x is greater than 0, the first if block gets executed. If the value of x is less than 0, the elif block gets executed, and if neither of the if and elif blocks are satisfied, the else block gets executed. 

Multiple elif blocks

As we earlier said, we can have as much elif blocks as necessary, this allows us to chain multiple conditions together so that the block whose condition gets satisfied first is executed and the check terminates.

def check(age):
    if age < 0: 
        print("Age entered is not valid") 
    elif age <= 3: 
        print("You are a baby!") 
    elif age <= 12: 
        print("You are a child!") 
    elif age <= 18: 
        print("You are a teenager!") 
    else: 
        print("You are an adult!")

check(14)
check(25)
check(-4)

The if-else syntax

The elif blocks are optional, they are only included when multiple conditions need to be tested and evaluated. If we have a binary situation with only two possibilities, then the elif block is not needed. In this case We would only need to use an if statement and an else statement. If the condition of the if block evaluates to  True, its statements gets executed. Otherwise, the code within the else block gets executed.

def even_or_odd(x):
    if x % 2:
        print(f"{x} is odd.")
    else:
        print(f"{x} is even.")

even_or_odd(10)
even_or_odd(7)
even_or_odd(5)
even_or_odd(2)

Nested if statements

Nesting is when an if statement appears inside the body of another if statement in any of its 3 primary blocks i.e if, elif, else

There is really no limit on how nesting can occur or how deep it can get. The following demonstrates a possible structure of nested if statements:

if <condition>:
    <statements>
elif <condition>:

    if <condition>
        <statements>
    elif <condition>:
        <statements>
    else:
        <statements>
elif <condition>:
      <statements>
else:
     if <condition>:
         <statements>
     else:
         <statements>
def greater(a, b):
    if a > b: 
        print(f"{a} is greater than {b}.") 
    else: 
        if a == b: 
            print(f"{a} is equal to {b}.") 
        else: 
            print(f"{a} is less than {b}.")

greater(10, 20)
greater(10, 5)
greater(10, 10)

Short Hand syntax

If we only have a single if block in an if statement and its body is made of a single statement, we can put the single statement in the same line as shown below.

if <condition>: <statement>
x = 10

if x == 10: print('x is equal to ten')

Python also supports a short hand syntax where simple if-else blocks are condensed into a single line. The short hand syntax is suitable in cases where the body of the if and else statements consists of only one statement each.

<statement> if <condition> else <statement>

The first statement is returned if the condition evaluates to True, otherwise the statement at the end is returned. 

def check(x):
    return f'{x} is Odd' if x % 2 else f'{x} is Even'

print(check(10))
print(check(1))
print(check(7))
print(check(2))

Related articles

💖 💪 🙅 🚩
mainpynerds
Main

Posted on March 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related