Up until now, the Python code scripts you have written have run in a straight, predictable line. The computer starts at line 1, executes it, moves to line 2, and continues downward until it hits the end of the file. However, real-world software needs to make decisions based on changing data.
Think of conditional logic like a real-world scenario: If it is raining outside, you take an umbrella. Else (if it is clear), you leave the umbrella at home. In Python, we use If and Else statements to act as traffic controllers in our scripts. They evaluate whether a specific condition is true or false, and then force the program to run different paths of code based on that calculation.
To write an if statement, you use the if keyword, state a logical condition, and finish the line with a trailing colon :.
The most critical structural detail here is Python's use of indentation. Any lines of code that should run only when the condition is met must be spaced forward by 4 spaces (or one tab). If you forget to indent your code blocks, Python will fail to understand the layout structure and throw an immediate error.
# Setting up a simple entry filter system
user_age = 20
if user_age >= 18:
print("Access Granted!") # Indented: Runs only if age is 18+
else:
print("Access Denied!") # Indented: Runs only if age is under 18
To build conditions for your if statements, you need tools to compare variables against numbers or text strings. Python gives us a clean collection of math-based comparison operators that always calculate down to a strict Boolean value (True or False):
== (Is Equal To): Checks if two values match perfectly. Be careful not to use a single equals sign (=), which is only used for assigning variables!!= (Is Not Equal To): Checks if two data points are completely different.> and <: Greater than and less than comparisons.>= and <=: Greater than or equal to, and less than or equal to.What happens if your application has more than just two choices? For instance, a video game might need to hand out Gold, Silver, or Bronze medals depending on a player's rank.
To handle three or more distinct directions, Python introduces the elif keyword (short for "else if"). You can string together as many elif checks as your app requires, and Python will evaluate them sequentially from top to bottom until it finds the first match.
exam_score = 85
if exam_score >= 90:
print("Grade: A")
elif exam_score >= 80:
print("Grade: B") # This path is selected and executed
elif exam_score >= 70:
print("Grade: C")
else:
print("Grade: F") # Fallback path if all statements fail
Conditional syntax transitions can lead to a few frequent logic errors for beginners:
: at the end of an if, elif, or else line is the number one cause of syntax errors in beginner scripts.
if score = 100: will cause your app to crash instantly. Remember to always use the double equals operator == when checking for exact equivalence.
Let's write some code! Open your local editor and try this exercise:
Create a variable named temperature and assign it an integer value representing degrees.
Write an if statement that prints "It is hot!" if the value is greater than 30.
Add an elif block to print "It is nice!" if the value is greater than 15.
Finally, add an else block to fallback and print "It is cold!" if all other conditions fail.