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.
Conditions in Python use comparison operators and logical operators to evaluate expressions.
== : equal to!= : not equal to< : less than> : greater than<= : less than or equal to>= : greater than or equal toand : logical andor : logical ornot : logical notifThe basic structure for conditions in Python is the if instruction.
x = 10
if x > 5:
print("x is greater than 5")
if...elseThe 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...elseThe 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")
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")
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")