In Python, the
if
statement is used for conditional execution of code. It allows you to execute a block of code if a specified condition is true. Here’s the basic syntax of theif
statement:
if condition:
# code to be executed if the condition is true
Here’s a simple example:
x = 10
if x > 5:
print("x is greater than 5")
In this example, the print
statement will only be executed if the condition x > 5
is true.
You can also use the
else
andelif
(short for “else if”) statements to handle multiple conditions. Here’s an example:
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
In this example, the first condition is checked. If it’s true, the corresponding block of code is executed. If the first condition is false, the elif
condition is checked, and if that’s true, its corresponding block is executed. If neither the if
nor elif
conditions are true, the else
block is executed.
You can also use logical operators (and
, or
, not
) to combine multiple conditions. Here’s an example:
x = 5
y = 12
if x > 0 and y > 10:
print("Both conditions are true")
else:
print("At least one condition is false")
In this example, the
and
operator is used to check if bothx > 0
andy > 10
are true. If they are, the corresponding block of code is executed. If not, theelse
block is executed.Photo by Hitesh Choudhary on Unsplash