In this lesson, we will explore the fundamental concept of Control Flow in Python, specifically focusing on how programs make decisions. You will learn how to use conditional statements to perform different actions based on whether specific criteria are met, transforming your code from a static script into a responsive tool.
Before writing an if statement, you must understand the boolean data type. In Python, a Boolean is a value that is either True or False. When you ask the computer a question, it evaluates the expression and returns one of these two values.
To compare values, we use comparison operators:
== (Equal to)!= (Not equal to)> (Greater than)< (Less than)>= (Greater than or equal to)<= (Less than or equal to)These operations are the building blocks of all program logic. For example, if you are checking a user's age to see if they are eligible for a discount, the expression age >= 65 will evaluate to True if the user is 65 or older, and False otherwise.
Note: A common mistake for beginners is using the single equals sign
=for comparisons. Remember that=is for assignment (setting a variable), while==is for comparison (asking a question).
The if statement acts as a gateway in your code. If the condition provided is True, the code indented underneath the if statement will run. If it is False, Python skips that block entirely.
The most important syntax rule here is the indentation. In Python, you must indent the code inside the if block (usually by 4 spaces). This tells Python exactly which lines are part of the decision. Without this indentation, your program will throw an IndentationError.
temperature = 85
if temperature > 80:
print("It is a hot day!")
print("Remember to drink water.")
If temperature were 70, neither print statement would execute. This allows you to group multiple lines of code that should only trigger when a specific condition is met.
Real-world logic is rarely binary. Often, you need to handle multiple scenarios. This is where else and elif (short for else if) come into play.
else: Provides a fallback option. If the initial if condition is False, the else block runs.elif: Allows you to check additional conditions if the previous if or elif conditions were False.Consider a grading program:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or below")
Python checks these from top to bottom. It stops at the first True condition it finds. If the score is 85, it skips the first if (because 85 is not >= 90), enters the elif, prints "Grade: B", and then exits the entire structure entirely.
Sometimes a single condition isn't enough. You can combine multiple conditions using logical operators: and, or, and not.
and: Results in True only if both sides are True.or: Results in True if at least one side is True.not: Reverses the boolean value (e.g., not True becomes False).For example, to check if a person is a teenager (between 13 and 19):
age = 15
if age >= 13 and age <= 19:
print("You are a teenager.")
Using these operators allows you to build highly complex and precise logic within your programs.
When writing if statements, keep your logic readable. Avoid "deep nesting"—putting too many if statements inside other if statements. If you find your code moving too far to the right side of the screen, it is often a sign that you should simplify your logic.
A common pitfall is the logic error. This happens when your code is syntactically correct but doesn't do what you intended. For instance, testing if x > 10 and x < 5 will never execute, because no number can be simultaneously greater than 10 and less than 5. Always double-check your conditions with mental test cases.
True or False and are the foundation of decision-making.if block.elif and else to create multi-path logic that handles more than one outcome.and, or, not) help you combine multiple conditions to create complex rules.Conditional statements define the logic that allows a program to respond dynamically based on specific criteria. Explain the functional difference between an assignment operator and a comparison operator, and describe why indentation is a critical requirement when defining the logic within an if statement block. Additionally, imagine you are writing a program to check if a user is old enough to vote; write a brief explanation of how you would structure the condition using comparison operators and what role the Boolean result plays in executing the subsequent code.