In Python, the if
statement is used to execute a block of code only if a specified condition is true. It's part of conditional statements that allow decision-making in code.
if condition:
# code to execute if the condition is true
x = 10
if x > 5:
print("x is greater than 5")
if
: This keyword introduces the condition.condition
: This is a logical statement that evaluates to True
or False
.:
: A colon follows the condition.else
You can add an else
statement to handle cases where the condition is not true:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
elif
for Multiple ConditionsThe elif
keyword allows testing multiple conditions:
x = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
You can use comparison operators (e.g., >
, <
, ==
, etc.) and logical operators (e.g., and
, or
, not
).
Example using and
:
x = 7
if x > 5 and x < 10:
print("x is between 5 and 10")
Let me know if you'd like more details on conditions or operators!