Conditional Statements in Python

Theory

Until now, our programs ran line by line. A conditional changes that flow: depending on a condition, the program chooses one of several paths.

Motivating example: absolute value

Given an integer x, print its absolute value. If x > 0, print x; otherwise print -x.

x = int(input())
if x > 0:
    print(x)
else:
    print(-x)

How it works:

  • if is followed by a condition and a colon :.
  • The indented block under if runs when the condition is True.
  • else: introduces the alternative block, which runs when the condition is False.

Syntax you’ll use

if CONDITION:
    # Block 1
else:
    # Block 2

Block 1 runs if CONDITION is true. Otherwise, Block 2 runs.

Single-branch (“incomplete”) if

You can omit else. Only the if block runs when the condition is true; the rest of the program continues regardless.

x = int(input())
if x < 0:
    x = -x  # change only when needed
print(x)    # always runs

Multiple choices: ifelifelse

Use elif (“else if”) for more than two branches.

score = int(input("Score: "))

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

print(grade)

Indentation = block structure

  • All lines belonging to the same block must have the same indentation.
  • Recommended: 4 spaces per indentation level.
  • Do not mix tabs and spaces (it can cause errors). Configure your editor to insert spaces on Tab.

Python vs other languages: Python uses indentation to mark blocks. Languages like C, C++, Java, and JavaScript use braces { ... }, while Pascal uses begin ... end and Ruby uses end.

Conditions & truthiness

  • Common comparison operators: ==, !=, <, <=, >, >=.
  • Logical operators: and, or, not.
  • “Falsy” values: 0, 0.0, "", [], {}, set(), None. Everything else is “truthy”.
name = input("Name (optional): ")
if name:  # empty string is False
    print("Hello,", name)
else:
    print("Hello!")

Clean patterns

1) Guard clause (early exit)

def abs_val(x):
    if x >= 0:
        return x
    return -x

2) Conditional expression (one-liner)

x = int(input())
abs_x = x if x >= 0 else -x
print(abs_x)

Common mistakes (and fixes)

  • Forgetting the colon after if/elif/else.
  • Inconsistent indentation (mixing tabs/spaces or misaligned blocks).
  • Assignment vs comparison: use == to compare, not =.
  • Unreachable code: placing code after a return in the same block.

Quick practice

  1. Read an integer and print even if it’s even, otherwise odd.
  2. Given two integers, print the larger one (no built-ins like max).
  3. Classify a number: positive, negative, or zero.
Show sample solutions
# 1) even / odd
n = int(input())
if n % 2 == 0:
    print("even")
else:
    print("odd")

# 2) larger of two
a = int(input())
b = int(input())
if a >= b:
    print(a)
else:
    print(b)

# 3) sign
x = int(input())
if x > 0:
    print("positive")
elif x < 0:
    print("negative")
else:
    print("zero")

Key takeaways: end your conditions with :, use consistent 4‑space indentation, and choose among if, if/else, and if/elif/else based on how many paths you need.

Problems

Maximum of Two Numbers

Leap Year

Determine whether the given year is a leap year. (A leap year is divisible by 4 but not by 100, unless it is also divisible by 400.)

Rook

Determine whether a rook on a square with given coordinates (row and column) attacks a piece on another specified square.

Bishop

Determine whether a bishop on a square with given coordinates (row and column) attacks a piece on another specified square.

Queen

Determine whether a queen on a square with given coordinates (row and column) attacks a piece on another specified square.

Knight

Determine whether a knight on a square with given coordinates (row and column) attacks a piece on another specified square.

Chocolate Bar

Given a chocolate bar of size n × m squares, determine if it is possible to break off exactly k squares with a single straight-line break between squares (splitting into two rectangles).

Counters

Each edge square of a square board is given one counter. Could there be exactly k counters placed? (For example, a 2×2 board has 4 counters, a 6×6 board has 20.)

Equation

Solve the linear equation ax + b = 0 in integers.

Complex Equation

Solve the rational equation (ax + b) / (cx + d) = 0 in integers.

Change

An item costs a roubles and b kopeks. It was paid with c roubles and d kopeks. How much change should be returned?

Ice Cream

Ice cream is sold in packs of 3 and 5 scoops. Can exactly k scoops be bought?

Cutlets

You can fry k cutlets at once in a pan. Each cutlet must be fried m minutes per side without interruption. What is the minimum time required to fry n cutlets on both sides?

Coordinate Quadrants

Given coordinates of two points on a plane, determine if they lie in the same quadrant (all coordinates are non-zero).

Which Number Is Greater?

-

Maximum of Three

-

Is the Triangle Possible?

-

How Many Are Equal? (Among Three Numbers)

