Skip to content
Educora
IntermediateGrade 824 min30 / 59

The conditional statement: if, elif, else and compound conditions

Comparisons, the full and incomplete `if`, `elif` chains, nested conditions, `and`, `or`, `not` and conditions built on remainders — with exam-style tracing, “how many times `Yes`?” and written-program tasks.

Check yourself
In this lesson you will learn
  • Work out the result (True / False) of comparisons, including comparisons of strings.
  • Write full and incomplete if statements, elif chains and nested conditions, and trace which branch runs.
  • Evaluate compound conditions with and, or, not in the correct order of priority.
  • Write programs that solve repeating-pattern problems with remainder conditions (n % k).

An ATM gives money when the PIN is typed correctly and shows a warning when it is wrong; at a traffic light we cross on green and stop on red. A program must also choose what to do depending on the situation. In a flowchart this is a branch drawn as a rhombus (see “Algorithms and flowcharts” and “Branching algorithms”); in Python it is written with the conditional statement if. Every paper of the 2025–2026 entrance exams had 2–3 tasks on the conditional statement, sometimes including a written program.

Comparisons: when is a condition true?

A condition is an expression whose value is True or False. The simplest conditions are built with comparison operators. Note: equality is written with two equals signs, ==, because a single = is assignment.

OperatorMeaningExample
==is equal to7 == 7 → True
!=is not equal to7 != 7 → False
< >less than, greater than3 > 8 → False
<= >=less or equal, greater or equal8 >= 8 → True

Strings are compared character by character, by the codes of the characters — like words in a dictionary: 'apple' < 'apricot' is true because at the third character p comes before r. Capital letters have smaller codes than small letters, so 'Z' < 'a' is also true. Strings of digits are compared character by character too: '10' < '9' is true ('1' < '9'), although 10 > 9. A number is never equal to a string: 5 == '5' → False. Python also allows double inequalities: 10 <= n <= 99 means “n is a two-digit number”.

The value of a condition is an ordinary value: you can print it (print(7 > 3) → True) and store it in a variable: even = n % 2 == 0. Here the comparison n % 2 == 0 is computed first, then True or False is assigned to even; after that if even: is enough. Splitting long conditions into such parts makes a program easier to read.

The full and the incomplete if

Definition
Incomplete and full if

The incomplete form has only the if part: if the condition is true, the block runs; if it is false, nothing happens. The full form is if … else: exactly one of the two branches always runs — the if block when the condition is true, the else block when it is false.

Writing rules: a colon (:) follows the condition, and the commands of a branch are written with indentation — usually 4 spaces. Consecutive lines with the same indentation form one block: when the indentation ends, the block ends. else is written at the same indentation as its if. Commands that follow the conditional statement without indentation run in both cases.

Python
n = 38
if n % 5 == 3:
    print(n // 5)
else:
    print(n % 5)
print('end')
▸ Expected output
7
end
38 % 5 = 3, the condition is true and 38 // 5 = 7 is printed. print('end') has no indentation, so it runs in any case. Set n = 41 and run again: this time the else branch works.
Python
x = 12
y = 5
if x % y == 2:
    y = x * 2
    print(x, y)
    x = y - x
y = y + 1
print(x, y)
▸ Expected output
12 24
12 25
The program of Example 1.
Example 1. Commands after the condition (coded answer)

What will the program above print? Write both lines.

Show solution
x % y = 12 % 5 = 2, the condition is true and the block runs:
y = 12 · 2 = 24; print(x, y) → 12 24; x = 24 − 12 = 12.
After the block come the unindented commands: y = 24 + 1 = 25; print(x, y) → 12 25.
The answer is two lines: 12 24 and 12 25. Trap: whoever computes the unindented y = y + 1 with the starting y = 5 writes “12 6”.

elif chains and nested conditions

When there are more than two choices, elif (“else if”) is used. Conditions are checked from top to bottom; the branch of the first true condition runs and the rest of the chain is skipped — even if later conditions are also true. If no condition is true, the final else runs (if there is none, nothing happens). That is why the order of the conditions matters: if if n > 10 comes before elif n > 100, the second branch can never run.

condition 1true?yesbranch 1nocondition 2true?yesbranch 2noelse branchnext statement
The if … elif … else chain: conditions are checked from top to bottom, the branch of the first true condition runs, then the program continues after the chain.
Python
s = 'k'
b = 'm'
if s == b:
    print('A')
elif s < b:
    print('B')
elif s == 'k':
    print('C')
else:
    print('D')
▸ Expected output
B
The program of Example 2. In the exam the first line is s = input().
Example 2. A character is typed

If the letter k is typed on the keyboard, what does the program above print?
A) A B) B C) C D) D E) nothing

Show solution
s == b → 'k' == 'm' ✗.
s < b → 'k' < 'm' ✓ (k comes before m in the alphabet) → B is printed.
The rest of the chain is not checked, although s == 'k' was true as well. Answer: B.

A branch can contain another conditional statement — this is a nested condition. The inner if is checked only when the outer condition is true. Only the indentation decides which else belongs to which if: an else belongs to the nearest if above it that has the same indentation. Exam programs often nest conditions 2–3 levels deep, so trace them systematically.

  1. 1
    Write the starting values

    Copy the variables and their starting values (including the input values) into a table.

  2. 2
    Evaluate the condition: ✓ or ✗

    Compute the condition with the current values and write ✓ (true) or ✗ (false) next to it.

  3. 3
    If ✗, skip the block

    Skip all lines with a bigger indentation and go to the elif / else at the same indentation or, if there is none, to the line after the block.

  4. 4
    If ✓, enter the block

    Carry out the commands, update the variables and repeat steps 2–3 for inner conditions. Once a branch has run, the remaining elif / else parts of that chain are skipped.

  5. 5
    Do not forget the commands after it

    The unindented lines after the conditional statement always run — the answer is often produced exactly there.

Python
a = 36
b = 14
if a % b > 5:
    a = a - b
    if a > 2 * b:
        b = b + 3
    else:
        b = b - 3
        if b % 2 == 1:
            a = a + 1
else:
    a = a + b
print(a + b, a - b)
▸ Expected output
34 12
The program of Example 3: conditions nested three levels deep.
Example 3. An exam-style closed task: nested conditions

Determine the result of the program above.
A) 39 5 B) 33 11 C) 34 12 D) 58 14 E) 22 11

Show solution
1) a % b = 36 % 14 = 8; 8 > 5 ✓ → a = 36 − 14 = 22.
2) a > 2 · b → 22 > 28 ✗ → the else branch: b = 14 − 3 = 11.
3) Inner condition: b % 2 == 1 → 11 % 2 = 1 ✓ → a = 22 + 1 = 23.
4) The outer else is skipped. print(a + b, a - b) → 23 + 11 = 34, 23 − 11 = 12.
Answer: C) 34 12. Option B is for those who forget the inner if (a = 22, b = 11), option A for those who take the wrong branch (b = 17).

Compound conditions: and, or, not

Several conditions are joined with logical operators: and is true when both conditions are true; or is true when at least one is true; not reverses the value of a condition. These are the conjunction, disjunction and inversion of the lesson “Boolean logic and logic gates”.

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue
arithmetic → == != < > <= >= → not → and → or

Priority decreases from left to right: arithmetic first, then comparisons, then not, and and finally or. When in doubt, add brackets — the program becomes both correct and readable.

Ready-made patterns for intervals: x lies in [10, 20] — 10 <= x <= 20 (that is, x >= 10 and x <= 20); x lies outside it — x < 10 or x > 20, which is the same as not (10 <= x <= 20). Careful: writing and in the “outside” condition is a mistake — no number is both less than 10 and greater than 20 at the same time, so such a condition is always false.

Example 4. Priority makes a difference

With x = 7 and y = 2, evaluate: 1) x > 5 or y > 3 and x < 0; 2) not x > 5 and y == 2; 3) (x > 5 or y > 3) and x < 0.

Show solution
1) and first: y > 3 and x < 0 → ✗ and ✗ = False; then x > 5 or False → ✓ or ✗ = True.
2) not is done after the comparison but before and: not (7 > 5) = not True = False; False and … = False.
3) Brackets first: x > 5 or y > 3 = True; True and x < 0 = ✓ and ✗ = False.
Expressions 1 and 3 differ only by the brackets, yet their results are opposite.
Example 5. How many times is “Yes” printed?

The program is run 10 times in a row, and each time a pair (s, t) is typed: (9, 4); (9, 6); (2, 5); (−1, 3); (8, 8); (0, 0); (12, 9); (−5, −5); (7, 1); (10, 11). How many times is Yes printed? (In the Azerbaijani exam the program usually prints the words for “yes” / “no”.)
s = int(input())
t = int(input())
if s >= 8 and t % 3 != 0 or s < 0:
    print('Yes')
else:
    print('No')

Show solution
Because and is done before or, the condition reads (s >= 8 and t % 3 != 0) or s < 0.
• Pairs with s < 0 give Yes at once: (−1, 3), (−5, −5) — 2 pairs.
• For the others s ≥ 8 is needed and t must not be divisible by 3: (9, 4) ✓, (9, 6) ✗ (6 % 3 = 0), (8, 8) ✓, (12, 9) ✗ (9 % 3 = 0), (10, 11) ✓ — 3 pairs.
• In (2, 5), (0, 0), (7, 1) s < 8 → No.
Total: 2 + 3 = 5.
Python
pairs = [(9, 4), (9, 6), (2, 5), (-1, 3), (8, 8),
         (0, 0), (12, 9), (-5, -5), (7, 1), (10, 11)]
