In Python, an if
statement allows you to conditionally execute a block of code based on a certain condition. An if
statement consists of the if
keyword, followed by a condition enclosed in parentheses, and then a colon. The code block that is executed if the condition is True
must be indented.
Here’s an example:
x = 5 if x > 0: print("x is positive")
In this example, the if
statement checks if x
is greater than 0. If it is, then the code block below it, which prints “x is positive”, will be executed.
You can also use an else
statement to execute a different block of code if the condition in the if
statement is False
. Here’s an example:
x = -2 if x > 0: print("x is positive") else: print("x is not positive")
In this code, the condition x < 0
is evaluated. Since x
is not less than zero, the code block within the else
statement is executed, and the output will be “x is positive”.
You can also use the elif
statement to include multiple conditions. The general syntax of the if-elif-else
statement in Python is as follows:
if condition1: # code block to execute if condition1 is True elif condition2: # code block to execute if condition1 is False and condition2 is True else: # code block to execute if both condition1 and condition2 are False
Here, condition1
and condition2
are expressions that evaluate to either True or False. If condition1
is True, then the code block within the first if
statement is executed. If condition1
is False and condition2
is True, then the code block within the elif
statement is executed. If both condition1
and condition2
are False, then the code block within the else
statement is executed.
For example, consider the following code snippet:
x = 10 if x < 0: print("x is negative") elif x == 0: print("x is zero") else: print("x is positive")
In this code, the condition x < 0
is evaluated first. Since x
is not less than zero, the next condition x == 0
is evaluated. Since x
is not equal to zero, the code block within the else
statement is executed, and the output will be “x is positive”.