Python Lesson: if, elif, else

1. What Are Conditional Statements?

Conditional statements allow your program to make decisions based on conditions that are either True or False.

1a Comparison Operators

Comparison operators return True or False.

print(5 == 5)
print(5 != 3)
print(5 > 3)
print(5 < 3)
print(5 >= 5)
print(5 <= 4)

    
print(True and False)
print(True or False)
print(not True)
    

2. The if Statement

age = 18

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

3. The else Statement

else runs when the if condition is False.

age = 16

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

4. The elif Statement

elif means "else if" and allows multiple conditions.

score = 85

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

5. Using Comparison Operators

x = 10

if x == 10:
    print("x is ten")
    

6. Using Logical Operators

age = 20
has_id = True

if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")
    

7. Indentation Matters!

Python uses indentation to define blocks of code. Incorrect indentation will cause errors.

8. Common Mistakes

Python Conditional (if/else) Exercises

Complete the following exercises to reinforce your understanding of if statements.

Exercise 1: Even or Odd

Ask the user for an integer input. Write a program that prints whether the number is "Even" or "Odd" using an if-else statement [3].

Exercise 2: Grade Calculator

Ask the user for a numerical grade ($0$-$100$). Using if-elif-else, print the letter grade:

Exercise 3: Age Restriction

Define a variable age. If age is 18 or older, print "You are an adult." Otherwise, print "You are a minor."

Exercise 4: Logical Operators

Take two numbers from the user (x and y). Print "Both are positive" if both numbers are greater than 0, otherwise print "At least one number is not positive" [2, 7].

Exercise 5: Leap Year (Nested If)

Write a program that asks for a year and determines if it is a leap year. A year is a leap year if it is divisible by 4, but not by 100, unless it is also divisible by 400 [8].

Submit Code Here



9. Ready for the Quiz?

Take the if / elif / else Quiz