Python conditional Statement
Conditional statements in Python are used to control the flow of a program based on certain conditions. There are three types of conditional statements in Python: if
, if-else
, and if-elif-else
.
If
if
statement:
The if
statement allows you to execute a block of code if a certain condition is true. The syntax for the if
statement is as follows:
if condition:
# execute this block of code
Examples:
a = 10
if a > 20:
print(" a is greater than 20")
if a < 20:
print("a is less than 20")
if a == 20:
print("a is equal to 20")
If else
if-else
statement:
The if-else
statement allows you to execute one block of code if a condition is true, and another block of code if the condition is false. The syntax for the if-else
statement is as follows:
if condition:
# execute this block of code if condition is true
else:
# execute this block of code if condition is false
Examples:
a = 10
if a > 20:
print(" a is greater than 20")
else: # this block execute
print("a is less than 20")
# change the value to see the effect
a = 50
if a > 20: # this block execute
print("a is greater than 20")
else:
print("a is less than 20")
if elif else
if-elif-else
statement:
The if-elif-else
statement allows you to execute different blocks of code based on multiple conditions. The syntax for the if-elif-else
statement is as follows:
if condition1:
# execute this block of code if condition1 is true
elif condition2:
# execute this block of code if condition1 is false and condition2 is true
...
elif conditionN:
# execute this block of code if all previous conditions are false and conditionN is true
else:
# execute this block of code if all previous conditions are false
Examples:
a = 10
if a > 20:
print(" a is greater than 20")
elif a < 20:
print("a is less than 20")
else:
print("a is equal to 20")
If Else Sort Hand
sort hand is used to write if else condition in one line for sort code .
a = 10
if a > 2: print("a is greater than 20")
# another way
print(" a is greater than 20") if a > 20 else print("a is less than 20")
It's important to note that the conditions in the if
, elif
, and else
statements are tested in order, and the first one that evaluates to True
determines which block of code is executed. Once a condition is found to be true, the rest of the conditions are skipped.