Computer Science Researcher • Educator • Programming Instructor
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.
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.
age = 18
if age >= 18:
print("You are an adult.")
Output:
You are an adult.
Python checks whether age is greater than or equal to 18. Since the condition is true, the message is displayed.
temperature = 20
if temperature > 25:
print("It's hot today.")
else:
print("It's cool today.")
Output:
It's cool today.
Since temperature is not greater than 25, Python executes the else block.
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
else:
print("Grade C")
Output:
Grade B
Python checks each condition from top to bottom. The first true condition is executed, and the remaining ones are ignored.
name = "Ali"
if name == "Ali":
print("Welcome, Ali")
else:
print("Unknown user")
Output:
Welcome, Ali
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.
1. What does an if statement do?
Repeats code2. Which keyword checks the second condition?
else3. What does else represent?
The first condition4. What is the output of: if 5 > 2: print("Yes")
Error5. Which operator checks equality?
=6. What is the output of: if 4 == 4: print("Match")
Error7. Which condition is true?
8 < 38. Which line checks if two strings are equal?
name = "Ali"9. What is the result of: if "A" == "a": print("Match")
Match10. Which block runs when all conditions are false?
if