Conditions
Introduction
Conditions are essential instructions in programming. They allow controlling the execution flow of a program based on certain conditions.
In Python, conditional structures allow performing tests and executing different parts of code based on the results of these tests.
Comparison and logical operators
Conditions in Python use comparison operators and logical operators to evaluate expressions.
Comparison operators
==
: equal to!=
: not equal to<
: less than>
: greater than<=
: less than or equal to>=
: greater than or equal to
Logical operators
and
: logical andor
: logical ornot
: logical not
if
Conditional structure
The basic structure for conditions in Python is the if
instruction.
x = 10
if x > 5:
print("x is greater than 5")
if...else
Conditional structure
The else
instruction allows defining a block of code that executes when the if
condition is false.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
if...elif...else
Conditional structure
The elif
instruction (contraction of "else if") allows testing multiple conditions in sequence.
x = 8
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is less than or equal to 5")
Nested conditions
Conditions can be nested to verify multiple conditions.
x = 7
y = 5
if x > 5:
if y > 3:
print("x is greater than 5 and y is greater than 3")
else:
print("x is greater than 5 but y is not greater than 3")
Using complex conditions
The and
, or
, and not
operators allow combining multiple conditions.
x = 4
y = 6
if x > 2 and y < 10:
print("x is greater than 2 AND y is less than 10")
if not(x > 5 or y > 10):
print("x is NOT greater than 5 OR y is NOT greater than 10")
Best practices
- Clarity: Avoid overly complex conditions. Use intermediate variables to clarify your code's intention.
- Testing: Always test your conditions with different sets of values to ensure they work correctly.