if Statement
In Python, the if statement is used to conditionally execute a block of code based on a specified condition. The basic syntax of an if statement is as follows:
if condition:
# Code to be executed if the condition is True
Here's a more detailed breakdown:
- The
ifkeyword is followed by a condition that evaluates to eitherTrueorFalse. - If the condition is
True, the indented code block following theifstatement is executed. - If the condition is
False, the indented code block is skipped.
Example:
x = 10
if x > 5:
print("x is greater than 5")
In this example, the condition x > 5 is True, so the indented print statement is executed, and the output will be:
x is greater than 5
Adding an else Clause:
You can also include an else clause to specify a block of code to be executed when the if condition is False:
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
In this case, since x is not greater than 5, the code in the else block is executed, and the output will be:
x is not greater than 5
Adding elif (Else If) Statements:
You can use elif to check multiple conditions in sequence:
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 False, but the second condition (x == 10) is True, so the corresponding block is executed, and the output will be:
x is equal to 10
The if, elif, and else statements allow you to create more complex decision structures based on various conditions. The code in each block is indented to indicate which statements are part of each block.