If Statements
If Statements
Sometimes a program should only do something when a condition is true.
For example:
- If it is raining, take an umbrella.
- If you are hungry, eat food.
- If the password is correct, log in.
Python uses if statements to make decisions like this.
What Is an If Statement?
An if statement checks a condition.
If the condition is true, Python runs the code below it.
age = 18
if age >= 18:
print("You are an adult")
Understanding the Example
Let’s break it down:
age = 18stores a valueage >= 18asks: is age greater than or equal to 18?- If the answer is
True, the message is printed
The Colon :
The colon tells Python that a block of code is starting.
if age >= 18:
Always add a colon after the condition.
Indentation
The spaces before the next line are called indentation.
Indented code belongs to the if statement.
if age >= 18:
print("Adult")
Without indentation, Python gives an error.
Another Example
score = 90
if score >= 50:
print("You passed")
If the Condition Is False
If the condition is false, Python skips the indented code.
age = 15
if age >= 18:
print("Adult")
Nothing is printed because the condition is false.
Code Along
temperature = 30
if temperature > 25:
print("It is hot today")
Mini Challenge
Build an age checker.
-
Create a variable called
age. -
If the age is 18 or higher, print:
-
You are old enough to drive
Real World Use Case
Websites use if statements to check passwords, age limits, account status, and many other decisions.
Quiz
- What does an
ifstatement do? - What happens if the condition is true?
- Why is the colon important?
- What is indentation?
Assignment
Create a program that stores a test score. If the score is 50 or more, print "Pass".
Summary
You learned how if statements help Python make decisions, how conditions work, and why colons and indentation are important.