edubun
English

Making decisions with if

Python checks if and each elif from the top and runs only the first branch whose condition is True; the rest are skipped.

A ticket price that depends on age

Here is a problem to try before any new syntax. A small science museum (made up for this example) charges nothing for children under 7, 3,000 won for ages 7 to 18, and 5,000 won for everyone else. Given an age, the program should print the price. Write the rule in plain words first, as a list of questions in the order you would ask them at the ticket desk.

You probably wrote something like this: is the visitor younger than 7? If yes, free, and stop. If not, are they 18 or younger? If yes, 3,000 won, and stop. Otherwise, 5,000 won. That is already the program. Python spells "if", "otherwise if" and "otherwise" as if, elif and else.

age = 12
if age < 7:
    price = 0
elif age <= 18:
    price = 3000
else:
    price = 5000
print(price)
Output
3000

Three details of the syntax matter. Each condition line ends with a colon. The lines that belong to a branch are indented, and the Python tutorial recommends four spaces. When the indentation ends, the branch ends, which is why print(price) runs whatever the age. And only one branch runs: for age 12, the first condition is False, the second is True, so price becomes 3000 and the else is never looked at.

Comparisons give True or False

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal to5 != 5False
<less than3 < 7True
<=less than or equal to7 <= 7True
>greater than3 > 7False
>=greater than or equal to18 >= 19False

Note the double equals. One = assigns a value, two == compare. Strings can be compared too: "kimchi" == "Kimchi" is False, because capital letters count as different characters.

The order of the elif lines changes the answer

Because Python stops at the first True condition, the order of the branches matters. Grading a score is the classic case. Check for 90 and above first, then 80, then 70. Put the 70 check first and a score of 95 is caught by it and gets a C, since 95 >= 70 is also True.

An if/elif/else chain is a ladder. Python goes down until a condition is True, runs that one branch, and jumps past the rest.
score = 95
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "D"
print(grade)
Output
A

and, or, not join conditions

and is True only when both sides are True. or is True when at least one side is. not flips True and False. A condition such as "between 13 and 18" can be written age >= 13 and age <= 18, or in Python's shorter form 13 <= age <= 18. A condition can also sit inside another branch, which is called nesting. The Korean middle-school informatics curriculum names both, logical operations and nested control structures, in one of its programming standards.

age = 15
has_ticket = True
if 13 <= age <= 18 and has_ticket:
    print("Teen entry")
if not has_ticket or age < 7:
    print("See the desk")
else:
    print("Go in")
Output
Teen entry
Go in
ifRuns the indented lines only when the condition is True
elif"Otherwise, if": checked only when everything above was False
elseRuns when no condition above was True
==Compares two values; = assigns
and / or / notBoth true / at least one true / the opposite
indentationFour spaces that mark which lines belong to a branch
  1. What does this print?
    x = 8
    if x > 5:
        print("big")
    else:
        print("small")
  2. What does this print?
    age = 7
    if age < 7:
        print("free")
    elif age <= 18:
        print("3000")
    else:
        print("5000")
  3. What does this print?
    score = 85
    if score >= 70:
        print("C")
    elif score >= 80:
        print("B")
  4. What does this print?
    x = 3
    if x > 5:
        print("A")
    print("B")
    • A
      B
    • B
    • A
    • (nothing)
  5. What does this print?
    print(5 == 5.0, "a" == "A")
  6. What does this print?
    t = 30
    print(t > 25 and t < 28)
  7. What does this print?
    rain = False
    print(not rain)
  8. What does this print?
    n = 14
    if n % 2 == 0:
        if n > 10:
            print("big even")
        else:
            print("small even")
    else:
        print("odd")
  9. Which line correctly checks whether x is 10?
    • if x = 10:
    • if x == 10:
    • if x == 10
    • if (x = 10)
  10. Put the lines in order so the program prints "Even".
    Output
    Even
Common mistakes
  • "if score = 90: checks whether score is 90." One = is assignment. Python stops with SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? Write if score == 90:.
  • "if answer == "yes" or "y": catches both answers." Python reads it as (answer == "yes") or ("y"), and a non-empty string such as "y" counts as true, so the condition is always true. Write answer == "yes" or answer == "y".
  • "Indentation is just for looks." In Python it decides which lines belong to the branch. Forgetting it stops the program with IndentationError: expected an indented block after 'if' statement on line 2.
Teacher's noteStarting from the ticket desk works because learners already know the decision; the only new thing is the spelling. Ask them to say the rule aloud in order before typing. The wrong-order grading program is worth running deliberately: it prints C for 85 without any error, which is a first taste of a logic error. When checking work, test the boundary values (6, 7, 18, 19 for the ticket problem), since off-by-one mistakes between < and <= hide there. The Korean middle-school informatics curriculum has a standard on logical operations and nested control structures.
Key points
  • if / elif / else: only the first True branch runs.
  • Condition lines end with :, and the branch is indented four spaces.
  • == compares; = assigns.
  • Put the strictest condition first in an elif chain.
  • and, or and not combine conditions.
Sources for this course (6)
  • Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
  • Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
  • Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
  • General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
  • Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
  • Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)

Checked: 2026-10-19