Learn
🤖 AI Hub 📰 News 📖 Dictionary 🧰 Resources
Grow
💼 Jobs 🚀 Community 🏆 Challenges
Explore by Stage
🌑 Zero 📚 Learn 🔧 Practice 🏗 Build 🚀 Launch 💰 Earn
Account
Login Sign Up
🏗️HTML 🎨CSS ⚡JavaScript 🐙Git & GitHub ⚛️React Soon 📘TypeScript Soon 🐍Python 🗄️Database & SQL Soon 🌐Web Development Soon ☁️Cloud & DevOps Soon 🤖AI & ML Soon 📄Resume Prep Soon 🎤Interview Prep Soon 💼Freelancing Soon 🚀SaaS & Side Projects Soon 🤖Automation Soon
Beginner 🕑 11 min read 👁 3 views 📅 Oct 22, 2026

Conditions: if, elif and else

Teach your Python programs to make decisions with if, elif and else, comparison operators and and, or, not. You will build a school result checker that turns marks into grades.

Programs That Make Decisions

When your school publishes exam results, one simple rule decides every grade: 90 and above gets A+, 75 and above gets A, 60 and above gets B, 35 and above gets C, and below 35 is a fail. The clerk does not think hard about each marksheet. They check the marks against the rule, from the top, and stop at the first line that fits.

A cinema ticket counter works the same way. A small child enters free, children pay a lower price, adults pay the full price, and senior citizens get a concession. The person at the counter asks your age and decides the price.

So far, your Python programs ran every line from top to bottom, every time. In this lesson you will teach your programs to make decisions like the school clerk and the ticket counter. You will use if, elif and else, and by the end you will build a real result checker that asks for marks and prints the grade.

Step 1: Questions with True or False Answers

Every decision starts with a question that has a yes or no answer. In Python, “yes” is True and “no” is False. These two values are called booleans. You get them by comparing values with comparison operators:

OperatorMeaningExampleResult
==is equal to5 == 5True
!=is not equal to5 != 3True
>is greater than7 > 9False
<is less than2 < 10True
>=is greater than or equal to35 >= 35True
<=is less than or equal to40 <= 35False

Notice the double equals sign. A single = stores a value in a variable. A double == asks whether two values are equal. Run this example and check each answer:

marks = 82

print(marks > 90)    # False
print(marks >= 35)   # True
print(marks == 82)   # True
print(marks != 100)  # True
print(marks < 50)    # False

# Strings can be compared too (capital letters matter)
city = "Pune"
print(city == "Pune")  # True
print(city == "pune")  # False

Step 2: if and else

An if statement runs a block of code only when its condition is True. An else block runs when the condition is False. Think of a road that splits into two: the program takes exactly one path.

Look closely at the shape of the code. The if line ends with a colon (:). The lines that belong to it are pushed to the right by 4 spaces. When the program finishes the chosen block, it continues with the next line that is not pushed in.

marks = 28

if marks >= 35:
    print("Result: Pass")
    print("Well done!")
else:
    print("Result: Fail")
    print("Do not give up. The supplementary exam is next month.")

print("Thank you for checking your result.")
# Result: Fail
# Do not give up. The supplementary exam is next month.
# Thank you for checking your result.

Change marks to 72 and run it again. The first block runs instead, and the last line runs in both cases because it is outside the if and else blocks.

Step 3: Many Choices with elif

The school result rule has five grades, not two. For this, Python has elif, which is short for “else if”. Python checks each condition from the top. As soon as one is True, it runs that block and skips all the rest. The final else catches everything that did not match.

marks = 78

if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 35:
    grade = "C"
else:
    grade = "Fail"

print(f"Marks: {marks}, Grade: {grade}")  # Marks: 78, Grade: A

Why does 78 give an A and not a B or a C? Because 78 is also greater than 60 and 35, but Python stopped at the first true condition, marks >= 75. This is why the order of your conditions matters so much.

Step 4: Indentation Is the Rule, Not a Style

In many languages, curly braces mark which lines belong to an if. Python uses indentation instead: the spaces at the start of a line. If you forget them, Python cannot understand your program and stops with an IndentationError. Run this to see the error for yourself:

age = 15

if age >= 12:
print("Full ticket")  # ERROR: IndentationError

