If Else Statement in Python
In Python, the if
, else
, and elif
(short for "else if") statements are used for conditional execution of code. These statements allow you to execute different blocks of code based on whether certain conditions are true or false. Here's a basic overview of how the If Else Statement in Python work:
pythonCopy codeif condition1:
# Block of code to execute if condition1 is True
elif condition2:
# Block of code to execute if condition1 is False and condition2 is True
else:
# Block of code to execute if both condition1 and condition2 are False
if
: This is the initial condition that is checked. If it evaluates toTrue
, the associated block of code is executed. If it evaluates toFalse
, the next condition (elif
orelse
) is checked.elif
(optional): Short for "else if". It allows you to check multiple conditions. If the precedingif
orelif
conditions areFalse
and theelif
condition isTrue
, the associated block of code is executed.else
(optional): This block of code is executed if none of the preceding conditions (if
orelif
) areTrue
.
Here's an example demonstrating the usage of if
, elif
, and else
statements in Python:
pythonCopy codex = 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")
Output:
vbnetCopy codex is equal to 10
In this example:
x
is equal to10
, so the conditionx == 10
isTrue
.Therefore, the block of code associated with the
elif
statement is executed, printing"x is equal to 10"
.The
else
block is not executed because the condition associated with it (x < 10
) isFalse
. Check out online Python Interpreter to practice and excel in your tech career!