count = 0
for s, t in pairs:
    if s >= 8 and t % 3 != 0 or s < 0:
        count = count + 1
print(count)
▸ Expected output
5
Check: here a for loop (next lesson) tests the same condition for each of the 10 pairs and counts the Yes answers.
Python
x = 3
y = 5
if x * y > 15:
    print('#')
elif y ** x != 125:
    print('# #')
else:
    print('# # # #')
if y // x == 1:
    print('# # #')
▸ Expected output
# # # #
# # #
The program of Example 6.
Example 6. Counting the printed symbols

How many # symbols are printed after the program above runs?
A) 1 B) 3 C) 4 D) 7 E) 10

Show solution
First conditional statement: x · y = 15, 15 > 15 ✗; elif: 5 ** 3 = 125, 125 != 125 ✗ → else: # # # # (4 symbols).
Second, separate if: y // x = 5 // 3 = 1, 1 == 1 ✓ → # # # (3 symbols).
Total D) 7. The second if is a statement of its own and is checked whatever the first one did.

Remainder conditions and a written task

The exam’s favourite conditions are built on remainders. Learn to recognise them at a glance:

  • n % 2 == 0 — n is even; n % 2 == 1 — n is odd;
  • n % k == 0 — n is divisible by k; n % k != 0 — it is not;
  • n % 10 == 7 — the last digit is 7; n // 10 % 10 == 3 — the tens digit is 3;
  • n % 3 == 0 and n % 5 == 0 — n is divisible by 15;
  • repeating pattern: if something repeats every k steps, n % k shows where n sits in the pattern.

Let us apply the last idea to a written task. The natural numbers are written into a 4-column table like a “snake”: left to right in odd rows and right to left in even rows.

ABCD
1234
8765
9101112
16151413
…………
Example 7. Written task: which column holds the number?

Write a Python program that reads a natural number n (1 ≤ n ≤ 1000) and prints the column of the table above that contains it. For example: input 6 → output C; 13 → D; 16 → A; 26 → B.

Show solution
1) The pattern repeats every 8 numbers (two rows = 8 cells), so we look at the remainder r = n % 8.
2) From the first two rows we read where each remainder sits: r = 1 → A, 2 → B, 3 → C, 4 → D, 5 → D, 6 → C, 7 → B, 0 → A (8, 16, 24, … are in column A).
3) Group them: A — r = 0 or 1; B — 2 or 7; C — 3 or 6; D — the remaining 4 and 5.
4) Turn this into an if … elif … else chain (the program is below). Check: 26 % 8 = 2 → B ✓, 13 % 8 = 5 → D ✓.
Python
n = 26
r = n % 8
if r == 0 or r == 1:
    print('A')
elif r == 2 or r == 7:
    print('B')
elif r == 3 or r == 6:
    print('C')
else:
    print('D')
▸ Expected output
B
The solution of the written task. On the answer sheet the first line must be n = int(input()); here it is n = 26 so that it runs in the browser. Try 6, 13 and 16 as well.

A written task needs a complete program: input (int(input())), computation (here the remainder and the conditions) and output (print). DİM does not publish the marking criteria of the written tasks, so write every part clearly and check your program step by step against all cases of the example table and against the “border” values (here numbers with remainder 0, such as 8 and 16).

Exercise

A traffic light works in a cycle: in every 60 seconds it is green (green) for the first 30 seconds, yellow (yellow) for the next 5 and red (red) for the remaining 25; counting starts at second 0. Write an if … elif … else so that the program prints the colour for each moment (the for loop over the given moments is ready).

Exercise · Python
for t in [10, 33, 50, 1000, 1234]:
    r = t % 60
    colour = '?'
    # choose the colour with if / elif / else
    print(t, colour)
▸ Expected output
10 green
33 yellow
50 red
1000 red
1234 yellow
Exercise

A year is a leap year (366 days) if it is divisible by 4 but not by 100, or if it is divisible by 400. Replace False in leap with this compound condition so that the program prints the right answer for the four years.

Exercise · Python
for y in [2024, 2100, 2000, 2026]:
    leap = False  # write the condition here
    if leap:
        print(y, 'Yes')
    else:
        print(y, 'No')
▸ Expected output
2024 Yes
2100 No
2000 Yes
2026 No

Key points

  • A condition is an expression worth True or False: equality is ==, inequality !=; strings are compared character by character by their codes ('10' < '9').
  • In an incomplete if the branch may run or not; in a full if … else exactly one of the two branches runs. A block is defined by its indentation.
  • In an if … elif … else chain only the branch of the first true condition runs; separate if statements are each checked on their own.
  • Priority: arithmetic → comparison → not → and → or; when in doubt, use brackets.
  • Even/odd, divisibility and repeating patterns (columns, weekdays, traffic lights) are split into branches with the remainder n % k.

Check yourself

12 questions. Every correct answer earns XP.

1 / 12
Which operator checks whether two values are equal in Python?