TL ; DR:
if
statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:
is_rainy = True
if is_rainy:
print("I bring an umbrella")
It is mandatory to start the line after the if statement with a tab! For example, this code:
am_hungry = False
if am_hungry:
print("I have breakfast") # this produces an error
would throw an IndentationError
.
Full lesson:
As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:
If it's rainy:
I bring an umbrella
If I'm hungry:
I have breakfast
I I'm tired:
I take a nap
We can also tell the computer to make decisions like these in our programs.
If Statements:
if
statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:
if conditions:
# instructions
The keyword if
tells Python to execute the indented code coming after the colon :
(where we have our Python comment) only if the conditions
are met.
Boolean conditions:
The conditions inside if statements are known as Boolean conditions and they may only be True
or False
.
If the boolean condition evaluates to True
, the program executes the indented code coming after the colon. If it evaluates to False
, that code will not execute.
If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.
Let's turn those decisions into working code using if statements:
is_rainy = True
if is_rainy:
print("I bring an umbrella")
The code above prints "I bring an umbrella"
since the condition in the parentheses evaluates to True
But this code:
am_hungry = False
if am_hungry:
print("I have breakfast")
prints nothing since amHungry
evaluates to False
.
Assignment
Follow the Coding Tutorial and let's practice with if statements!
Hint
Look at the examples above if you get stuck.
In this lesson, we will explore the concept of if
statements in Python. If
statements are fundamental in programming as they allow us to make decisions based on certain conditions. This capability is crucial for creating dynamic and responsive programs. Whether you're developing a game, a web application, or a simple script, understanding how to use if
statements effectively is essential.
At its core, an if
statement evaluates a condition and executes a block of code only if that condition is true. This is known as conditional execution. The basic syntax of an if
statement in Python is:
if condition:
# code to execute if condition is true
Here, the condition
is a boolean expression that evaluates to either True
or False
. If the condition is true, the indented code block will run. If it is false, the code block will be skipped.
Let's break down the key concepts and techniques involved in using if
statements:
True
or False
. Examples include comparisons like 5 > 3
or checking the value of a variable like is_rainy == True
.if
statement must be indented.if
statement inside another if
statement to check multiple conditions.Let's look at some examples to understand how if
statements work in different contexts:
# Example 1: Simple if statement
temperature = 30
if temperature > 25:
print("It's a hot day")
# Example 2: Nested if statements
is_rainy = True
temperature = 20
if is_rainy:
if temperature < 15:
print("It's cold and rainy")
else:
print("It's warm and rainy")
In Example 1, the message "It's a hot day" will be printed because the condition temperature > 25
is true. In Example 2, the nested if
statement checks both the is_rainy
and temperature
conditions to print the appropriate message.
When working with if
statements, it's important to avoid common mistakes and follow best practices:
if
statement is properly indented. Incorrect indentation will lead to errors.Once you're comfortable with basic if
statements, you can explore advanced techniques such as:
elif
(short for "else if") to check multiple conditions in sequence.else
to execute a block of code if none of the previous conditions are true.and
, or
, and not
.# Example of elif and else
temperature = 15
if temperature > 25:
print("It's a hot day")
elif temperature > 15:
print("It's a warm day")
else:
print("It's a cold day")
Let's implement a more comprehensive example that demonstrates the use of if
statements:
# Function to determine what to wear based on weather conditions
def what_to_wear(is_rainy, temperature):
if is_rainy:
if temperature < 15:
return "Wear a raincoat and warm clothes"
else:
return "Wear a raincoat"
else:
if temperature < 15:
return "Wear warm clothes"
else:
return "Wear light clothes"
# Test the function
print(what_to_wear(True, 10)) # Output: Wear a raincoat and warm clothes
print(what_to_wear(False, 20)) # Output: Wear light clothes
In this example, the what_to_wear
function takes two parameters: is_rainy
and temperature
. It uses nested if
statements to determine the appropriate clothing based on the weather conditions.
When working with if
statements, debugging and testing are crucial to ensure your code works as expected:
unittest
or pytest
.import unittest
class TestWhatToWear(unittest.TestCase):
def test_rainy_and_cold(self):
self.assertEqual(what_to_wear(True, 10), "Wear a raincoat and warm clothes")
def test_rainy_and_warm(self):
self.assertEqual(what_to_wear(True, 20), "Wear a raincoat")
def test_not_rainy_and_cold(self):
self.assertEqual(what_to_wear(False, 10), "Wear warm clothes")
def test_not_rainy_and_warm(self):
self.assertEqual(what_to_wear(False, 20), "Wear light clothes")
if __name__ == '__main__':
unittest.main()
When approaching problems that require if
statements, consider the following strategies:
In this lesson, we covered the basics and advanced concepts of if
statements in Python. Mastering if
statements is essential for making decisions in your programs and creating dynamic, responsive code. Practice writing if
statements in different scenarios to strengthen your understanding and improve your problem-solving skills.
For further reading and practice, check out the following resources: