Lesson 7 – Conditions (if, elif, else)

Conditions allow your program to make decisions. Python checks whether something is true or false, and then executes the correct block of code. This is how programs respond to user input, compare values, and choose different actions.

How Do Conditions Work?

Python uses if, elif and else to test conditions. Each condition must be followed by a colon, and the code inside the block must be indented.

Example 1: What happens if a condition is true?

age = 18

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

Output:

You are an adult.
        

Explanation:

Python checks whether age is greater than or equal to 18. Since the condition is true, the message is displayed.

Example 2: What happens when a condition is false?

temperature = 20

if temperature > 25:
    print("It's hot today.")
else:
    print("It's cool today.")
        

Output:

It's cool today.
        

Explanation:

Since temperature is not greater than 25, Python executes the else block.

Example 3: How do multiple conditions work?

marks = 85

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

Output:

Grade B
        

Explanation:

Python checks each condition from top to bottom. The first true condition is executed, and the remaining ones are ignored.

Example 4: Can we compare strings?

name = "Ali"

if name == "Ali":
    print("Welcome, Ali")
else:
    print("Unknown user")
        

Output:

Welcome, Ali
        

Example 5: Using conditions with user input

number = int(input("Enter a number: "))

if number > 0:
    print("Positive number")
elif number == 0:
    print("Zero")
else:
    print("Negative number")
        

This program responds differently depending on what the user types.


Quiz: Test Your Understanding

1. What does an if statement do?

Repeats code
Makes a decision
Stores text
Prints shapes
Correct answer: Makes a decision

2. Which keyword checks the second condition?

else
elif
check
repeat
Correct answer: elif

3. What does else represent?

The first condition
A repeated block
A default action
A loop condition
Correct answer: A default action

4. What is the output of: if 5 > 2: print("Yes")

Error
Yes
5 > 2
False
Correct answer: Yes

5. Which operator checks equality?

=
==
!=
>
Correct answer: ==

6. What is the output of: if 4 == 4: print("Match")

Error
Match
4
False
Correct answer: Match

7. Which condition is true?

8 < 3
4 == 5
10 > 2
7 != 7
Correct answer: 10 > 2

8. Which line checks if two strings are equal?

name = "Ali"
name == "Ali"
print(name)
name = Ali
Correct answer: name == "Ali"

9. What is the result of: if "A" == "a": print("Match")

Match
Error
No output
Nothing happens
Correct answer: No output (condition is false)

10. Which block runs when all conditions are false?

if
elif
else
stop
Correct answer: else
Back to Top