Beginner-friendly teaching edition • decisions, loops, ranges, Boolean logic and basic statistics
if, if...else and if...elif...else.while and for.+=.range() to generate sequences of integers.while.and, or and not.break and continue.Decimal when monetary calculations require decimal precision.statistics module.These topics follow the chapter's stated objectives and outline.
range Functionrange: A Deeper LookDecimal for Monetary Amountsbreak and continueand, or, notThe source chapter organizes these topics as sections 3.1 through 3.15.
Control statements control which code runs and how many times it runs. Python mainly gives us two kinds of control:
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.
| Statement | Simple meaning | Typical use |
|---|---|---|
if | Run code when a condition is True. | Check eligibility, score, age, etc. |
if...else | Choose between two paths. | Pass / fail, yes / no. |
if...elif...else | Choose among multiple paths. | Grade A/B/C/D/F. |
while | Repeat while a condition remains True. | Repeat until a target or sentinel is reached. |
for | Repeat 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.
if StatementAn 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')grade >= 60.True.print() executes.Indentation is required. The statements belonging to the if must be indented. Four spaces are the convention used in the chapter.
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= and ==.= means assignment. == asks whether two values are equal.if...else and if...elif...elsegrade = 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.
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.
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.
else part is optional. Use it when you want a default action for all cases that did not match an earlier condition.while StatementA 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.
for StatementA 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 sepprint(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.
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.
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
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.
Augmented assignment is a shorter way to update a variable using its current value.
| Long form | Short form | Meaning |
|---|---|---|
total = total + number | total += number | Add and assign |
x = x - 2 | x -= 2 | Subtract and assign |
x = x * 5 | x *= 5 | Multiply and assign |
x = x ** 3 | x **= 3 | Exponentiate and assign |
x = x / 2 | x /= 2 | Divide and assign |
x = x // 2 | x //= 2 | Floor-divide and assign |
x = x % 9 | x %= 9 | Remainder and assign |
The chapter shows += as a concise replacement for repeating the same variable on both sides of the assignment.
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.
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.
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
-1 is not processed as a grade. It only signals that input is finished. The program also checks for zero entered grades before dividing.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.
range(): A Deeper Lookrange() can take one, two or three arguments.
| Form | Meaning | Example |
|---|---|---|
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.
Decimal for Monetary AmountsNormal 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.
The chapter calculates the amount after each year for a $1000 investment earning 5% annually, using the compound-interest formula:
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.
| Specifier | Meaning |
|---|---|
>2 | Right-align in a field of width 2. |
10.2f | Right-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.
break and continuebreakbreak 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
continuecontinue 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.
and, or and notComparison operators create simple conditions. Boolean operators combine those conditions into more complex decisions.
and — Both Conditions Must Be Truegender = 'Female'
age = 70
if gender == 'Female' and age >= 65:
print('Senior female')and is True only when both sides are True.
| Expression 1 | Expression 2 | 1 and 2 |
|---|---|---|
| False | False | False |
| False | True | False |
| True | False | False |
| True | True | True |
or — At Least One Condition Is Truesemester_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.
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 Falsegrade = 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.
| Higher → Lower | Operators |
|---|---|
| 1 | () |
| 2 | ** |
| 3 | * / // % |
| 4 | + - |
| 5 | < <= > >= == != |
| 6 | not |
| 7 | and |
| 8 | or |
This ordering is the chapter's precedence table for the operators introduced so far.
Descriptive statistics help us summarize a collection of data. This section introduces three measures of central tendency: mean, median and mode.
| Measure | Easy meaning | Example idea |
|---|---|---|
| Mean | Average value. | Total ÷ number of values. |
| Median | Middle value after sorting. | For 5 values, the 3rd sorted value. |
| Mode | Most frequently occurring value. | The value appearing most often. |
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.
statistics Moduleimport 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.
if, elif, else, while or for.= when you mean ==.range(stop) includes stop.while loop whose condition never becomes False.else at the wrong indentation level.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.Decimal for applications that require precise decimal monetary calculations.if...elif...else instead of several separate if statements?while loop eventually change its condition?range(2, 10, 2)?break and continue?Decimal useful for financial calculations?and, or and not do?if...elif...else.for loop and range().-1 and then displays their average.break to stop a loop when a target number is found.continue to skip even numbers.statistics module.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.