Conditional Statements

Conditional Statements

Conditional Statements in python programming are used to make decisions based on the conditions.

Conditional statements execute sequentially when there is no condition around the statements. If we put some condition for a block of statements, the execution flow may change based on the result evaluated by the condition.

1. if
if condition : statement 

OR

if condition : 
    statement-1
    statement-2 
    statement-3

If condition is true then statements will be executed.

name=input("Enter Name:")
if name=="ashok" :
    print("Hello ashok Good Morning")
print("How are you..!!!")

Output

ashok@mariyala:~/work$py test.py
Enter Name:ashok
Hello ashok Good Morning
How are you..!!!

ashok@mariyala:~/work$py test.py
Enter Name:kumar
How are you..!!!
2. if-else
if condition: 
    Action-1 
else: 
    Action-2

if condition is true then Action-1 will be executed otherwise Action-2 will be executed.

name=input("Enter Name:")
if name=="ashok" : 
    print("Hello ashok Good Morning")
else: 
    print("Hello kumar Good Morning")
print("How are you!!!")

Output

ashok@mariyala:~/work$py test.py
Enter Name:ashok
Hello ashok Good Morning
How are you!!!
ashok@mariyala:~/work$py test.py
Enter Name:Raju
Hello kumar Good Moring
How are you!!!
3. if-elif-else
if condition1: 
    Action-1 
elif condition2: 
    Action-2 
elif condition3: 
    Action-3 
elif condition4: 
    Action-4
    .....
else: 
    Default Action

Based condition the corresponding action will be executed.

Note

  1. else part is always optional. Hence the following are various possible syntax’s.
    • If
    • if – else
    • if-elif-else
    • if-elif

2. There is no switch statement in Python

Conditional Statements
Scroll to top