19 May Python Decision Making Statements
With decision making statement like if, if…else, elseIf, switch, etc, you can easily take decision based on different conditions. In this lesson we will learn how to work with Python Decision Making Statements. In the previous lesson we learned how to work with loops in Python.
if statement in Python
The if decision making statement in Python executes the code, if the condition is true.
Syntax
Here’s the syntax,
1 2 3 4 |
if condition: code will execute if condition is true; |
Example
The following is an example showing the usage of if statement in Python,
1 2 3 4 5 6 7 8 |
print ('Studyopedia: Never Stop Learning') #if statement myVar = 35 if myVar: print (myVar) |
Output
The following is the output,
if…else in Python
The if…else decision making statement in Python executes some code if the condition is true and another code if the condition is false. The false condition comes under else.
Syntax
Here’s the syntax,
1 2 3 4 5 6 |
if condition: code will execute if condition is true else: code will execute if condition is false |
Example
The following is an example showing the usage of if…else statement in Python,
1 2 3 4 5 6 7 8 9 10 11 |
print ('Studyopedia: Never Stop Learning') myVar = 8 #if-else statement if myVar < 2 : print "Value is less than 5!" else: print "Value is more than 5!" |
Output
The following is the output,
if…elif…else in Python
The if…elif…else statement in Python execute code for different conditions. If more than 2 conditions are true, you can use else for the false condition.
Syntax
Here’s the syntax,
1 2 3 4 5 6 7 8 9 10 |
if condition1: code will execute if condition is true elif condition2: code will execute if another condition is true elif condition3: code will execute if above conditions aren’t true else: code will execute if all the above given conditions are false |
Example
The following is an example showing the usage of if…elif…else statement in Python,
Here, myVar = 8 and the else condition will get executed.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
print ('Studyopedia: Never Stop Learning') myVar = 8 #if-elif-else statement if myVar < 8: print "Value is less than 8!" elif myVar > 8: print "Value is greater than 8!" else: print "Value is equal to 8!" |
Output
The following is the output,
In this lesson we learned how to work with decision making statements in Python.
Python Tutorial (English)
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments