


Khusboo Tayal
In programming, we often need to make decisions based on conditions. Python provides the if, elif, and else statements to implement decision-making logic. This guide will help you understand how to use these conditional statements effectively, even if you're a beginner.
The if...else statement is used to execute a block of code only if a certain condition is true. If the condition is false, the else block is executed.
if condition:
# code if condition is True
else:
# code if condition is Falseage = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")Output:
You are eligible to vote.
Use elif (short for "else if") to check multiple conditions:
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")You can combine multiple conditions using logical operators like:
x = 10
y = 20
if x > 5 and y > 15:
print("Both conditions are True")You can nest one if statement inside another:
num = 10
if num > 0:
if num % 2 == 0:
print("Positive Even Number")
else:
print("Positive Odd Number")
If you have only one statement to execute, you can write it in one line:
x = 5
if x > 3: print("x is greater than 3")
A compact way to write simple if...else logic:
x = 10 result = "Even" if x % 2 == 0 else "Odd" print(result)
Understanding if...else statements is a foundational skill in Python. It allows your code to make decisions, handle multiple scenarios, and control the program's flow. Practice writing different conditions and combining them to become more confident.
Q1: Can I have multiple elif statements?
Yes, you can have multiple elif conditions between if and else.
Q2: Is else mandatory in Python?
No, else is optional. You can use if alone or with elif.
Q3: Can I use if...else with strings and other data types?
Yes, you can use if...else with strings, numbers, booleans, or any data type that supports logical comparisons.
Subscribe to our newsletter to get the latest Python tutorials, project ideas, and updates right to your inbox.
#python #pythonifelse #conditionalstatements #learnpython #pythontutorial #controlflow #pythonbeginners #ifstatement #elifelse #pythoncodeexamples