Python – if Statement
Python if statement runs either one set of statements or another set of statements depending upon the condition associated with. If, if-else, and if elif are three selection statements available in Python.
Before anything else, let’s clear the concept of single statement and compound statement
Single Statement: Any valid Python statement.
Compound Statement: Group of statement that executes as a single statement.
If Statement
It will execute its associated statement only once its associated condition results in True. If associated condition is not True then it will skip the associated statement and will move on next statement.
Syntax
if condition: statement
if statement is the first selection statement that checks the associated condition with. Runs the associated statement(s), if the result is true otherwise control jumps on the very next statement.
Flow Diagram of if statement
Example of if statement
age =18 if age < 20: print(' You are minor my dear'
The output of the above code is
You are minor my dear
if-else statement
If statement is a selection statement i.e. it will execute its associated statement only once its associated condition results in True. If the associated condition is not True then it will skip the associated statement and will move on to the statement associated with ELSE.
Syntax
if condition: statement-1 else: statement-2
Flow Diagram of if-else statement
Sample program to demonstrate the working of if-else statement
age =21 if age >20 : print(' You are minor my dear') else: print(' You are major my dear.... Welcome to the club')
The sample output of the above program is
You are major my dear.... Welcome to the club
if you have multiple such conditions then how to deal with that condition. Let’s consider a situation where you are given a day number and you are requested to generate its associated day name.
probable solution using only if statement
dno =int(input(“Enter day Number”)) If(dno==1): print(“Monday”) If(dno==2): print(“Tuesday”) If(dno==3): print(“Wednesday”) If(dno==4): print(“Thursday”) If(dno==5): print(“Fridday”) If(dno==6): print(“Saturday”) If(dno==7): print(“Sundayday”)
using if elif statement – Compare multiple conditions
dno =int(input(“Enter day Number”)) If(dno==1): print(“Monday”) elif(dno==2): print(“Tuesday”) elif(dno==3): print(“Wednesday”) elif(dno==4): print(“Thursday”) elif(dno==5): print(“Fridday”) elif(dno==6): print(“Saturday”) elif(dno==7): print(“Sundayday”)
The last one is a better solution as it compares fewer numbers compared to the previous solution. Indentation is one of the most important parts of the selection statement. The improperly indented statement will raise logical errors. unlike other programming languages, Python does not support a switch statement.
Python Assignment on if statement is one such article that you must try with this if statement tutorial.