Learning If Statements
What is an If Statement?
An if statement allows your program to make decisions. It checks whether a condition is true or false and runs a block of code accordingly.
Basic Syntax of an If Statement
if condition:
# Code to run if the condition is true
Example:
temperature = 25
if temperature > 20:
print("It's a warm day!")
Output:
It's a warm day!
Indentations and Blocks
Indentation is crucial in Python. It determines which code belongs to a specific block.
Example:
if True:
print("This is inside the block.") # Indented
print("This is outside the block.") # Not indented
Common Error:
If you forget to indent properly, Python will show an error:
if True:
print("This will cause an error!") # No indentation
If-Else Statement
An if-else statement allows you to provide an alternative block of code if the condition is false.
Syntax:
if condition:
# Code if condition is true
else:
# Code if condition is false
Example:
temperature = 15
if temperature > 20:
print("It's a warm day!")
else:
print("It's a cool day.")
Output:
It's a cool day.
Elif Statement
Use elif when you need to check multiple conditions. It stands for "else if."
Syntax:
if condition1:
# Code if condition1 is true
elif condition2:
# Code if condition2 is true
else:
# Code if none of the conditions are true
Example:
temperature = 0
if temperature > 20:
print("It's a warm day!")
elif temperature > 10:
print("It's a cool day!")
else:
print("It's a cold day!")
Output:
It's a cold day!
Practice Exercises
Exercise 1: Basic If
Write a program that checks if a number is positive and prints "The number is positive."
Exercise 2: If-Else
Write a program that asks for the user’s age. If the age is 18 or older, print "You can vote!" Otherwise, print "You are too young to vote."
Exercise 3: Elif
Write a program that asks for the number of hours you study daily:
If it’s more than 6 hours, print "You’re a study master!"
If it’s between 3 and 6 hours, print "Good job!"
If it’s less than 3 hours, print "Try to study more."
Bonus Challenge
Write a program that asks the user for the current temperature. Based on the input:
If it’s above 30°C, print "It’s hot!"
If it’s between 20°C and 30°C, print "It’s warm."
If it’s between 10°C and 20°C, print "It’s cool."
Otherwise, print "It’s cold!"
Congratulations!
Now you know how to use if statements, if-else, and elif in Python. These are essential tools for controlling your program's flow and making decisions. Keep practicing to master this skill! 🎉