Conditions in Python
Conditions in Python allow a program to make decisions based on checking the truth of logical expressions. Imagine that your program has reached a fork in the road: depending on where you need to go, it will choose one of the paths. This is one of the fundamental elements of programming, which allows you to execute different parts of the code depending on different circumstances. In Python, the if, elif and else operators are used to create such "forks".
Syntax
Conditions in Python are defined using the keywords if, elif and else. These operators allow code blocks to be executed depending on whether the expression being checked is true or false.
IMPORTANT! After the condition itself (if condition: or elif condition:) and else is always followed by a colon (:).
if condition:
# a block of code that will be executed if the condition is true
else:
# another block of code that will be executed if the condition is false
Indentation in Python is not just a beauty, it's part of the syntax! Unlike many other languages where curly braces {} are used to group code, Python uses indentation (usually 4 spaces) for this purpose. It is the indentation that shows which lines of code belong to if and which to else. All lines within the same block must have the same indentation.
A useful tip: The most common mistake of beginners is mixing spaces and tabs to create indents. This may result in the IndentationError error. Set up your code editor so that it automatically replaces tabs with 4 spaces.
x = 10
if x > 5:
print("x is greater than 5") # This code is inside the if block, it will be executed.
y = x - 5 # And this line is also inside the if block.
# Nested condition: validation within validation
if y < 3:
# This line has even more indentation, it belongs to the nested if.
print("y is less than 3")
else:
# This code will be executed only if the condition 'x > 5' is false.
print("x is not more than 5")
Basic condition operators
- if: Executes a block of code if its condition is true (
True). This is the "main" check.
- elif: (short for "else if") Checks its condition only if all previous checks
if and elif turned out to be false.
- else: Executes its code block if all the previous conditions (
if and all elif) are false. The else block is optional.
Let's look at some examples.
x = 10
if x > 5: # Condition 10 ;gt; 5 is True.
print("x is greater than 5") # This code will be executed.
Now the bundle is with else. Only one of the blocks is executed: either if or else.
x = 3
if x > 5: # Condition 3 ;gt; 5 is False.
print("x is greater than 5") # This block will be skipped.
else:
print("x is not more than 5") # The program will go here and execute this code.
The elif operator allows you to check several conditions in a row. There can be any number of elif blocks. As soon as one of them turns out to be true, the whole construction will be completed.
x = 5
if x > 5: # Condition 5 > 5 is False.
print("x is greater than 5")
elif x == 5: # Condition 5 == 5 is true.
print("x is 5") # This block will be completed and the check will end.
else: # The program won't even look here, since the condition in elif has already been fulfilled.
print("x is less than 5")
A useful tip: The order of the elif matters! Python checks them from top to bottom. Place more specific and rigorous checks above, and more general checks below.
Comparison operators
Comparison operators are used inside conditions to compare two values. The result of their operation is always a boolean value: True (true) or False (false).
== Equal to
!= Not equal to
More
Less
>= Greater than or equal to
<= Less than or equal to
A useful tip: Do not confuse the comparison operator == with the assignment operator =! One of the most common mistakes. x = 5 is "putting the value 5 in the variable x". x == 5 is "to ask if the value in x is equal to five?".
x = 10
b = 17
c = 0
print(x > 9) # True
print(b <= 17) # True
print(c != 1) # True
print(x < 110) # True
print(b == 17) # True
print(c >= -10) # True
Checking for range membership (comparison chains)
If you need to check whether a number falls within a certain range, Python allows you to do this very gracefully using "comparison chains".
a = 17
# Check that 'a' is in the range from 10 to 100 inclusive.
print(10 <= a <= 100) # True
This is a more readable and pythonic entry than a > = 10 and a <= 100.
# You can build more complex chains.
# This entry verifies that 200 is gt; 17 and 17 is lt; 100.
print(200 > a < 100) # True
Logical operators: and, or, not
It is often necessary to check not one, but several conditions at once. Logical operators are used for this purpose.
- and (boolean "And"): Returns
True only if both conditions are true.
- or (boolean "OR"): Returns
True if at least one of the conditions is true.
- not (logical "NOT"): Inverts a boolean value (changes
True to False and vice versa).
age = 25
has_license = True
# To drive a car, you must be over 18 and have a license.
if age >= 18 and has_license == True:
print("You can drive")
temperature = -5
is_weekend = True
# Let's go for a walk if it's warm outside OR it's a day off.
if temperature > 0 or is_weekend == True:
print("Great day for a walk!")