Python is known for its simplicity and readability, making it an ideal language for beginners and professionals alike. One of the most fundamental concepts in Python programming is conditional statements, which allow your code to make decisions based on specific conditions. The if...else statement is the cornerstone of conditional programming in Python. This comprehensive tutorial will walk you through everything you need to know about using if...else in Python, complete with examples, explanations, and real-world applications.
The if...else statement is one of the most important control structures in Python. It allows your program to execute certain code based on whether a condition is True or False. You can use it to implement decision-making in your programs, making your code more flexible and capable of handling various scenarios.
Basic Structure:
if statement: Checks a condition, and if it is True, executes a block of code.else statement: Executes an alternative block of code if the condition is False.elif statement: Allows checking multiple conditions in a sequential manner.if StatementThe if statement allows you to test a condition and execute code if the condition is True.
if condition:
    # Code to execute if the condition is True
temperature = 25
if temperature > 20:
    print("It's warm outside.")
if statement checks whether the temperature is greater than 20.True, it executes the code inside the if block.else with ifThe else statement provides an alternative block of code to execute if the if condition is False.
if condition:
    # Code to execute if the condition is True
else:
    # Code to execute if the condition is False
temperature = 15
if temperature > 20:
    print("It's warm outside.")
else:
    print("It's cold outside.")
elif for Multiple ConditionsThe elif statement allows you to check multiple conditions, where each condition is checked in sequence.
if condition1:
    # Code to execute if condition1 is True
elif condition2:
    # Code to execute if condition2 is True
else:
    # Code to execute if all conditions are False
temperature = 30
if temperature > 30:
    print("It's very hot outside.")
elif temperature > 20:
    print("It's warm outside.")
else:
    print("It's cold outside.")
elif condition is checked only if the previous if or elif condition is False.if StatementsNested if statements are if statements within another if block. This allows you to check additional conditions within an existing condition.
temperature = 25
humidity = 70
if temperature > 20:
    if humidity > 60:
        print("It's warm and humid outside.")
    else:
        print("It's warm but not humid.")
else:
    print("It's cold outside.")
Explanation:
if...else (Ternary Operator)The ternary operator provides a shorthand way to write an if...else statement on a single line.
result = value_if_true if condition else value_if_false
temperature = 25
weather = "warm" if temperature > 20 else "cold"
print(weather)  # Output: warm
Explanation:
if...elseThe and operator requires both conditions to be True.
temperature = 25
humidity = 60
if temperature > 20 and humidity > 50:
    print("It's warm and humid outside.")
or OperatorThe or operator requires at least one condition to be True.
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
    print("It's a day off.")
not OperatorThe not operator inverts the condition.
is_raining = False
if not is_raining:
    print("It's not raining.")
if...elseComparison operators are essential for evaluating conditions in if...else statements.
| 
 Operator  | 
 Description  | 
 Example  | 
| 
 
  | 
 Equal to  | 
 
  | 
| 
 
  | 
 Not equal to  | 
 
  | 
| 
 
  | 
 Greater than  | 
 
  | 
| 
 
  | 
 Less than  | 
 
  | 
| 
 
  | 
 Greater than or equal to  | 
 
  | 
| 
 
  | 
 Less than or equal to  | 
 
  | 
age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
if...else with Boolean ExpressionsThe if...else statement can also work with Boolean expressions.
is_logged_in = True
if is_logged_in:
    print("Welcome back!")
else:
    print("Please log in.")
Explanation:
is_logged_in is True, the welcome message is displayed.Problem:
Write a program that checks if a user is old enough to drive.
age = int(input("Enter your age: "))
if age >= 18:
    print("You are eligible to drive.")
else:
    print("You are not eligible to drive.")
if statement checks if the user’s age is 18 or above.Problem:
Write a program that assigns grades based on a student’s score.
score = int(input("Enter your score: "))
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"Your grade is {grade}.")
elif statement checks a specific range, assigning a grade based on the score.if to check a condition, else to handle the False case, and elif to check multiple conditions.if...else statements for concise code.The if...else statement is a foundational concept in Python that enables your programs to make decisions. Whether you’re handling simple conditions with if, multiple conditions with elif, or a default case with else, mastering these statements will allow you to build more dynamic and responsive applications.
By understanding if...else, you’ll be able to: