For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
The Python if-else statement is a fundamental control structure that enables your programs to make decisions based on conditions. It forms the backbone of logical reasoning within your code, allowing programs to execute different blocks of code depending on whether specified conditions are true or false.
In real-world applications, these conditional statements help create dynamic, responsive software that can adapt to different scenarios from simple user input validation to complex business logic implementation.
# Simple example of if-else in action
user_age = 18
if user_age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
Output
You are eligible to vote.
This guide will take you through everything you need to know about if-else statements in Python, from basic syntax to advanced implementations with a real-world example.
Advance your Python skills with a globally recognized MS in Data Science from LJMU and IIITB.
The if-else statement in Python is a conditional statement that executes a block of code when a specified condition evaluates to True and a different block when the condition is False.
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
The key components of an if-else statement are:
An indented block of code to execute if the condition is False
Transform your Python knowledge into data-driven insights with Upgrad’s online Data Science course.
Examples of Python If-Else Statements
Let's explore some practical examples to understand how if-else statements work in Python:
Problem Statement: Imagine a student learning mathematics needs a program to check if a number is even or odd to help with understanding number properties.
# Program to check if a number is even or odd
number = int(input("Enter a number: "))
# Check if number is divisible by 2
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
Output:
Enter a number: 7
7 is an odd number.
This example demonstrates a basic if-else statement for mathematical categorization which is a common task in programming.
Curious about Python developer salaries in 2025? Discover the latest trends now
Problem Statement: A login system needs to verify if a user's password meets the minimum length requirement before allowing access to the system.
# Simple password length checker
password = input("Enter your password: ")
# Check if password meets minimum length requirement
if len(password) >= 8:
print("Password accepted.")
print("Login successful!")
else:
print("Password too short!")
print("Your password must be at least 8 characters long.")
Output:
Enter your password: pass123
Password too short!
Your password must be at least 8 characters long.
This example shows how if-else statements are used for input validation which is a critical component of secure applications.
Problem Statement: A teacher needs to automate the process of assigning letter grades based on numerical scores to save time when evaluating student exams.
# Program to determine pass/fail status and grade
marks = float(input("Enter your marks (out of 100): "))
# Determine if student has passed or failed
if marks >= 40:
print("Congratulations! You have passed the exam.")
# Additional message based on performance level
if marks >= 90:
print("You received an A grade. Excellent performance!")
elif marks >= 80:
print("You received a B grade. Very good performance!")
elif marks >= 70:
print("You received a C grade. Good performance!")
elif marks >= 60:
print("You received a D grade. Satisfactory performance!")
else:
print("You received an E grade. Work harder next time!")
else:
print("Sorry, you have failed the exam.")
print("Please contact your teacher for remedial classes.")
Output:
Enter your marks (out of 100): 75
Congratulations! You have passed the exam.
You received a C grade. Good performance!
This example demonstrates how multiple if-else statements can be combined to create a comprehensive grading system.Real-World Application of If-Else Statement in Python
Let's explore a comprehensive real-world example that demonstrates the power of if-else statements in a practical application.
Problem Statement: An Indian e-commerce website wants to implement a discount system for its shopping cart that calculates discounts based on the total purchase amount and customer loyalty status.
# E-commerce shopping cart discount calculator
cart_total = float(input("Enter cart total (in Rs.): "))
is_registered_user = input("Are you a registered user? (yes/no): ").lower() == "yes"
has_promo_code = input("Do you have a promo code? (yes/no): ").lower() == "yes"
# Initialize discount variables
discount_percentage = 0
discount_amount = 0
final_amount = cart_total
discount_reason = ""
# Apply discount logic based on cart total
if cart_total >= 5000:
discount_percentage = 10
discount_reason = "Purchase above Rs. 5,000"
else:
if cart_total >= 3000:
discount_percentage = 7.5
discount_reason = "Purchase above Rs. 3,000"
else:
if cart_total >= 1000:
discount_percentage = 5
discount_reason = "Purchase above Rs. 1,000"
else:
discount_reason = "No minimum purchase discount applicable"
# Apply additional discount for registered users
if is_registered_user:
if discount_percentage > 0:
discount_percentage += 2 # Additional 2% for registered users
discount_reason += " + 2% registered user bonus"
else:
discount_percentage = 2
discount_reason = "2% registered user discount"
# Apply promo code discount if applicable
if has_promo_code:
if cart_total >= 2000:
# Fixed amount discount for promo code
promo_discount = 200
discount_reason += f" + Rs. 200 promo code discount"
else:
print("Sorry, promo code requires minimum purchase of Rs. 2,000")
# Calculate final amounts
discount_amount = (cart_total * discount_percentage / 100)
if has_promo_code and cart_total >= 2000:
discount_amount += promo_discount
final_amount = cart_total - discount_amount
# Display cart summary
print("\n===== SHOPPING CART SUMMARY =====")
print(f"Cart Total: Rs. {cart_total:.2f}")
print(f"Discount: Rs. {discount_amount:.2f} ({discount_reason})")
print(f"Final Amount: Rs. {final_amount:.2f}")
# Display additional offers or suggestions
if final_amount >= 4000:
print("\nYou qualify for free shipping!")
else:
shipping_cost = 99
print(f"\nShipping charge of Rs. {shipping_cost} will be applied.")
amount_for_free_shipping = 4000 - final_amount
if amount_for_free_shipping > 0:
print(f"Add items worth Rs. {amount_for_free_shipping:.2f} more to qualify for free shipping!")
Output:
Enter cart total (in Rs.): 3500
Are you a registered user? (yes/no): yes
Do you have a promo code? (yes/no): yes
===== SHOPPING CART SUMMARY =====
Cart Total: Rs. 3500.00
Discount: Rs. 462.50 (Purchase above Rs. 3,000 + 2% registered user bonus + Rs. 200 promo code discount)
Final Amount: Rs. 3037.50
Shipping charge of Rs. 99 will be applied.
Add items worth Rs. 962.50 more to qualify for free shipping!
This e-commerce example demonstrates how if-else statements are used to implement business logic for calculating discounts, applying promotional offers, and providing personalized recommendations to customers.
The if-else statement is a very important part of logical decision-making in Python programming. By mastering this fundamental control structure, you gain the ability to create amazing programs that can adapt to different situations and user inputs.
Yes, the else clause is optional. If you only need to execute code when a condition is true and do nothing otherwise, you can use an if statement by itself.
In Python, the following values are considered False:
Yes, you can use logical operators (and, or, not) to combine multiple conditions:
if age >= 18 and income > 25000:
print("Eligible for credit card")
While there's no technical limit, deeply nested if-else statements can make code difficult to read and maintain. If you find yourself nesting beyond 3-4 levels, consider refactoring your code.
Yes, Python offers a ternary operator for concise if-else expressions:
status = "Adult" if age >= 18 else "Minor"
Python doesn't have a built-in switch/case statement like many other languages. Multiple if-elif-else statements typically serve this purpose, though Python 3.10+ introduced the match-case statement as an alternative.
No, parentheses are not required around conditions in Python if statements, though they can be used for clarity or when combining multiple conditions:
# Both of these are valid:
if x > 5:
print("x is greater than 5")
if (x > 5 and y < 10):
print("x is greater than 5 and y is less than 10")
You can use comparison operators with and or use Python's chained comparisons:
# Both are equivalent:
if 0 <= x <= 100:
print("x is between 0 and 100")
if x >= 0 and x <= 100:
print("x is between 0 and 100")
== checks if two values are equal, while is checks if two variables refer to the same object in memory. For most primitive types, use == for comparison:
if x == 10: # Checks if value is equal to 10
print("x equals 10")
if x is None: # Checking for None is a common use case for 'is'
print("x is None")
Use the not operator to negate conditions, but consider rewriting for clarity when possible:
# Instead of:
if not is_valid:
print("Invalid input")
# Consider if the opposite makes more sense:
if is_valid:
print("Processing valid input")
else:
print("Invalid input")
Yes, you can use the or operator to combine conditions:
if age < 18 or income < 10000:
print("Not eligible for loan")
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.