📘 CodingMarble Learn

Control Statements in Python: if-else, while and for

Normally Python runs lines one after another (sequence). Control statements change this flow. if-else chooses one of two paths; if-elif-else picks the first true condition from many. while repeats a block while a condition is true; for repeats once for each item of a sequence such as range(start, stop, step).

🎬 Step-by-step story

  1. if-else is a fork: True takes one path, False takes the other.
  2. if-elif-else is a ladder: the first true condition wins, the rest are skipped.
  3. while repeats a block as long as its condition stays true.
  4. for visits each item of a sequence, one by one.
  5. range(start, stop, step) makes the numbers; stop is not included.
  6. Your turn: move the marks slider and watch the ladder decide the grade.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Can both the if block and the else block run?

No. The condition is either True or False, so exactly one of them runs.

If two elif conditions are True, which one runs?

Only the first True one from the top. Python skips everything below it.

Why did my while loop never stop?

The variable in the condition was never changed inside the loop, so the condition stayed True. Add a line like i += 1.

Why does range(1, 6) stop at 5?

range never includes stop. Think of stop as "the first number NOT wanted". This makes range(n) give exactly n numbers.

Can a for loop go over a string?

Yes. for ch in "hello" takes each letter in turn. It works on lists, tuples and dictionaries too.

Flow of control

The order in which lines run is the flow of control. There are three kinds:

The lines inside each statement form a block and must be indented.

if and if-else

if condition:
    block A        # runs when True
else:
    block B        # runs when False

The condition is any expression that gives True or False, like m >= 33. Only one of the two blocks runs. else is optional: a plain if runs its block only when True and does nothing otherwise.

n = int(input("Number: "))
if n % 2 == 0:
    print("Even")
else:
    print("Odd")

if-elif-else: many choices

Use elif ("else if") when there are more than two paths. Python checks from the top and runs the block of the first True condition, then skips the rest.

if m >= 90:
    grade = "A"
elif m >= 75:
    grade = "B"
elif m >= 60:
    grade = "C"
elif m >= 33:
    grade = "D"
else:
    grade = "Retry"

Order matters. If m >= 33 came first, 95 marks would get grade D.

An if inside another if is a nested if.

The while loop

i = 1              # 1. start
while i <= 5:      # 2. check
    print(i)
    i += 1         # 3. change

The block repeats while the condition is True. You must start the variable before, and change it inside, or the loop never ends (an infinite loop). Use while when you do not know in advance how many times to repeat, e.g. "keep asking until the password is right".

The for loop and range()

for takes each item of a sequence (range, string, list) in turn.

total = 0
for n in range(1, 6):
    total += n
print(total)      # 15

range(stop): 0 to stop − 1. range(start, stop): start to stop − 1. range(start, stop, step): jumps by step; step can be negative to count down.

for ch in "IP":
    print(ch)     # I then P

while vs for

for: number of repeats known (a range or a list). while: repeat until a condition changes.

Extra: break leaves a loop at once; continue skips to the next round.

Try it: trace table

On paper, make a table with columns i and output. Trace i = 10; while i > 0: print(i); i -= 3 by hand. Then run it. Did you get 10, 7, 4, 1? Next, use the slider in step 6 of the 3D: find the smallest marks that give grade B.

Key formulas and definitions

Worked examples

1. Write a program to print whether a number is positive, negative or zero.

n = int(input()) if n > 0: print("Positive") elif n < 0: print("Negative") else: print("Zero")

2. What does this print? i = 1 while i < 10: print(i, end=" ") i *= 2

i = 1, 2, 4, 8 are all < 10, then i = 16 stops it. Output: 1 2 4 8

3. Find the sum of the first 10 natural numbers using for.

s = 0 for n in range(1, 11): s += n print(s) → 55. Check: 10 × 11 ÷ 2 = 55.

4. List the values from range(15, 2, -4).

Start 15, go down by 4, stop before 2: 15, 11, 7, 3.

5. Print the multiplication table of 7 (7 × 1 to 7 × 10).

for i in range(1, 11): print(7, "x", i, "=", 7 * i)

6. Find the factorial of 5 with a while loop.

f = 1; n = 5 while n > 1: f *= n; n -= 1 Trace: f = 5, 20, 60, 120. Output 120.

7. How many times does the body run? for k in range(3, 20, 5)

k = 3, 8, 13, 18 → 4 times.

Common mistakes

Practice quiz

1. How many values does range(2, 8) give?
2. In an if-elif-else ladder, how many blocks run?
3. Which loop is best when the number of repeats is not known?
4. list(range(10, 0, -3)) is:
5. A loop whose condition never becomes False is:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What are control statements in Python?

Statements that change the normal top-to-bottom flow: selection (if, if-else, if-elif-else) and loops (while, for).

What is the difference between while and for?

for repeats over a known sequence (like range); while repeats as long as a condition is True, when the count is not known.

What does range(2, 10, 3) give?

2, 5, 8. Start at 2, add 3 each time, stop before 10.

Where this is taught

Canada (Ontario)Grade 11A. Programming Concepts and Skills
Canada (Ontario)Grade 11A. Programming Concepts and Skills
RomaniaClasa a X-aProgramming language basics
CBSE (India)Class 11Computational Thinking and Programming - 1
CBSE (India)Class 11Introduction to Python
USA (Common Core, NGSS, AP)Grade 10Big Idea 3: Algorithms and Programming
USA (Common Core, NGSS, AP)Grade 11Selection and Iteration
Japan高校1年Computers and programming
South Korea고등학교 2학년Algorithms and programming
South Korea고등학교 3학년Programming
Russia11 классAlgorithms and programming

Learn first

Learn next

Related lessons

All Informatics Practices lessons