HomeProgrammingPythonPython Condition

Python Condition

Python if…elif…else and Nested if

 Decision making is required when we want to execute a code only if a certain condition is satisfied. The if…elif…else statement is used in Python for decision making.

Python if Statement Syntax

if test expression:
    statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True. If the text expression is False, the statement(s) is not executed. In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Flowchart of if statement in Python programming

Example: Python if Statement

 

# In this program, user inputs a number.
# If the number is positive, we print an appropriate message

num = float(input("Enter a number: "))
if num > 0:
    print("Positive number")
print("This is always printed")

Output 1

Enter a number: 3
Positive number
This is always printed

Output 2

Enter a number: -1
This is always printed

In the above example, num > 0 is the test expression. The body of if is executed only if this evaluates to True. When user enters 3, test expression is true and body inside body of if is executed. When user enters -1, test expression is false and body inside body of if is skipped. The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression. We can see this in our two outputs above.

Python if…else

Syntax of if…else

if test expression:
    Body of if
else:
    Body of else

The  if..else statement evaluates test expression and will execute body of if only when test condition is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks.

Python if..else Flowchart

Flowchart of if...else statement in Python Programming

Example of if…else

# In this program, user input a number
# Program check if the number is positive or negative and display an appropriate message

num = float(input("Enter a number: "))
if num >= 0:
    print("Positive or Zero")
else:
    print("Negative number")

Output 1

Enter a number: 2
Positive or Zero

Output 2

 
Enter a number: -3
Negative number

In the above example, when user enters 2, the test epression is true and body of if is executed andbody of else is skipped. When user enters -3, the test expression is false and body of else is executed and body of if is skipped.

Python if…elif…else

Syntax of if…elif…else

if test expression:
    Body of if
elif test expression:
    Body of elif
else: 
    Body of else

The elif is short for else if. It allows us to check for multiple expressions. If the condition for if isFalse, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition. A if block can have only one else block. But it can have multiple elifblocks.

Flowchart of if…elif…else

Flowchart of if...elif....else in python programming

Example of if…elif…else

# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message

num = float(input("Enter a number: "))
if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

Output 1

Enter a number: 2
Positive number

Output 2

Enter a number: 0
Zero

Output 3

Enter a number: -2
Negative number

Python Nested if statements

We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. In fact, any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so must be avoided if we can.

Python Nested if Example

# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

Output 1

Enter a number: 5
Positive number

Output 2

Enter a number: -1
Negative number

Output 3

Enter a number: 0
Zero

 

- A word from our sponsors -

spot_img

Most Popular

Leave a reply

Please enter your comment!
Please enter your name here

More from Author

Freddy Film Review

Kartik Aryan alias Freddy Ginwala is a successful dentist. When it...

Putin Plans to Replace SWIFT With Blockchain Payment System

Russian President Vladimir Putin criticized monopolies in global financial payment systems...

Bitget Crypto Exchange Flips Layoff Trend, Expands to Africa

The cryptocurrency winter has been colder for some than others. While...

New iPhone15 Leaks Reveals Stunning Design and No Sim Card

The first iPhone 15 leaks have already promised a combination of...

- A word from our sponsors -

spot_img

Read Now

Freddy Film Review

Kartik Aryan alias Freddy Ginwala is a successful dentist. When it comes to his personal life, he is not successful as since last 5 years he is desperately looking for his soulmate. One day he gets his love but that love changes his life completely. Analysis of the...

Putin Plans to Replace SWIFT With Blockchain Payment System

Russian President Vladimir Putin criticized monopolies in global financial payment systems and called for an independent and blockchain-based settlement network, speaking at the International AI Travel conference in Moscow on 24 November. Russia’s Rostec Group, a government organization, has developed a blockchain platform to launch a digital system for...

Bitget Crypto Exchange Flips Layoff Trend, Expands to Africa

The cryptocurrency winter has been colder for some than others. While some cryptocurrency exchanges are forced to conduct massive employee layoffs to weather the bear market, others like Bitget Crypto Exchange continue to make massive hires to improve their services, Bitget crypto exchange flips the layoff trend. On...

New iPhone15 Leaks Reveals Stunning Design and No Sim Card

The first iPhone 15 leaks have already promised a combination of eye-catching and controversial design changes. And excitement is only likely to grow further now a new exclusive has revealed another stunning design decision. In a move that would see Apple step back in time, a new leak from anonymous...

Get iPhone 14 Under 60000 on Flipkart – Limited Time

The original price of the iPhone 14 is Rs 79,900. However, you can get the device at a discount of Rs 5000 if you have an HDFC bank card how the deal works The original price of the iPhone 14 is Rs 79,900. However, you can get the device...

Download Unofficial TWRP for Samsung A135 Exynos

​ DISCLAIMER: I WAS NEVER, HAVE NEVER BEEN, AND WILL NEVER BE RESPONSIBLE FOR ANY DAMAGES AGAINST YOUR DEVICES. We are not responsible for bricked devices, dead SD cards, thermonuclear war, or you getting fired because the alarm app failed. Please do some research if you have any concerns about the...

Android 13 and One UI 5 for Samsung Galaxy A52

Samsung was widely panned for its slow and non-existent software support during the TouchWiz era. Over the years, though, it has made considerable improvements in this area, and with One UI 5, the Korean giant has raised the bar to a new level altogether. The Galaxy S22 was...

Presearch Coin | Earn Crypto While You Search | 25 Pre Coin for Signup

Presearch offers PRE tokens as a reward for those who search through the platform. These tokens have intrinsic value because they are the access tokens purchased by advertisers to target searchers entering certain keywords. The amount currently provided to searchers is 0.25 PRE if they search through the...

Nodle Joins First Polkadot Parachain Auction

Nodle, one of the world’s largest ecosystems of connected devices, today announced their entrance into Polkadot’s inaugural parachain slot auction and crowdloan. Nodle provides infrastructure, software, and data access to the Internet of Things (IoTs) using Bluetooth Low Energy (BLE) on existing smartphones. Polkadot is a blockchain...

How to Mine Nodle Cash IoT Network

Introduction Nodle – built on a Bluetooth Low Energy (BLE) network – is a connectivity provider for the Internet of Things (IoT). The network helps companies and cities collect data from their devices, sensors, and tags. The Nodle Network can help manufactures/operators of electronic devices collect valuable data and also help...

Ethereum Whales on Move – Relocate Over $500,000,000 Matter of Hours

A massive amount of Ethereum (ETH) worth half a billion dollars is on the move, as crypto whales relocate their ETH troves. This Friday, blockchain tracker Whale Alert spotted a series of transactions in which large Ethereum holders moved 237,419 ETH, worth $557,777,068, in just over 10 hours. In...

Dogecoin becomes the 7th accepted cryptocurrency on Coinbase

Coinbase Commerce, the e-commerce arm of the United States-based crypto exchange, has added support for Dogecoin (DOGE) payments. According to a Twitter announcement, Dogecoin became the seventh cryptocurrency for merchants to accept payments on Coinbase’s e-commerce portal. The platform currently supports Bitcoin (BTC), Bitcoin Cash (BCH), Ether (ETH),...