Control Statements

Beginner-friendly teaching edition • decisions, loops, ranges, Boolean logic and basic statistics

Big idea: A Python program normally runs from top to bottom. Control statements let you change that flow—make a decision, repeat an action, skip an iteration, or stop a loop.

What You Will Learn

  • Make decisions with if, if...else and if...elif...else.
  • Repeat statements with while and for.
  • Use augmented assignments such as +=.
  • Use range() to generate sequences of integers.
  • Use sentinel-controlled iteration with while.
  • Create compound conditions with and, or and not.
  • Change loop flow with break and continue.
  • Use f-strings and format specifiers for readable output.
  • Use Decimal when monetary calculations require decimal precision.
  • Calculate mean, median and mode using the statistics module.

These topics follow the chapter's stated objectives and outline.

Chapter Structure

  1. Introduction
  2. Control Statements
  3. if Statement
  4. if...else and if...elif...else
  5. while Statement
  6. for Statement
  7. Iterables, Lists and Iterators
  8. Built-In range Function
  9. Augmented Assignments
  10. Sequence-Controlled Iteration; Formatted Strings
  11. Sentinel-Controlled Iteration
  12. Built-In Function range: A Deeper Look
  13. Using Type Decimal for Monetary Amounts
  14. break and continue
  15. Boolean Operators and, or, not
  16. Intro to Data Science: Mean, Median and Mode
  17. Wrap-Up

The source chapter organizes these topics as sections 3.1 through 3.15.

3.1 Introduction

Control statements control which code runs and how many times it runs. Python mainly gives us two kinds of control:

Selection → choose a pathIteration → repeat work

Selection uses if, if...else and if...elif...else. Iteration uses while and for. The chapter also introduces range(), sentinel-controlled loops, Decimal, f-strings and Boolean operators.

3.2 Control Statements

StatementSimple meaningTypical use
ifRun code when a condition is True.Check eligibility, score, age, etc.
if...elseChoose between two paths.Pass / fail, yes / no.
if...elif...elseChoose among multiple paths.Grade A/B/C/D/F.
whileRepeat while a condition remains True.Repeat until a target or sentinel is reached.
forRepeat once for every item in an iterable.Process characters, list items or a range.

This selection/iteration distinction is the chapter's basic model of control flow.

3.3 if Statement

An if statement checks a condition. If the condition is True, Python executes the indented suite. If it is False, Python skips it.

grade = 85

if grade >= 60:
    print('Passed')
How it works:
1. Python evaluates grade >= 60.
2. The result is True.
3. The indented print() executes.

Indentation is required. The statements belonging to the if must be indented. Four spaces are the convention used in the chapter.

Truthy and Falsey Values

Python can interpret expressions as True or False. A nonzero numeric value is treated as True and zero as False. A non-empty string is True, while an empty string is False.

if 1:
    print('1 is True')

if 0:
    print('0 is True')   # this does not execute
Common mistake: Do not confuse = and ==.
= means assignment. == asks whether two values are equal.

3.4 if...else and if...elif...else

Two Choices: if...else

grade = 57

if grade >= 60:
    print('Passed')
else:
    print('Failed')

Exactly one of the two suites runs: the if suite when the condition is True, otherwise the else suite.

Short Form: Conditional Expression

grade = 87
result = 'Passed' if grade >= 60 else 'Failed'
print(result)

This is useful when you simply need to choose one value based on a condition.

Many Choices: if...elif...else

grade = 77

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

Python checks conditions from top to bottom and stops at the first True condition. In the example, 77 produces C.

Remember: The else part is optional. Use it when you want a default action for all cases that did not match an earlier condition.

3.5 while Statement

A while loop repeats its suite while its condition remains True.

product = 3

while product <= 50:
    product = product * 3

print(product)

The values grow 3 → 9 → 27 → 81. When product <= 50 becomes False, the loop stops and the final value is 81.

Infinite loop warning: Something inside the loop must eventually make the condition False. If the condition never changes to False, the loop can continue forever.

3.6 for Statement

A for loop processes each item in an iterable one at a time.

for character in 'Programming':
    print(character, end=' ')

Output:

P r o g r a m m i n g

Python takes one character, runs the loop body, then takes the next character until there are no more items.

print() with end and sep

print(10, 20, 30, sep=', ')

Output:

10, 20, 30

end changes what print() writes after its arguments. By default it uses a newline. sep controls what appears between multiple arguments; its default is a space.

3.6.1 Iterables, Lists and Iterators

An iterable is an object from which Python can obtain items one at a time. Strings and lists are common examples.

total = 0

for number in [2, -3, 0, 17, 9]:
    total = total + number

print(total)

Output: 25.

The for statement uses an iterator behind the scenes to obtain consecutive items. Think of an iterator as a bookmark that remembers where it is in a sequence.

3.6.2 Built-In range()

range(10) represents the integers 0 through 9. The ending value is not included.

for counter in range(10):
    print(counter, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9
Off-by-one warning: range(9) produces 0 through 8, not 0 through 9.

The source explains that range() produces an iterable of consecutive integers starting at 0 and stopping before its argument.

3.7 Augmented Assignments

Augmented assignment is a shorter way to update a variable using its current value.

Long formShort formMeaning
total = total + numbertotal += numberAdd and assign
x = x - 2x -= 2Subtract and assign
x = x * 5x *= 5Multiply and assign
x = x ** 3x **= 3Exponentiate and assign
x = x / 2x /= 2Divide and assign
x = x // 2x //= 2Floor-divide and assign
x = x % 9x %= 9Remainder and assign

The chapter shows += as a concise replacement for repeating the same variable on both sides of the assignment.

3.8 Sequence-Controlled Iteration; Formatted Strings

In sequence-controlled iteration, the loop processes a known sequence of values. The chapter uses a class-average problem: ten grades are stored in a list, the loop adds each grade to a running total, counts the grades, and then calculates the average.

total = 0
grade_counter = 0
grades = [98, 76, 71, 87, 83, 90, 57, 79, 82, 94]

for grade in grades:
    total += grade
    grade_counter += 1

average = total / grade_counter
print(f'Class average is {average}')

Output: Class average is 81.7.

f-Strings

An f-string starts with the letter f. Curly braces contain values or expressions that Python inserts into the resulting string.

name = 'Ravi'
score = 92
print(f'{name} scored {score}')

Here {name} and {score} are replacement fields. The chapter introduces f-strings as a convenient way to insert values into formatted output.

3.9 Sentinel-Controlled Iteration

Sometimes we do not know in advance how many values the user will enter. A sentinel is a special value that tells the program, "stop reading input."

total = 0
grade_counter = 0

grade = int(input('Enter grade, -1 to end: '))

while grade != -1:
    total += grade
    grade_counter += 1
    grade = int(input('Enter grade, -1 to end: '))

if grade_counter != 0:
    average = total / grade_counter
    print(f'Class average is {average:.2f}')
else:
    print('No grades were entered')

Example output:

Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 72
Enter grade, -1 to end: -1
Class average is 85.67
Key idea: The sentinel -1 is not processed as a grade. It only signals that input is finished. The program also checks for zero entered grades before dividing.

Formatting to Two Decimal Places

average = 85.666666...
print(f'{average:.2f}')

.2f means: format as a floating-point value with two digits after the decimal point. Thus the result becomes 85.67.

3.10 Built-In Function range(): A Deeper Look

range() can take one, two or three arguments.

FormMeaningExample
range(stop)Start at 0; stop before stop.range(5) → 0,1,2,3,4
range(start, stop)Start at start; stop before stop.range(5, 10) → 5,6,7,8,9
range(start, stop, step)Move by step each time.range(0, 10, 2) → 0,2,4,6,8
for number in range(10, 0, -2):
    print(number, end=' ')

Output: 10 8 6 4 2. A negative step moves downward.

3.11 Using Type Decimal for Monetary Amounts

Normal floating-point numbers are useful for many scientific calculations, but some financial applications need decimal precision. Floating-point values are represented in binary and some decimal values are only approximations in memory.

from decimal import Decimal

principal = Decimal('1000.00')
rate = Decimal('0.05')

print(principal + Decimal('10.00'))

Decimal belongs to the Python Standard Library's decimal module, so it must be imported. The chapter recommends creating Decimal values from strings for these precise decimal calculations.

Compound Interest Example

The chapter calculates the amount after each year for a $1000 investment earning 5% annually, using the compound-interest formula:

a = p(1 + r)n
p = principal, r = annual interest rate, n = number of years, a = amount after n years
from decimal import Decimal

principal = Decimal('1000.00')
rate = Decimal('0.05')

for year in range(1, 11):
    amount = principal * (1 + rate) ** year
    print(f'{year:>2}{amount:>10.2f}')

The chapter's sample values progress from 1050.00 after year 1 to 1628.89 after year 10.

Understanding Format Specifiers

SpecifierMeaning
>2Right-align in a field of width 2.
10.2fRight-align a floating-point value in width 10 with two decimal places.
<Left-align a value.

This formatting makes the year and monetary amounts line up neatly in columns.

3.12 break and continue

break

break immediately exits a while or for loop.

for number in range(100):
    if number == 10:
        break
    print(number, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9

continue

continue skips the rest of the current iteration and moves to the next iteration.

for number in range(10):
    if number == 5:
        continue
    print(number, end=' ')

Output:

0 1 2 3 4 6 7 8 9

The chapter also notes that while and for can have an optional else clause, which runs when the loop terminates normally rather than because of break.

3.13 Boolean Operators: and, or and not

Comparison operators create simple conditions. Boolean operators combine those conditions into more complex decisions.

and — Both Conditions Must Be True

gender = 'Female'
age = 70

if gender == 'Female' and age >= 65:
    print('Senior female')

and is True only when both sides are True.

Expression 1Expression 21 and 2
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue

or — At Least One Condition Is True

semester_average = 83
final_exam = 95

if semester_average >= 90 or final_exam >= 90:
    print('Student gets an A')

or is False only when both sides are False.

Short-Circuit Evaluation

Python can stop evaluating a Boolean expression as soon as its final result is known. For and, a False left side is enough to make the whole expression False. For or, a True left side is enough to make the whole expression True.

not — Reverse True and False

grade = 87

if not grade == -1:
    print('The next grade is', grade)

not changes True to False and False to True. Often, the same condition can be written more naturally—for example, grade != -1.

Boolean Operator Precedence

Higher → LowerOperators
1()
2**
3* / // %
4+ -
5< <= > >= == !=
6not
7and
8or

This ordering is the chapter's precedence table for the operators introduced so far.

3.14 Intro to Data Science: Mean, Median and Mode

Descriptive statistics help us summarize a collection of data. This section introduces three measures of central tendency: mean, median and mode.

MeasureEasy meaningExample idea
MeanAverage value.Total ÷ number of values.
MedianMiddle value after sorting.For 5 values, the 3rd sorted value.
ModeMost frequently occurring value.The value appearing most often.

Calculate Mean Manually

grades = [85, 93, 45, 89, 85]
mean = sum(grades) / len(grades)
print(mean)

Output: 79.4. The built-in sum() calculates the total and len() gives the number of values.

Use the statistics Module

import statistics

grades = [85, 93, 45, 89, 85]

print(statistics.mean(grades))
print(statistics.median(grades))
print(statistics.mode(grades))

Output:

79.4
85
85

Sorting gives [45, 85, 85, 89, 93], so 85 is the middle value and also the most frequent value. If multiple values tie for most frequent, the chapter notes that statistics.mode() can raise StatisticsError.

Quick Concept Map

Conditionif / elif / elsewhileforrange()+=f-stringbreakcontinueand / or / notDecimalstatistics

Common Beginner Mistakes

  • Forgetting the colon after if, elif, else, while or for.
  • Using inconsistent indentation inside a suite.
  • Writing = when you mean ==.
  • Assuming range(stop) includes stop.
  • Creating a while loop whose condition never becomes False.
  • Forgetting to handle the zero-item case before calculating an average.
  • Using a regular floating-point value when an application requires decimal monetary precision.
  • Putting the else at the wrong indentation level.

Remember These Points

  • if chooses whether code runs.
  • if...else chooses between two paths.
  • if...elif...else chooses among several paths and stops at the first True condition.
  • while repeats while its condition is True.
  • for processes each item in an iterable.
  • range() stops before its ending value.
  • break exits a loop; continue skips to the next iteration.
  • and requires both conditions, or requires at least one, and not reverses a condition.
  • Use Decimal for applications that require precise decimal monetary calculations.
  • Mean = average, median = middle after sorting, mode = most frequent.

Chapter Revision

1. What is the difference between selection and iteration?
2. When would you use if...elif...else instead of several separate if statements?
3. Why must a while loop eventually change its condition?
4. What values are produced by range(2, 10, 2)?
5. What is the difference between break and continue?
6. Why is Decimal useful for financial calculations?
7. What do and, or and not do?
8. What are mean, median and mode?

Practice Programs

  1. Ask the user for a number and print whether it is positive, negative or zero.
  2. Ask for a grade and print A, B, C, D or F using if...elif...else.
  3. Print numbers from 1 to 20 using a for loop and range().
  4. Calculate the sum of all integers from 1 to 100 using a loop and augmented assignment.
  5. Build a sentinel-controlled program that accepts numbers until -1 and then displays their average.
  6. Use break to stop a loop when a target number is found.
  7. Use continue to skip even numbers.
  8. Calculate mean, median and mode for a list using the statistics module.

3.15 Wrap-Up

This chapter builds the core idea of program control flow. You learned how to make decisions with if, if...else and if...elif...else, and how to repeat work with while and for. You also learned how range() controls iteration, how sentinel values can end input-driven loops, and how augmented assignments make updates shorter.

The chapter then introduced Decimal for precise monetary calculations, f-string formatting, break and continue, Boolean operators, and the descriptive statistics measures mean, median and mode. These concepts prepare you for creating functions and working with additional Python Standard Library capabilities in the next chapter.