Python: Zero to Hero
Home/The Foundation
Share

Chapter 4: Making Decisions — if, elif, else

So far your programs have run top to bottom like a straight road — same steps, same result, every time. That's useful, but it's not how real programs work.

Real programs decide. A login page checks if your password is correct. A weather app shows "bring an umbrella" or "enjoy the sunshine." A game says "You won!" or "Try again." All of those are decisions — and in Python, decisions are built with if.

By the end of this chapter, your programs will react to data and to the people who use them.

Boolean Values: True and False

Before you can make a decision, you need to understand how Python represents "yes" and "no."

Python has a data type called bool (short for Boolean, named after mathematician George Boole). A bool has exactly two possible values: True and False. Capital T, capital F. That matters — Python is case-sensitive.

is_raining = True
is_sunny = False

print(is_raining)   # True
print(is_sunny)     # False
print(type(is_raining))  # <class 'bool'>

You'll see booleans constantly. Every comparison you make in Python — "is x greater than y?" "is this string equal to that string?" — gives you back a True or a False.

Comparison Operators

A comparison operator looks at two values and answers a yes/no question. The answer is always True or False.

Operator Meaning Example Result
== equal to 5 == 5 True
!= not equal to 5 != 3 True
< less than 3 < 5 True
> greater than 5 > 3 True
<= less than or equal to 5 <= 5 True
>= greater than or equal to 6 >= 10 False
print(10 == 10)   # True
print(10 == 9)    # False
print(10 != 9)    # True
print(10 > 9)     # True
print(10 < 9)     # False
print(10 >= 10)   # True
print(10 <= 9)    # False

The most common beginner mistake: using = when you mean ==.

  • = is assignment: "put this value into this variable."
  • == is comparison: "are these two values equal?"
age = 18       # assignment — storing 18 in age
age == 18      # comparison — asking if age equals 18 (returns True)

Mix them up and Python will either crash or do something unexpected. Watch for it.

You can compare strings too:

name = "Alice"
print(name == "Alice")   # True
print(name == "alice")   # False — case-sensitive
print(name != "Bob")     # True

Your turn: Try five comparisons in Python — mix numbers and strings. Predict the result before you run each one, then check.

Getting Input from the User

To make useful decisions, programs often need information from the person running them. Python's input() function handles this.

name = input("What is your name? ")
print(f"Hello, {name}!")

When this runs, Python prints the message, waits for the user to type something and press Enter, then stores whatever they typed as a string in name.

Important: input() always returns a string. Even if the user types a number.

answer = input("How old are you? ")
print(type(answer))   # <class 'str'>

If you need a number, convert it with int() or float():

age_text = input("How old are you? ")
age = int(age_text)
print(f"Next year you will be {age + 1}.")

Or more concisely — wrap input() directly inside int():

age = int(input("How old are you? "))
print(f"Next year you will be {age + 1}.")

Both do the same thing. The second style is what you'll see most often in real code.

What happens if the user types something that isn't a number? Python crashes with a ValueError. You'll learn how to handle that gracefully in Chapter 13 (Error Handling). For now, trust that the user will type a number when you ask for one.

Your turn: Ask the user for their favorite number. Convert it to an integer. Print the number, its double, and its square.

if — One Branch

The if statement runs a block of code only when a condition is True. If the condition is False, the block is skipped entirely.

score = 75

if score >= 50:
    print("You passed!")

Output:

You passed!

Change score to 30 and run again — nothing prints, because 30 >= 50 is False.

The colon and the indent are not optional. The if line ends with :. Everything that belongs to the if block must be indented — pushed to the right by 4 spaces. This is how Python knows where the block starts and ends.

if score >= 50:
    print("You passed!")   # inside the if — indented
    print("Great job!")    # also inside the if — same indentation

print("Done.")             # outside the if — not indented, always runs

Python doesn't use {} curly braces like many other languages. Indentation is the structure. Every editor you'll use (VS Code, Colab, Jupyter) handles the indentation automatically — just press Enter after the : and it adds the spaces.

In plain English: The if statement says "only do this if it's true." The indented lines are the "this."

Your turn: Create a variable temperature. If it's above 30, print "It's hot today." Run it with a temperature of 35, then with 20. Make sure you see the right behavior each time.

if / else — Two Branches

else is the fallback — the code that runs when the if condition is False.

score = 35

if score >= 50:
    print("You passed!")
else:
    print("You didn't pass. Keep practicing.")

Output:

You didn't pass. Keep practicing.

Python checks the condition. It's False, so it skips the if block and runs the else block instead. Exactly one of the two blocks always runs.

A real example with user input:

age = int(input("How old are you? "))

if age >= 18:
    print("You can vote.")
else:
    print("You're not old enough to vote yet.")

If the user types 21, they see "You can vote." If they type 16, they see the other message.

Your turn: Ask the user for a number. If it's even (number % 2 == 0), print "Even." Otherwise print "Odd."

if / elif / else — Many Branches

When you have more than two possible outcomes, use elif (short for "else if"). Python checks each condition in order — the moment it finds one that's True, it runs that block and skips all the rest.

grade = 85

if grade >= 90:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("F")

Output:

B

