Introduction
Conditional statements in Python allow you to control the flow of execution based on conditions. By using if
, elif
, and else
, you can make decisions in your programs and execute different code blocks depending on whether certain conditions are true or false. This is a fundamental concept in Python programming and plays a crucial role in creating dynamic programs.
Objective
The goal of this topic is to help you understand how to use conditional statements in Python. By the end of this tutorial, you will be able to:
- Understand how
if
,elif
, andelse
work in Python. - Write simple Python programs that make decisions using conditional statements.
- Use multiple conditions in a single program to control the flow of execution.
Python Code: If, Elif, Else
# Python program to demonstrate if, elif, else statements
# Input: User enters their age
age = int(input("Enter your age: "))
# If the age is less than 13, display that the person is a child
if age < 13: print("You are a child.") # If the age is between 13 and 19, display that the person is a teenager elif age >= 13 and age <= 19:
print("You are a teenager.")
# Otherwise, display that the person is an adult
else:
print("You are an adult.")
Explanation of the Program Structure
The program starts by asking the user to input their age. The input is then converted to an integer using int()
function because input from the user is by default treated as a string.
Next, the if
statement checks if the user’s age is less than 13. If this condition is true, the program will print “You are a child.”
If the first condition is false, the program proceeds to the elif
(else if) statement, which checks if the age is between 13 and 19. If this condition is true, the program prints “You are a teenager.”
If neither of the above conditions are met, the program executes the else
statement and prints “You are an adult.”
How to Run the Program
To run the program:
- Open a text editor (e.g., VS Code, Sublime Text, or IDLE).
- Copy and paste the code into a new Python file, for example,
conditional_statements.py
. - Open your terminal or command prompt and navigate to the folder containing the Python file.
- Run the program by typing
python conditional_statements.py
and pressing Enter. - Enter your age when prompted, and the program will display the appropriate message based on the condition that matches your age.