If Else Conditional Statements in Python
Hi! My name is Safia Khatoon. I am complete my Bachelors in Technology from RTC Institute Of Technology. My specialisation in Computer Science and Engineering.I love contributing to Open Source with the help of the skills I gain.
Also, I'm working on my YouTube Channel as well where I teach about DevOps tools and make technical content. You can have a look at it through my profile.
Feel free to reach out to me! I'd be happy to connect with you.
1. If Statement
π Definition:
The if statement is used to check a condition. If the condition is True, the code inside the block will execute.
π‘ Example:
age = 18
if age >= 18:
print("You are an adult.") # This will execute because the condition is True
Explanation:
- If
ageis 18 or greater, it will print "You are an adult."
2. If-Else Statement
π Definition:
if-else is used when you need to choose between two possibilities. If the condition is True, the code inside the if block will execute. If it is False, the else block will execute.
π‘ Example:
marks = 45
if marks >= 40:
print("Pass") # If marks are 40 or greater, it will print "Pass"
else:
print("Fail") # If marks are less than 40, it will print "Fail"
Explanation:
If
marksare 40 or greater, it will print "Pass".If
marksare less than 40, it will print "Fail".
3. Elif Statement
π Definition:
elif is used to check multiple conditions. It is short for else if. If the if condition fails, elif allows you to check another condition.
π‘ Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B") # If marks are 75 or greater, it will print "Grade B"
elif marks >= 50:
print("Grade C")
else:
print("Fail")
Explanation:
If
marksare 90 or greater, it will print "Grade A".If
marksare between 75 and 89, it will print "Grade B".If
marksare between 50 and 74, it will print "Grade C".If
marksare less than 50, it will print "Fail".
4. Key Points:
if: Used when you want to check a single condition.else: Used to provide an alternative action when theifcondition is False.elif: Used to check multiple conditions.
Real-life Example 1: Age Group Check (If-Else-Elif)
age = 20
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
Explanation:
If
ageis less than 13, it will print "You are a child".If
ageis between 13 and 17, it will print "You are a teenager".If
ageis 18 or greater, it will print "You are an adult".
Real-life Example 2: Number Positive or Negative (If-Else)
num = -5
if num >= 0:
print("The number is positive.")
else:
print("The number is negative.")
Explanation:
If
numis positive or zero, it will print "The number is positive".If
numis negative, it will print "The number is negative".
5. Conclusion:
if: Used to check a single condition.else: Used when the if condition is False and you want to handle it differently.elif: Used to check multiple conditions.