Lightning bolt and Python code snippet with "Python If Statements" in blocky caps

Python If Statements

We need a way of making our programs behave differently in different scenarios. Somehow we need to control the flow of the commands we have written.

What is Control Flow?

Control flow refers to the order in which instructions in a program are executed. By default, Python runs the code line by line from top to bottom. But, sometimes you want to change this based on certain conditions or inputs. This is where conditional statements come into play.

If Statements

An if statement allows you to check a condition (an expression that evaluates to True or False) and execute a block of code if the condition is True.

Basic Syntax:

if condition:
    # Code to run if the condition is True
  • condition: A comparison or expression that evaluates to True or False.
  • Indentation: The code inside the if block must be indented (typically 4 spaces). This tells Python that this block of code is related to the if statement.

Example:

age = 18

if age >= 18:
    print("You are an adult.")

In this example, if the value of age is 18 or more, Python will print “You are an adult.” If age is less than 18, nothing will happen because no other instructions are given for when the condition is False.

Else Statements

An else statement provides an alternative block of code to run if the if condition is False. It ensures that one of the two blocks of code runs, no matter what.

Syntax:

if condition:
    # Code to run if the condition is True
else:
    # Code to run if the condition is False

Example:

age = 16

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

If age is less than 18, Python will print “You are a minor.” The else block ensures there is a response even if the initial condition is not met.

Elif Statements

You can chain multiple conditions using elif (short for “else if”). This allows you to check several conditions in sequence.

Syntax:

if condition1:
    # Code to run if condition1 is True
elif condition2:
    # Code to run if condition2 is True
else:
    # Code to run if both conditions are False

Example:

age = 15

if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
else:
    print("You are a child.")

In this example:

  • If age is 18 or more, Python prints “You are an adult.”
  • If age is between 13 and 17, it prints “You are a teenager.”
  • If age is less than 13, it prints “You are a child.”

Combining Conditions with Logical Operators

You can combine multiple conditions using logical operators: and, or, and not.

1. And Operator:

Both conditions must be True for the overall expression to be True.

age = 25
income = 50000

if age > 18 and income > 30000:
    print("You are eligible for the loan.")

In this example, both age > 18 and income > 30000 must be true for the message to be printed.

2. Or Operator:

At least one of the conditions must be True for the overall expression to be True.

age = 17
permission = True

if age >= 18 or permission:
    print("You can enter the event.")

In this case, either the age must be 18 or higher, or permission must be True for the message to be printed.

3. Not Operator:

The not operator reverses the result of a condition. If the condition is True, it becomes False, and vice versa.

is_raining = False

if not is_raining:
    print("It's a sunny day!")

Here, the message “It’s a sunny day!” is printed because not False becomes True.

Nesting If Statements

You can place an if statement inside another if statement. This is called nesting.

Example:

age = 20
is_student = True

if age >= 18:
    if is_student:
        print("You are eligible for a student discount.")
    else:
        print("You are not eligible for a student discount.")

In this case, Python checks if age >= 18. If True, it then checks if is_student is True. If both conditions are met, the message “You are eligible for a student discount” is printed. Otherwise, it prints the other message.

Example: Building a Simple Program

Let’s build a simple program that checks whether a user can ride a rollercoaster based on their height and age.

Rollercoaster Eligibility Program:

# Get user input
height = int(input("Enter your height in cm: "))
age = int(input("Enter your age: "))

# Check eligibility
if height >= 120:
    if age >= 8:
        print("You can ride the rollercoaster!")
    else:
        print("You are too young to ride the rollercoaster.")
else:
    print("You are not tall enough to ride the rollercoaster.")

How it works:

  • The program first asks the user for their height and age.
  • If the height is 120 cm or more, it then checks if the user is 8 or older.
  • Depending on these conditions, it prints whether or not the user can ride the rollercoaster.

Using the Pass Statement

In some cases, you might need to include an if statement but don’t want to write any code inside it (yet). For this, you can use the pass statement, which acts as a placeholder and does nothing.

Example:

age = 17

if age >= 18:
    pass  # You can add code here later
else:
    print("You are under 18.")

Key Concepts Recap

  • If statements allow you to execute code based on a condition. If the condition is True, the code inside the if block runs.
  • Use else to define code that should run when the if condition is False.
  • Use elif to check additional conditions after an initial if condition fails.
  • Logical operators like and, or, and not allow you to combine multiple conditions.
  • Nesting allows you to place if statements inside other if statements to create more complex decision-making structures.

Exercises

  1. Write a program that checks whether a person is eligible to vote (age must be 18 or above).
  2. Create a program that asks the user for a number and checks if the number is positive, negative, or zero.
  3. Write a program that checks if a student’s grade is an A, B, C, D, or F based on their score (out of 100).
  4. Create a program that checks if two input numbers are both positive or at least one of them is negative.

