Previous | Tutorial index | Next
if Statement – Making a Single DecisionTo be able to use an if statement to run a code block only when a specific condition is True.
In programming, a condition is any expression that Python can evaluate as either True or False. This data type is called a Boolean (named after George Boole).
True, the code inside the if block executes.False, Python completely ignores that block and continues with the rest of the program.if StatementVisualizing code helps a lot. Here is how an if statement flows:
[ Start ]
|
v
[Check Condition]
|
+----+----+
| |
True False
| |
v |
[Run Indented] |
| |
+----+----+
|
v
[Continue with
rest of program]
In Python, the if statement doesn't only work with True or False. It also checks for "truthiness":
0, None, "" (empty string), [] (empty list) are treated as False.1, -5, "Hello", [1, 2, 3]) are treated as True.Example:
if "Python":
print("This will print, because a non-empty string is truthy!")
Beginner Tip: For now, always write clear comparisons (e.g.,
if age > 12:) rather than relying on truthiness, to make your code easier to read.
input() and Type Conversioninput() function always returns a string (text), even if the user types a number.int().Incorrect (Causes an error or wrong logic):
age = input("Enter age: ") # age is a string, e.g., "15"
if age > 12: # ERROR! Can't compare string to int.
print("Teenager")
Correct:
age = int(input("Enter age: ")) # Converts to integer
if age > 12:
print("Teenager")
if condition:
# Code to run if condition is True
do_something()
# Code here runs regardless (outside the if block)
temperature = 30
if temperature > 25:
print("It's a hot day! Drink water.")
print("This line always runs.")
Output:
It's a hot day! Drink water.
This line always runs.
temperature = 20
if temperature > 25:
print("It's a hot day!") # This is completely skipped
print("Goodbye.") # This runs normally
Output:
Goodbye.
Python comparisons are case-sensitive. "hello" is not the same as "Hello".
user_input = "Yes"
if user_input == "yes": # Checks for lowercase 'yes'
print("Confirmed!")
print("Program ended.")
Output: Program ended. (Because "Yes" does not equal "yes").
number = 10
if number % 2 == 0: # % is the modulo operator (remainder after division)
print(f"{number} is an even number.")
Output: 10 is an even number.
| Operator | Meaning | True Example | False Example |
|---|---|---|---|
> |
Greater than | 10 > 5 |
4 > 8 |
< |
Less than | 3 < 7 |
9 < 2 |
>= |
Greater than or equal to | 5 >= 5 |
4 >= 6 |
<= |
Less than or equal to | 3 <= 3 |
7 <= 2 |
== |
Equal to (VALUE check) | "Hi" == "Hi" |
"Hi" == "hi" |
!= |
Not equal to | 5 != 3 |
5 != 5 |
Critical Rule:
=is for assigning a value (e.g.,x = 10).==is for checking if two things are equal. Never mix them up inside anif!
The Missing Colon (:)
if temperature > 25 (No colon)SyntaxError: invalid syntax: at the end of the if line.Inconsistent Indentation
Python strictly uses indentation to know which code belongs to the if.
Wrong:
if x > 5:
print("Big!") # Not indented
Error: IndentationError: expected an indented block
Fix: Use exactly 4 spaces (or 1 Tab, but never mix them) for the code inside the if.
Comparing Different Data Types
if age > "12": (Comparing int to str)TypeError: '>' not supported between instances of 'int' and 'str'int(input()) to convert user input to a number before comparing.Floating Point Precision
0.1 + 0.2 == 0.3 is actually False in Python!abs(0.1 + 0.2 - 0.3) < 0.0001), though for this tutorial, stick to integers.Q1: Which keyword starts a conditional statement in Python?
conditionifwhenloopQ2: The code inside an if statement must be __________ to the right.
ifQ3: The expression "apple" == "Apple" evaluates to:
TrueFalseQ4: What is the output of:
score = 85
if score >= 90:
print("A")
print("Done")
ADoneA and DoneQ5: What is printed?
x = 0
if x:
print("Hello")
print("World")
Hello then WorldWorld onlyHello onlyExercise 1: Positive Numbers
Write a program that asks the user for a number. If the number is greater than 0, print "The number is positive."
num = float(input("Enter a number: "))
if num > 0:
print("The number is positive.")
Exercise 2: Letter Hunter
Ask for a word. If it contains the letter "z", print "This word has a 'z'!".
word = input("Enter a word: ")
if "z" in word:
print("This word has a 'z'!")
Exercise 3: Divisible by 5
Ask for an integer. If it is divisible by 5, print "This number is a multiple of 5."
num = int(input("Enter an integer: "))
if num % 5 == 0:
print("This number is a multiple of 5.")
Exercise 4: Freezing Alert
Ask for a temperature in Celsius. If it is below 0, print "Warning: Freezing conditions!"
temp = float(input("Enter temperature (°C): "))
if temp < 0:
print("Warning: Freezing conditions!")
Exercise 5: Adult Check
Ask for age. If 18 or older, print "You are eligible to vote."
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
This homework combines code prediction, bug fixing, and writing original programs. Submit your .py files or written answers.
Write down the exact output of the following snippets without running them.
Snippet 1:
price = 100
if price > 50:
print("Expensive")
print("Checkout")
Snippet 2:
name = "Alice"
if name == "alice":
print("Welcome back, Alice!")
print("System ready.")
Snippet 3:
count = 5
if count:
print("There are items.")
else:
# Wait, there is no else! Let's just see what happens.
pass
print("Done")
The following programs have syntax errors or logic errors. Fix them so they run correctly. Explain what was wrong and write the corrected version.
Buggy Code 1:
user_age = input("Enter age: ")
if user_age >= 18
print("Adult")
Problems:
: after the if condition.input() returns a string, but we are comparing it to an integer (18) – this causes a TypeError.Corrected Code:
user_age = int(input("Enter age: "))
if user_age >= 18:
print("Adult")
Buggy Code 2:
temperature = 30
if temperature > 25
print("It's warm.")
Problems:
: after the if condition.print statement is not indented – Python will raise an IndentationError because it expects a block inside the if.Corrected Code:
temperature = 30
if temperature > 25:
print("It's warm.")
Buggy Code 3:
answer = "Yes"
if answer = "Yes":
print("Confirmed")
Problem: Using the assignment operator = inside the if condition instead of the equality comparison operator ==. This will raise a SyntaxError.
Corrected Code:
answer = "Yes"
if answer == "Yes":
print("Confirmed")
Write complete Python programs for each of the following tasks. Use only the concepts covered so far (variables, input(), int(), and only if statements – no else or elif are allowed in these tasks).
Task 1: The Lucky Number
Write a program that asks the user to guess a secret number. If the user guesses exactly 42, print "You guessed the secret number!". If they guess anything else, the program should simply end quietly (do nothing).
guess = int(input("Guess the secret number: "))
if guess == 42:
print("You guessed the secret number!")
Task 2: Password Strength Checker (Basic) Ask the user to create a password.
"admin123", print "Secure password set.""Password cannot be empty."if statements (not elif).password = input("Create a password: ")
if password == "admin123":
print("Secure password set.")
if password == "":
print("Password cannot be empty.")
Task 3: The Weekend Checker
Ask the user for today's date as a number (e.g., 1 for Monday, 7 for Sunday). Using only if statements (one for Saturday, one for Sunday), print "It's the weekend!" if the date is 6 or 7. Otherwise, print nothing.
date = int(input("Enter today's date (1=Mon, 7=Sun): "))
if date == 6:
print("It's the weekend!")
if date == 7:
print("It's the weekend!")
Add a third if statement to Task 3 that prints "Invalid day" if the user enters a number outside the range 1 to 7.
date = int(input("Enter today's date (1=Mon, 7=Sun): "))
if date == 6:
print("It's the weekend!")
if date == 7:
print("It's the weekend!")
if date < 1 or date > 7:
print("Invalid day")
(Note: This uses or, which is covered in Tutorial 5 – a great preview!)
Before moving to Tutorial 2, ensure you can confidently answer:
Once you've finished the quizzes, exercises, and homework, you're ready for Tutorial 2: The if-else Statement. Happy coding!