Python checks: is 85 >= 90? No. Is 85 >= 80? Yes. It prints "B" and stops — it never looks at the elif grade >= 70 line.

You can have as many elif branches as you need. The else at the end is optional, but it's good practice — it catches anything that didn't match any condition.

time_of_day = 14   # 2 PM in 24-hour format

if time_of_day < 12:
    print("Good morning!")
elif time_of_day < 17:
    print("Good afternoon!")
elif time_of_day < 21:
    print("Good evening!")
else:
    print("Good night!")

Output:

Good afternoon!

Your turn: Write a program that asks the user for a temperature (in Celsius) and prints:

  • "Freezing" if below 0
  • "Cold" if 0 to 10
  • "Mild" if 11 to 20
  • "Warm" if 21 to 30
  • "Hot" if above 30

Logical Operators: and, or, not

Sometimes one condition isn't enough. You want to check two things at once, or the opposite of a condition. That's what logical operators are for.

and — Both must be True

age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("You can enter the concert.")
else:
    print("You cannot enter.")

Output:

You can enter the concert.

With and, the whole condition is True only if both sides are True. If either one is False, the whole thing is False.

print(True and True)    # True
print(True and False)   # False
print(False and True)   # False
print(False and False)  # False

or — At least one must be True

is_weekend = False
is_holiday = True

if is_weekend or is_holiday:
    print("No work today!")
else:
    print("Back to work.")

Output:

No work today!

With or, the whole condition is True if at least one side is True.

print(True or True)    # True
print(True or False)   # True
print(False or True)   # True
print(False or False)  # False

not — Flips True to False and vice versa

is_logged_in = False

if not is_logged_in:
    print("Please log in first.")

Output:

Please log in first.

not True is False. not False is True. It reverses the value.

Combining them

You can chain logical operators together. Use parentheses to make the logic clear.

age = 20
has_id = True
is_member = False

if age >= 18 and has_id and (is_member or age >= 21):
    print("Access granted.")
else:
    print("Access denied.")

When combining multiple conditions, parentheses work just like in math — they group things and control the order of evaluation.

Your turn: Write a program that asks for a username and password (just use input()). If the username is "admin" and the password is "1234", print "Access granted." Otherwise print "Access denied."

Nested if Statements

You can put an if inside another if. This is called nesting.

score = 88
completed_bonus = True

if score >= 80:
    print("You passed!")
    if completed_bonus:
        print("And you earned a bonus star!")
    else:
        print("Complete the bonus task for an extra star.")
else:
    print("You didn't pass. Keep trying.")

Output:

You passed!
And you earned a bonus star!

The inner if only runs if the outer if already passed. Each level of nesting adds another 4 spaces of indentation.

A word of caution: Nesting more than 2 or 3 levels deep makes code very hard to read. When you find yourself going deeper than that, there's almost always a cleaner way to write it. You'll learn those techniques as you progress through the book.

Your turn: Write a program that asks for a number. First check if it's positive or negative (or zero). If it's positive, also check if it's even or odd. Print the result.

Putting It All Together: A Number Classifier

Here's a program that uses everything from this chapter.

number = int(input("Enter a number: "))

if number > 0:
    print(f"{number} is positive.")
    if number % 2 == 0:
        print("It's also even.")
    else:
        print("It's also odd.")
    if number > 1000:
        print("That's a big number!")
elif number < 0:
    print(f"{number} is negative.")
    if number < -1000:
        print("That's a very small number!")
else:
    print("You entered zero.")

print("Done.")

Sample run with 42:

Enter a number: 42
42 is positive.
It's also even.
Done.

Sample run with -2500:

Enter a number: -2500
-2500 is negative.
That's a very small number!
Done.

Sample run with 0:

Enter a number: 0
You entered zero.
Done.

Notice "Done." always prints — it's outside all the if blocks, so it runs no matter what the user enters.

What You Learned in This Chapter

  • bool is a data type with two values: True and False.
  • Comparison operators (==, !=, <, >, <=, >=) return True or False.
  • = is assignment. == is comparison. Never mix them up.
  • input() always returns a string. Use int() or float() to convert it to a number.
  • if runs a block when a condition is True.
  • else runs when the if condition is False.
  • elif adds more branches — Python checks each one in order and runs the first True one.
  • and requires both conditions to be True.
  • or requires at least one condition to be True.
  • not flips True to False and False to True.
  • Nested if statements let you check conditions inside conditions.
  • Indentation (4 spaces) defines which code belongs to which block. It is not optional.

What's Next?

Your programs can now decide — but they still do each thing only once. What if you want to do something ten times, or a hundred times, or until the user says stop?

In Chapter 5, you'll learn about loops. A loop lets you repeat a block of code without writing it over and over. It's one of the most powerful ideas in all of programming, and once you have it, you can build things you couldn't even attempt before.

Your turn: Build a simple number guessing game. Set a secret number with secret = 7. Ask the user to guess a number. If they guess too low, print "Too low!" If they guess too high, print "Too high!" If they get it right, print "You got it!" (Don't worry about letting them guess more than once — that's a loop, and it's coming in the next chapter.)

© 2026 Abhilash Sahoo. Python: Zero to Hero.