Next time, we’ll learn about loops, which allow you to execute blocks of code multiple times under certain conditions.

FAQ

Q1: What happens if I don’t include the else statement in an if block?

A1: The else statement is optional in Python. If you omit the else statement, nothing happens when the if condition evaluates to False. Python will simply move on to the next block of code. For example:

age = 16
if age >= 18:
    print("You are an adult.")
# No else block, so nothing happens if age < 18

In this case, when age is 16, nothing is printed because the if condition is False and there is no else block.

Q2: Can I use multiple elif statements in an if block?

A2: Yes, you can use multiple elif statements to check for multiple conditions in sequence. Python will evaluate each condition one by one from top to bottom and execute the first block where the condition is True. If none of the conditions are True, the else block (if present) will be executed.

Example:

score = 85

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

In this example, score is 85, so “Grade: B” is printed. Only the first True condition is executed, even if other conditions could also be True.

Q3: What is the purpose of the Pass statement in an If block?

A3: The pass statement is a placeholder that tells Python to “do nothing.” It’s useful when you’re writing code and need to define an if, elif, or else block without adding functionality right away. This prevents syntax errors when you don’t have code to execute yet but still need a valid block.

Example:

age = 20

if age >= 18:
    pass  # Placeholder, code can be added here later
else:
    print("You are a minor.")

Without the pass statement, Python would raise an error because the if block is empty.

Q4: Can I combine multiple conditions in an if statement?

A4: Yes, you can combine multiple conditions using logical operators like and, or, and not. This allows you to check more complex conditions in a single if statement.

  • and: Both conditions must be True.
  • or: At least one condition must be True.
  • not: Reverses the boolean value of a condition.

Example:

age = 25
income = 45000

if age > 18 and income > 30000:
    print("You are eligible for the loan.")

In this case, both conditions (age > 18 and income > 30000) must be True for the code block to execute.

Q5: What’s the difference between elif and else?

A5: The elif (short for “else if”) statement allows you to check additional conditions if the previous if condition is False. The else statement, however, acts as a “catch-all” for when none of the previous conditions are True. You can have multiple elif statements, but only one else statement, and it must come at the end of the chain.

Example:

temperature = 30

if temperature > 35:
    print("It's too hot.")
elif temperature < 15:
    print("It's too cold.")
else:
    print("The temperature is just right.")

Here, the else block runs only if none of the if or elif conditions are met.

Q6: What happens if two conditions are True in an if-elif block?

A6: Python will only execute the first True condition it encounters in an if-elif block. Once a condition is met and its block runs, Python ignores the rest of the elif and else blocks, even if their conditions could also be True.

Example:

score = 95

if score >= 90:
    print("Excellent")
elif score >= 80:
    print("Good")

Even though score >= 80 is also True, Python executes the first condition (score >= 90) and then exits the block, so “Excellent” is printed.

Q7: Can I use an if statement inside another if statement?

A7: Yes, you can nest if statements inside each other. This is called nesting, and it’s useful when you want to check multiple levels of conditions.

Example:

age = 25
is_student = True

if age >= 18:
    if is_student:
        print("You are eligible for a student discount.")
    else:
        print("You are not eligible for a student discount.")

In this case, the program first checks if age is 18 or above. If that’s True, it then checks if is_student is True and prints the appropriate message.

Q8: What does the not operator do in an if statement?

A8: The not operator inverts the result of a condition. If the condition is True, not makes it False, and vice versa. This is useful when you want to check for the opposite of a condition.

Example:

is_raining = False

if not is_raining:
    print("It's a sunny day!")

Since is_raining is False, the not operator makes the condition True, so “It’s a sunny day!” is printed.

Q9: What happens if I forget to indent the code inside an if statement?

A9: In Python, indentation is crucial. If you forget to indent the code inside an if block, Python will raise an IndentationError. This error occurs because Python uses indentation to determine which code belongs inside the if block.

Example of incorrect code:

age = 20

if age >= 18:
print("You are an adult.")  # This line should be indented

Python will raise an error because print("You are an adult.") is not properly indented.

Q10: How do I handle multiple conditions that depend on each other?

A10: You can handle multiple interdependent conditions using nested if statements or logical operators (and, or, not). Nesting is useful when each condition depends on the result of the previous one.

Example of using nesting:

age = 21
is_student = False

if age >= 18:
    if is_student:
        print("Eligible for student discount")
    else:
        print("No student discount")

In this case, the second if condition only runs if the first if condition (age >= 18) is True.

Similar Posts