Here is the fixed version. The print line is indented by 4 spaces, so Python knows it belongs to the if:

age = 15

if age >= 12:
    print("Full ticket")  # Full ticket
Always use 4 spaces for each level of indentation. Code editors such as VS Code and the playground insert 4 spaces when you press Tab. Never mix tabs and spaces in the same file.

Step 5: Combining Conditions with and, or and not

Real rules often have more than one part. Python gives you three logical operators to combine conditions:

  • and is True only when both sides are true. “An adult and a weekend show.”
  • or is True when at least one side is true. “A child or a senior citizen.”
  • not turns True into False and the other way around. “Not a member.”
age = 65
day = "Sunday"

# and: both sides must be True
if age >= 18 and day == "Sunday":
    print("Adult ticket on a weekend: Rs. 250")

# or: at least one side must be True
if age < 12 or age >= 60:
    print("You get the concession price")

# not: flips True to False and False to True
is_member = False
if not is_member:
    print("Join our cinema club for 10% off")

# Output:
# Adult ticket on a weekend: Rs. 250
# You get the concession price
# Join our cinema club for 10% off

Python also lets you write a range check in one go: 3 <= age < 12 means “age is at least 3 and less than 12”. It reads just like maths.

Step 6: Nested if Statements

You can put an if inside another if. This is called nesting. The inner decision is only checked when the outer one is true. Each level is indented by 4 more spaces.

age = 20
has_student_id = True

if age >= 18:
    print("Adult ticket")
    if has_student_id:
        print("Student discount: pay Rs. 150 instead of Rs. 200")
    else:
        print("Price: Rs. 200")
else:
    print("Child ticket: Rs. 120")

# Adult ticket
# Student discount: pay Rs. 150 instead of Rs. 200

Nesting is useful, but more than two or three levels becomes hard to read. Often an and or an elif gives a flatter, cleaner version of the same logic.

Step 7: Truthy and Falsy Values

A condition does not have to be a comparison. Python can treat any value as true or false. Values that count as false are called falsy: 0, 0.0, an empty string "", an empty list [] and the special value None. Almost everything else is truthy. The bool() function shows you which is which.

name = ""          # the user typed nothing
seats_left = 0
snacks = []          # an empty list (you will meet lists soon)

if name:
    print(f"Welcome, {name}!")
else:
    print("Please enter your name.")   # this runs

if seats_left:
    print("Seats are available.")
else:
    print("Housefull!")                # this runs

print(bool("Asha"), bool(""))   # True False
print(bool(5), bool(0))         # True False
print(bool(snacks))             # False

This gives a short way to check “did the user type anything?”: just write if name:.

Step 8: The One-Line if (Conditional Expression)

When you only need to choose between two values, Python has a short form: value_if_true if condition else value_if_false. Programmers often call it the ternary form. Use it for small, simple choices only. For anything longer, a normal if and else is easier to read.

age = 10

ticket = "Child" if age < 12 else "Adult"
print(ticket)  # Child

marks = 40
print("Pass" if marks >= 35 else "Fail")  # Pass

Real-Life Example: A School Result Checker

Now let us put everything together. This program asks for a student’s name and marks, checks that the marks make sense, then prints the grade and a short remark. It uses input(), so the playground has filled the Input box with a name and marks for you. Change them and run again.

print("=== Sunrise Public School: Result Checker ===")

name = input("Student name: ")
marks = float(input("Total marks out of 100: "))

if marks < 0 or marks > 100:
    print("Please enter marks between 0 and 100.")
else:
    if marks >= 90:
        grade = "A+"
        remark = "Outstanding!"
    elif marks >= 75:
        grade = "A"
        remark = "Excellent work."
    elif marks >= 60:
        grade = "B"
        remark = "Good, keep going."
    elif marks >= 35:
        grade = "C"
        remark = "You passed. Aim higher next time."
    else:
        grade = "Fail"
        remark = "Meet your class teacher for extra classes."

    result = "PASS" if marks >= 35 else "FAIL"
    print(f"{name}: {marks} marks, grade {grade}, {result}")
    print(remark)

With the default input, you will see that Kavya scored 91.0 marks, got grade A+ and passed. Notice how the program first checks for impossible marks (below 0 or above 100) before it works out a grade. Checking input first is a habit that real programs need.

