Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

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 –

Syntax

if condition:
    statement(s)

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.

Flowchart

If Flowchart

Example

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

Python if…else Statement –

Syntax

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

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.

Flowchart

If...else Flowchart

Example

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

Output

Number is Odd

Python if…elif…else Statement –

Syntax

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

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.

Flowchart

If...elif...else Flowchart

Example

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