Python if-else Statement

In Python, if-else is a conditional statement that executes a block of code if a specified condition is true, and another block of code if the condition is false.

Syntax

if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the conditon is False

The else clause is optional.

Example:

age = 20

if age >= 18:
    print("Welcome to the club")
else:
    print("You are not eligible to enter")

Output:

Welcome to the club

In this example, the variable age is assigned a value 20.

The if statement checks whether the condition age >= 18 (i.e., whether the person’s age is 18 or older) is True.

Since, 20 is greater than 18, the condition evaluates to True, so the code inside the if block runs, and the message "Welcome to the club" is printed.

If the value of age had been less than 18, the condition would have been False, and the code inside the else block would execute instead, printing the message "You are not eligible to enter".

Handling Multiple Conditions With elif

If you need to check multiple conditions in sequence, you can use the elif (short for "else if") statement. You can have as many elif blocks as necessary to handle different conditions.

For example:

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Output:

Grade: B

In this example, the variable score is assigned a value 85.

The first condition score >= 90 checks if the score is greater than or equal to 90. Since, 85 is not greater than or equal to 90, this condition is False, so Python skips this code block.

The next condition score >= 80 checks if the score is greater than or equal to 80. Since, 85 is greater than 80, this condition is True, so the code statement inside this block executes, printing "Grade: B".

Once a condition evaluates to True, Python skips all the remaining elif and else blocks without checking them.

One Line if-else (Ternary Operator)

A ternary operator is a shorthand way to write an if-else statement in a single line.

The general syntax is:

x = value_if_true if condition else value_if_false

Example:

age = 15

status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Minor

In this example, the variable age is assigned the value 15.

The expression status = "Adult" if age >= 18 else "Minor" uses a ternary conditional operator to assign a value to the variable status in a single line.

If the condition age >= 18 is True, status will be assigned the value "Adult". Otherwise, it will be assigned "Minor".

In our case, the age is 15, which is less than 18, the condition evaluates to False, so status is assigned the value "Minor".

Logical Operators With if-else Statements

Logical operators are used to combine multiple conditional statements.

There are 3 logical operators in Python:

  • and : Returns True only if all conditions are true.
  • or : Returns True if at least one of the conditions is true.
  • not : Inverts the result of a condition, returns True if the condition if false, and False if the condition is true.

Using and

Use and when you want your program to do something only if all conditions are true at the same time.

For example:

age = 30
salary = 60000

if age >= 18 and salary >= 50000:
    print("Loan Application Accepted")
else:
    print("Loan Application Denied")

In this example, there are two variables: age set to 30 and salary set to 60000.

The if statement checks two conditions at once using the and operator:

  • The condition age >= 18 checks if the age is greater than or equal to 18.
  • The condition salary >= 50000 checks if the salary is greater than or equal to 50000.

Both of these conditions must be true for the code inside the if block to run.

In our case, age is 30 (which is more than 18) and salary is 60000 (which is more than 50000), the condition is True. So, the program prints "Loan Application Accepted".

If either condition were false (e.g., if the age was less than 18 or the salary was below 50000), the program would print "Loan Application Denied".

Using or

Use or when you want your program to do something if at least one of the conditions is true.

Let’s change the salary variable from the above example to 40000 and see what happens:

age = 30
salary = 40000

if age >= 18 or salary >= 50000:
    print("Loan Application Accepted")
else:
    print("Loan Application Denied")

Output:

Loan Application Accepted

In this example, there are two variables: age set to 30 and salary set to 40000.

The if statement checks two conditions using the or operator:

  • The condition age >= 18 checks if the age is greater than or equal to 18.
  • The condition salary >= 50000 checks if the salary is greater than or equal to 50000.

With the or operator, only one of these conditions needs to be true for the code inside the if block to run.

In our case, age is 30 (which is more than 18), so the first condition is True.

Even though the salary (40000) is less than 50000, it doesn’t matter because only one condition is enough for the overall expression to be true.

Therefore, the program prints "Loan Application Accepted".

If both conditions were false (e.g., if the age was 15 and the salary was 40000), the program would print "Load Application Denied".

Using not

Use not to reverse a condition.

For example:

logged_in = False

if not logged_in:
    print("Please log in first")
else:
    print("Welcome to LivingWithCode.com")

Output:

Please log in first

In this example, the variable logged_in is set to False.

The if statement uses the not operator, which reverses the logical value of the condition that follows it.

Since, logged_in is False, not logged_in becomes True, so the code inside the if block runs.

Therefore, the program prints "Please log in first".

if logged_in were True, then not logged_in would be False, and the program would instead execute the code inside else block and print "Welcome to LivingWithCode.com".

Nested if-else Statements

A nested if-else means putting an if-else statement inside another if or else program. This allows you to check multiple conditions in sequence, depending on the result of the previous condition.

For example:

number = 15

if number > 0:
    print("The number is positive")
    if number % 2 == 0:
        print("It is an even number")
    else:
        print("It is an odd number")
else:
    print("The number is negative")

Output:

The number is positive
It is an odd number

In this example, the variable number is set to 15.

In the first if statement, the condition number > 0 checks if the number is greater than 0.

Since, 15 is greater than 0, the condition becomes True, so the code inside the if block runs and prints "The number is positive".

Inside this if block, there is another if-else statement that checks if the number is even by evaluating the condition number % 2 == 0 . The modulo operator (%) returns the remainder. If the remainder is 0 when dividing by 2, it means the number is even.

Since, 15 divided by 2 leaves a remainder (it is not evenly divisible), the condition becomes False, so the code inside the else block runs printing "It is an odd number".