Decision-making statements in programming languages decide the direction of the flow of program execution. In Python, if-else , elif statement is used for decision making. In this article we will discuss some important program related to If-else and nested if else and elif.
if test expression:
**************************************************************************************
If else Expresstion
if test expression:
Body of if
else:
Body of else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
******************************************************************************************
Expression for If elif else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
*********************************************************************************************
Nested if else
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
0 Comments