Python if…else Statement

If...esle

If…else Statement in Python

When we want to execute a code only if a certain criteria is fulfilled, decision making is needed.
For decision making in Python if…else statement is used.

Python IF Statement –

The statements in the ‘if’ block will run only if the condition(s) is/are True. All non-zero integers are treated as True and ‘0’ & ‘None’ values are treated as False.

Syntax

if condition:
    statement(s)

Flowchart

If Flowchart

Example

Run
number = 3
if number > 0 : 
    print("Number is Positive")
if number < 0:
    print("Number is Negative")
Output:
Number is Positive

Python if…else Statement –

The statements in the ‘if’ block will run only if the condition(s) is/are True, otherwise the statement(s) in the else block will be executed. All non-zero integers are treated as True and ‘0’ & ‘None’ values are treated as False.

Syntax

if condition:
    statement(s)
else:
statement(s)

Flowchart

If...else Flowchart

Example

Run
number = 3
if number // 2  : 
    print("Number is Even")
else:
    print("Number is Odd")
Output:
Number is Odd

Python if…elif…else Statement –

If we have to make decision based on multiple conditions we make use of if…elif…else statements

The statements in the ‘if’ and ‘elif’ block will run only if the condition(s) is/are True,otherwise the statement(s) in the else block will be executed. All non-zero integers are treated as True and ‘0’ & ‘None’ values are treated as False.

Syntax

if condition:
    statement(s)
elif condition:
statement(s)
else:
statement(s)

Flowchart

If...elif...else Flowchart

Example

Run
number = 0
if number > 0  : 
    print("Number is Positive")
elif number < 0 :
    print("Number is Negative")
else:
    print("Number is Zero")
Output
Number is Zero

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription