Conditional Statements in Python
In any programming language, decision-making is key. Python provides conditional statements to let you run code based on conditions.
These are essential when you want your program to respond differently depending on user input, state, or data.
Types of Conditional Statements in Python
ifstatementif-elsestatementif-elif-elseladder- Nested
ifstatements
Basic Syntax of if Statement
if_syntax.py
if condition:
# block of codeExplanation:
- The
conditionis an expression that evaluates to True or False. - If True, the indented block of code runs.
- If False, Python skips the block.
Example 1: Simple if Statement
if_example.py
age = 18
if age >= 18:
print("You are eligible to vote.")output.txt
You are eligible to vote.Example 2: if-else Statement
if_else_example.py
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")output.txt
You are not eligible to vote.Explanation:
- The
elseblock runs if theifcondition is False. - This provides a clear alternative action.
Example 3: if-elif-else Ladder
if_elif_else_example.py
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: F")output.txt
Grade: BExplanation:
- The
elif(short for else if) allows multiple conditions to be checked. - The first True condition will run.
- If no condition is True,
elseblock executes.
Example 4: Nested if Statements
nested_if_example.py
num = 10
if num > 0:
if num % 2 == 0:
print("Positive Even number")
else:
print("Positive Odd number")
else:
print("Negative number")output.txt
Positive Even numberExplanation:
- You can nest one
ifblock inside another for complex logic. - Be careful with indentation to maintain readability.
Example 5: Using Logical Operators in Conditions
logical_condition_example.py
age = 25
citizen = True
if age >= 18 and citizen:
print("Eligible to vote")
else:
print("Not eligible")output.txt
Eligible to voteExplanation:
- You can combine multiple conditions using
and,or,not. - This enables compound conditions.
Summary
- Conditional statements are used to perform different actions based on conditions.
if,if-else,if-elif-else, and nested if help control the flow of your program.- Logical operators (
and,or,not) can be used to build complex conditions. - Indentation is crucial in Python — it defines code blocks.
In the next section, we will explore Loops in Python — which allow you to repeat code efficiently.