Understanding if, if-else, and if-elif-else Statements in Python
What are if, if-else, and if-elif-else ?
These are Python’s tools for decision-making. They let your program choose between actions based on conditions you set. Think of them as decision checkpoints:
Let’s learn one by one in detail with coding examples:
The ‘ if ‘ Statement
if statement evaluates a condition (a test, like comparing numbers). If the condition is true, the code inside the if block runs. Otherwise, it skips the block.
Example : Checking Age
age = 20
if age >= 18:
print("You are eligible to vote!")
Code Explanation:
Imagine you’re checking if you can enter a movie theater:
The ‘if-else’ Statement
What if you want your program to respond when a condition is not true? This is where if – else comes in. it gives your program an alternate option if condition is not true.
Recommended by LinkedIn
Example : Checking Age
age = 16
if age >= 18:
print("You are eligible to vote!")
else:
print("Sorry, you're too young to vote.")
Explanation
Let’s go back to the movie theater example:
The if – elif – else Statement
Sometimes, you have multiple conditions to check. For this, Python provides the if – elif – else statement. Think of it as a series of checkpoints.
Example: Exam Grades
score = 85
if score >= 90:
print("You got Grade A")
elif score >= 80:
print("You got Grade B")
elif score >= 70:
print("You got Grade C")
else:
print("You need to work harder.")
Code Explanation
Think of this as choosing transportation based on how far you need to travel: