Conditional statements in Python
Conditional statements in Python allow you to execute specific blocks of code based on whether a condition is true or false. They are essential for decision-making in programming. The primary conditional statements in Python are if
, elif
, and else
.
1. if
Statement
The if
statement executes a block of code if a specified condition is true.
Syntax:
if condition:
# block of code
Example:
age = 18
if age >= 18:
print("You are an adult.")
2. elif
Statement
The elif
(short for "else if") statement checks another condition if the previous if
statement's condition is false.
Syntax:
if condition1:
# block of code
elif condition2:
# block of code
Example:
age = 16
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
3. else
Statement
The else
statement executes a block of code if none of the preceding conditions are true.
Syntax:
if condition1:
# block of code
elif condition2:
# block of code
else:
# block of code
Example:
age = 10
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
4. Nested if
Statements
You can nest if
statements within other if
, elif
, or else
blocks to create more complex conditions.
Syntax:
if condition1:
if condition2:
# block of code
else:
# block of code
else:
# block of code
Example:
age = 20
citizen = True
if age >= 18:
if citizen:
print("You are eligible to vote.")
else:
print("You are not a citizen.")
else:
print("You are not eligible to vote.")
Summary
Conditional statements are a fundamental part of Python, allowing you to control the flow of your program based on different conditions. By using if
, elif
, and else
, you can write programs that make decisions and execute specific blocks of code based on the given criteria.