Try these changes:

  1. Enter 34.5, then 35, then 150 as the marks and compare the results.
  2. Add a new grade A++ for exactly 100 marks. Where must the new condition go?
  3. Print an extra line, “Scholarship eligible”, when the marks are 85 or more.

Common Mistakes

  • Using = instead of ==. if marks = 90: is a SyntaxError, because = stores a value. Use == to compare.
marks = 90

if marks = 90:  # ERROR: SyntaxError
    print("Full marks in this section")
  • Forgetting the colon. Every if, elif and else line must end with :. Without it, Python shows a SyntaxError.
  • Putting conditions in the wrong order. Python stops at the first true condition, so start with the highest limit. Here is what goes wrong, and the fix:
marks = 95

# Wrong order: the first True condition wins
if marks >= 35:
    print("C")       # this runs, even for 95 marks!
elif marks >= 90:
    print("A+")      # never reached

# Right order: start with the highest limit
if marks >= 90:
    print("A+")      # this runs
elif marks >= 35:
    print("C")
  • Comparing text with a number. input() always returns a string. Comparing "19" >= 18 gives a TypeError. Convert it first with int() or float():
age = input("Your age: ")

# input() always gives text, so turn it into a number first
age = int(age)

if age >= 18:
    print("You can book an adult ticket.")
else:
    print("Please book a child ticket.")
  • Writing if day == "Saturday" or "Sunday":. This is always true, because the non-empty string "Sunday" is truthy on its own. Repeat the comparison: if day == "Saturday" or day == "Sunday":.

Practice Task: The Cinema Ticket Counter

Build a ticket counter for Galaxy Cinema. The Input box already has an age and a show time. Your program should:

  • Set the base price: under 3 years Rs. 0, 3 to 11 years Rs. 120, 12 to 59 years Rs. 200, 60 years and above Rs. 150
  • Take Rs. 30 off for a morning show (a free ticket stays free)
  • Print the final price, or “Free entry” when the price is 0
  • Print “Please show your ID at the gate” for children under 3 and for senior citizens
print("=== Galaxy Cinema: Ticket Counter ===")

age = int(input("Age: "))
show = input("Show (morning or evening): ")

# TODO 1: Work out the base price:
#         under 3: Rs. 0, 3 to 11: Rs. 120, 12 to 59: Rs. 200, 60 and above: Rs. 150

# TODO 2: If the show is "morning", take Rs. 30 off (but never below Rs. 0)

# TODO 3: Print the final price, or "Free entry" if it is 0

# TODO 4: If age is below 3 or 60 and above, also print "Please show your ID at the gate"
Show one possible answer (try it yourself first!)
print("=== Galaxy Cinema: Ticket Counter ===")

age = int(input("Age: "))
show = input("Show (morning or evening): ")

if age < 3:
    price = 0
elif age < 12:
    price = 120
elif age < 60:
    price = 200
else:
    price = 150

if show.lower() == "morning" and price > 0:
    price = price - 30

if price == 0:
    print("Free entry")
else:
    print(f"Ticket price: Rs. {price}")

if age < 3 or age >= 60:
    print("Please show your ID at the gate")

# With age 65 and a morning show:
# Ticket price: Rs. 120
# Please show your ID at the gate

Key Takeaways

  • Comparison operators (==, !=, >, <, >=, <=) give True or False.
  • if runs a block when a condition is true, elif adds more choices, and else catches everything else. Python stops at the first true condition.
  • Every if, elif and else line ends with a colon, and the block under it is indented by 4 spaces.
  • and, or and not combine conditions. Empty values and zero are falsy.
  • Use the one-line form a if condition else b only for small, simple choices.

❓ Frequently Asked Questions

No. With elif, Python stops at the first true condition and skips the rest. Separate if statements are all checked, so more than one block can run.
No. else is optional. Leave it out when nothing needs to happen if the condition is false.
Python accepts any number of spaces as long as you are consistent inside a block. The standard Python style guide, PEP 8, recommends 4 spaces, and almost all Python code uses them.
input() always returns text. Convert it with int() or float() before you compare it with a number.
Was this lesson helpful?

🎯 Finished this lesson?

🔗 Related Tutorials
🤖 Got a Doubt? Ask AI
Get instant answers in Hindi or English
🤖
Z2T Bot
Online
Ask me anything about this tutorial — I'm here! 👋