7. Conditional statements

Quiz: 0/5

Imagine writing a story where the plot twists depend on the reader's choices. Python's conditional statements let you do something similar: you instruct the computer, “If this happens, do that; otherwise, do something else.” This ability allows your programs to dynamically adapt to different situations.

What are conditional statements?

Conditional statements control the flow of your program by specifying rules for what should happen under different circumstances. Python provides three main tools for this logic:

  • if: Checks a condition.
  • elif (short for "else if"): Adds more conditions to check.
  • else: Provides a fallback for when no conditions are met.

The if statement: Asking "what if?"

The if statement evaluates a condition. If the condition is true, the code inside the if block runs. Otherwise, Python skips it.

temperature = 30

if temperature > 25:
    print("It's a warm day!")

Explanation:

  • Python checks if the temperature is greater than 25.
  • If true, it prints: "It's a warm day!"
  • If false, it skips the block entirely.

The else statement: A backup plan

The else statement ensures your program has a fallback if the if condition isn’t met.

temperature = 15

if temperature > 25:
    print("It's a warm day!")
else:
    print("It's a cool day.")

Explanation:

  • If the temperature is greater than 25, Python prints: "It's a warm day!"
  • Otherwise, it prints: "It's a cool day."

The elif statement: Adding more choices

The elif statement introduces additional conditions. Python evaluates them in sequence until one is true.

temperature = 20

if temperature > 25:
    print("It's a warm day!")
elif temperature > 15:
    print("It's a mild day.")
else:
    print("It's a cool day.")

Explanation:

  1. If the temperature is greater than 25, it prints: "It's a warm day!"
  2. If not, it checks if the temperature is greater than 15. If true, it prints: "It's a mild day."
  3. If neither condition is true, it prints: "It's a cool day."

How if, elif, and else work together

  1. Python checks the if condition first.
  2. If the if condition is true, the associated block runs, and Python skips the rest.
  3. If the if condition is false, Python evaluates the next elif condition (if present).
  4. If no conditions are true, the else block (if present) executes.

Examples of conditional statements

Example 1: Even or odd numbers

number = 7

if number % 2 == 0:
    print("It's an even number!")
else:
    print("It's an odd number!")

Explanation:

  • The program checks if the number is divisible by 2 (i.e., no remainder).
  • If true, it’s even; otherwise, it’s odd.

Example 2: Grading system

grade = 85

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
else:
    print("D")

Explanation:

  • If the grade is 90 or above, it prints: "A".
  • If between 80 and 89, it prints: "B".
  • If between 70 and 79, it prints: "C".
  • If below 70, it prints: "D".

Best practices for conditional statements

Keep conditions clear

Write conditions that are straightforward and easy to understand.

# Good
if age >= 18:
    print("Adult")

# Confusing
if not (age < 18):
    print("Adult")

Avoid redundant checks

Use elif to avoid overlapping conditions.

# Good
if score >= 90:
    print("A")
elif score >= 80:
    print("B")

# Inefficient
if score >= 90:
    print("A")
if score >= 80 and score < 90:
    print("B")

Use descriptive variable names

Choose meaningful names to make your code readable.

temperature = 30  # Clear
t = 30            # Vague

Conclusion

Conditional statements (if, elif, else) are fundamental tools for decision-making in Python. They allow your programs to react to various scenarios, making them dynamic and interactive. By mastering these, you can build more intelligent and responsive applications. Keep practicing, and soon you’ll be writing code that adapts effortlessly to any situation!

Hands-On Practise

Exercise: Student performance analyzer

Write a Python program that evaluates a student’s performance based on their exam score and attendance percentage. Follow these rules:

  1. Define two variables:

    • score (integer) representing the student’s exam score.
    • attendance (integer) representing the student’s attendance percentage.
  2. Use conditional statements to determine and print:

    • If the score is 90 or above and attendance is 95% or above, print: "Excellent performance! Keep it up!"
    • If the score is 80 or above and attendance is 85% or above, print: "Great job! You’re doing well."
    • If the score is 70 or above or attendance is 80% or above, print: "Good effort, but there’s room for improvement."
    • If none of these conditions are met, print: "Needs improvement. Focus on your studies and attendance."

Challenge (Optional):

Add another condition: If the score is less than 50, print an additional message: "Consider seeking help from a tutor."

Output:

Quizzes: 0/5

Question 1:

Which keyword is used to specify an alternative condition in Python?

  • else
  • elif
  • if
  • switch

Question 2:

What will the following code print? `python temperature = 20 if temperature > 25: print("It's hot") else: print("It's cold") `

  • It's hot
  • It's cold
  • Error
  • Nothing

Question 3:

Which of the following statements is true about the 'else' keyword?

  • 'else' can only appear once in an if-elif-else block
  • 'else' is optional in an if-elif-else block
  • 'else' executes only when no previous conditions are true
  • All of the above

Question 4:

What does the following code output? `python grade = 85 if grade >= 90: print("A") elif grade >= 80: print("B") elif grade >= 70: print("C") else: print("D") `

  • A
  • B
  • C
  • D

Question 5:

Which logical operator checks if both conditions are true?

  • or
  • and
  • not
  • ==

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonComparison and logical OperatorsNext lessonLoops: Automating repetition