If Statements in Python
TL ; DR:
ifstatements 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.
Introduction
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.
Understanding the Basics
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.
Main Concepts
Let's break down the key concepts and techniques involved in using if statements:
- Boolean Conditions: These are expressions that evaluate to
TrueorFalse. Examples include comparisons like5 > 3or checking the value of a variable likeis_rainy == True. - Indentation: Python uses indentation to define the scope of code blocks. The code inside an
ifstatement must be indented. - Nested If Statements: You can place an
ifstatement inside anotherifstatement to check multiple conditions.
Examples and Use Cases
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.
Common Pitfalls and Best Practices
When working with if statements, it's important to avoid common mistakes and follow best practices:
- Indentation Errors: Ensure that the code inside the
ifstatement is properly indented. Incorrect indentation will lead to errors. - Boolean Expressions: Make sure your conditions are valid boolean expressions. Avoid using non-boolean values directly in conditions.
- Readability: Write clear and readable conditions. Use parentheses to group complex expressions for better readability.
Advanced Techniques
Once you're comfortable with basic if statements, you can explore advanced techniques such as:
- Elif Statements: Use
elif(short for "else if") to check multiple conditions in sequence. - Else Statements: Use
elseto execute a block of code if none of the previous conditions are true. - Logical Operators: Combine multiple conditions using logical operators like
and,or, andnot.
# 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")
Code Implementation
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.
Debugging and Testing
When working with if statements, debugging and testing are crucial to ensure your code works as expected:
- Print Statements: Use print statements to check the values of variables and the flow of execution.
- Unit Tests: Write unit tests to verify the behavior of your functions. Use testing frameworks like
unittestorpytest.
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()
Thinking and Problem-Solving Tips
When approaching problems that require if statements, consider the following strategies:
- Break Down the Problem: Divide complex problems into smaller, manageable parts.
- Write Pseudocode: Outline your logic in plain language before writing actual code.
- Test Incrementally: Test your code step-by-step to catch errors early.
Conclusion
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.
Additional Resources
For further reading and practice, check out the following resources: