Python Conditional statement

Estimated reading: 3 minutes 1066 views

If Statement

The If statement is the most fundamental decision-making statement, in which the code is executed based on whether it meets the specified condition. It has a code body that only executes if the condition in the if statement is true. The statement can be a single line or a block of code.

The if statement in Python has the subsequent syntax:

if expression

					num = 5
if num > 0:
    print(num, "is a positive number.")
print("This statement is true.")
#When we run the program, the output will be:
5 is a positive number.
This statement is true.

If and else Statement

This statement is used when both the true and false parts of a given condition are specified to be executed. When the condition is true, the statement inside the if block is executed; if the condition is false, the statement outside the if block is executed. The if…Else statement in Python has the following syntax: if condition : #Will executes this block if the condition is true else : #Will executes this block if the condition is false
					num = 5
if num >= 0:
    print("Positive or Zero")
     print("Negative number")
output : Positive or Zero

If , elif and else condition

In this case, the If condition is evaluated first. If it is false, the Elif statement will be executed; if it also comes false, the Else statement will be executed. The If…Elif..else statement in Python has the subsequent syntax: if condition : Body of if elif condition : Body of elif else: Body of else
					num = 7
if num > 0:
    print("Positive number")
elif num == 0:
    print("Negative number")
output:  Positive number

Nested If Statement

A Nested IF statement is one in which an If statement is nestled inside another If statement. This is used when a variable must be processed more than once. If, If-else, and If…elif…else statements can be used in the program. In Nested If statements, the indentation (whitespace at the beginning) to determine the scope of each statement should take precedence.

The Nested if statement in Python has the following syntax:

amount = price*quantity
if amount > 200:
    if amount >1000:
        print("The amount is greater than 1000")
        if amount  800:
            print("The amount is between 800 and 1000")
        elif amount  600:
            print("The amount is between 600 and 1000")
            print("The amount is between 400 and 1000")
elif amount == 200:
    print("Amount is 200")
    print("Amount is less than 200")
The output : “The amount is between 400 and 1000.”

Leave a Comment

Share this Doc