Header Ads Widget

Responsive Advertisement

Control Flow in Python : If else in python


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: 
    statement(s)

# If the number is positive, we print an appropriate message
num = 3
if num > 0:
    print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
    print(num, "is a positive number.")
print("This is also always printed.")

**************************************************************************************




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")



i = 10
if (i == 10):
    
    #  First if statement
    if (i < 15):
        print("i is smaller than 15")
          
    # Nested - if statement
    # Will only be executed if statement above
    # it is true
    if (i < 12):
        print("i is smaller than 12 too")
    else:
        print("i is greater than 15")

Post a Comment

0 Comments