-

King’s Move

A square on a chessboard is identified by two numbers (a, b) from 1 to 8. The first is the column, the second is the row. Given two squares, determine if a king can move from the first to the second in one move.

Quadratic Equation

Given real numbers a, b, c, find all solutions of the quadratic equation ax² + bx + c = 0.

Triangle Type

Determine the type of triangle (acute, obtuse, or right-angled) based on its side lengths.

Cows

Given a number n, complete the phrase “On the meadow grazes...” with the correct form of the word “cow” in Russian.

Tube Tickets

A tube ticket for 1 trip costs 15 roubles, for 10 trips – 125 roubles, and for 60 trips – 440 roubles. A passenger plans to take n trips. Determine how many of each ticket type should be purchased to cover at least n trips at the lowest cost.

Tube Tickets – 2

A tube ticket for 1 trip costs 15 roubles, 5 trips – 70 roubles, 10 trips – 125 roubles, 20 trips – 230 roubles, and 60 trips – 440 roubles. A passenger plans to take n trips. Determine the optimal combination of tickets to cover at least n trips for the lowest total price.

Neighbour Coordinates

For a cell at coordinates (x, y) in a table of size M × N, output the coordinates of its neighbours. Neighbours share a side with the given cell.

Even and Odd Numbers

Given three integers A, B, and C, determine if there is at least one even and one odd number among them.

Roman Numerals

Given a number X, convert it to Roman numerals.

Sign of a Number

The mathematical function sign(x) is defined as: sign(x) = 1 if x > 0, sign(x) = -1 if x < 0, sign(x) = 0 if x = 0. Output the value of sign(x) for the given number.

Test System

In one of the problems on the site, the condition says: “If the given four-digit number is symmetric, output 1, otherwise output any other integer.” A pupil believes they solved the problem, but the system rejects it. They think it’s because they returned a different “any other number” than the expected one. Write a program that compares the system’s expected output and the student’s answer, and checks if the solution is correct.

Sort Three Numbers

You are given three numbers in separate lines. Sort them in non-decreasing order. The program must read a, b, c, reorder their values to ensure a ≤ b ≤ c, and output them.

FAQ

Find quick answers to common questions about our lessons, pricing, scheduling, and how Exact Science can help your child excel.
Where do you hold your classes?
We hold our classes online or on-site on Saturdays at our branch in Pimlico Academy, London.
You can find our timetable here.
What do you need to start learning online?
For lessons you only need a computer or phone with a microphone, camera and Internet access. Wherever you are - in London, Nottingham, New York or Bali - online lessons will be at hand.
When can I take the trial lesson?
You can get acquainted with the school at any time convenient for you. To do this, just leave a request and sign up for a lesson.
What should I expect from the trial lesson?
The trial lesson is a 30-minute online session designed to get a sense of how your child approaches mathematical thinking and problem solving. (In practice, it often runs a bit longer if the student is engaged!)

We typically explore a range of fun and challenging problems drawn from competitions. We adapt the difficulty based on how the student responds, aiming to make it both accessible and stimulating.

After the session, we’ll have a quick conversation with the parent to share observations and suggest a personalised path forward.
I can't attend class, what should I do?
It is OK, it happens! Students have the opportunity to cancel a lesson up to 8 hours before the scheduled time without loss of payment. So you can reschedule it for a convenient time, and the teacher will have the opportunity to
I don't have much free time, will I have time to study?
Learning can take place at your own pace. We will select a convenient schedule and at any time we will help you change the schedule, take a break or adjust the program.
How long is one lesson?
All classes last 1 hour.

Meet our team

Our teachers will tell you how to prepare for exams, help you cope with difficult tasks and win the Olympiad

They will tell you about the pitfalls of exams and the most common mistakes, and explain how to avoid them
George Ionitsa
Founder &
Maths and Coding Coach

What our students and parents say about learning with us

"Olympiad Maths Lessons helped me a lot to get the Gold medal in Junior Maths Challenge"
St. Paul's Student
"Thanks to the 'Data Science' and 'Coding in Python' lessons I got accepted to my dream university."
Michael
Data Science Student
Warwick University
"Great courses, which thoroughly explained topics beyond the capability of the GCSE answer sheet. Thanks so much."
Ivan
GCSE Student in Dubai
"Financial Mathematics! Best course to understand Python and Mathematics behind Finance!"
Gleb
VC Investor
"We got silver in PMC! Thanks George!"
Mum of St. Paul's Student
Prepare for the Primary Maths Challenge
"My daughter took a batch of 10 classes with George to understand Python with Turtle. I found George extremely knowledgeable and accessible."
Dad of Latymer School Student
Python with Turtle