The Python if statement is also similar to other languages like java, php simple if statements and etc.,

Python if statement :

Python if is a simple conditional statement which executes the block of statements if the condition returns True otherwise it skips the execution of the block.

Syntax :

if condition : statement

Or

if condition :
    statement 1
    statement 2

Example :

name = input('Enter your name .. ')
if name == 'chandra' :
    print('Hi',name)

print('Hello')

Output :

$ python3 sample.py
Enter your name ..chandra
Hi chandra
Hello
$ python3 sample.py
Enter your name ..shekhar
Hello

if-else statement:

if condition:
   Action 1
else:
   Action 2

if condition is true then Action 1 will execute otherwise Action 2 will execute.

Example:

name = input("Enter your Name: ")
if name == "chandra" :
    print("Hello Chandra Good Morning..")
else:
    print("Hello Guest Good Morning..")
print("How are you !")

Output:

Enter your Name: chandra
Hello Chandra Good Morning..
How are you !

if-elif-else:

if condition1:
    Action-1
elif condition2:
    Action-2
elif condition3:
    Action-3
...
else:
   Default action

Example:

color = input("What is your favourite color ? ")
if color == "RED" :
    print("You are danger..")
elif color == "WHITE":
    print("You are smart..")
elif color == "GREEN":
    print("You are cool")  
else:  
    print("Great !")

Output:

What is your favourite color ? GREEN
You are cool

Note: Here, else block is always optional.

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment