19 May Python Decision Making Statements
With decision-making statements like if, if…else, else if, switch, etc, you can easily make decisions based on different conditions. In this lesson, we will learn how to work with Python decision-making statements.
if statement in Python
The if decision-making statement in Python executes the code if the condition is true.
Syntax
Here’s the syntax,
if condition:
code will execute if condition is true;
Example
The following is an example showing the usage of an if statement in Python:
Demo19.py
# if statement in Python
# Code by studyopedia
age = 20
if age > 18:
print("Candidate can vote")
Output
The following is the output,
Candidate can vote
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,
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 the if…else statement in Python,
Demo20.py
# if...else statement in Python
# Code by studyopedia
age = 10
if age > 18:
print("Candidate can vote")
else:
print("Candidate cannot vote")
Output
Candidate cannot vote
if…elif…else in Python
The if…elif…else statement in Python executes code for different conditions. If more than 2 conditions are true, you can use else for the false condition.
Syntax
Here’s the syntax,
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 the if…elif…else statement in Python,
Here, age = 18, and the else condition will get executed.
Demo21.py
# if...elif...else statement in Python
# Code by studyopedia
age = 18
if age > 18:
print("Candidate can vote")
elif age < 18:
print("Candidate cannot vote")
else:
print("Candidate's age is 18, therefore voting is legal.")
Output
Candidate's age is 18, therefore voting is legal.
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, Studyopedi,a with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments