Python Basics, Branching, and Iteration
Algorithms, Programming, and Data Representation · Module 92313 · Chapter 6
This chapter builds the first working Python: values and their types, operators, names bound to values, strings, printing and reading input, and the two control-flow tools every program needs, choosing a branch and repeating a block.
Start from memory
Try each question first. Mark it sure, unsure, or guessed.
- What is the type of the value of
7 / 7in Python? - What does
"abc"[-1]evaluate to? - What is the difference between
=and==? - Which numbers does
range(5)produce? - What does
breakdo inside two nested loops?
Check the short answers
float:/always gives a float, here1.0. §6.2"c", the last character. §6.4=binds a name to a value;==tests two values for equality and gives a Boolean. §6.3, §6.6- 0, 1, 2, 3, 4: it starts at 0 and stops before 5. §6.8
- It leaves only the innermost loop; the outer loop carries on. §6.9
How to use this guide
Read a section, close it, and type its examples into a Python shell from memory before you check them. The lecture’s own advice applies to every line here: if you are unsure what a command does, try it in the console.
- Day 0: Try the cold start, then study §6.1–6.4; solve practice 1, 2, 3, 5, 12.
- Day 1: Rebuild §6.1–6.4 from memory, then study §6.5–6.7; solve practice 6, 8, 9, 15, 18, 19.
- Day 3: Rebuild §6.5–6.7 from memory, then study §6.8–6.10 and trace every loop on paper; solve practice 4, 7, 11, 13, 14, 17.
- About day 7: Do the derivation list cold, then practice 10, 16, 20–24 without notes.
- About day 14: Work both exam problems in 20 minutes each; answer the “Explain it” questions aloud.
- Before the exam: Tick only the self-check skills you can show cold; revisit the sections named in the answers you missed.
When stuck: make a trace table. Write one column per variable and one row per line executed, and fill it in line by line. Most loop and branch questions are answered by the last row.
How the chapter fits together
Values with types come first, because operators and comparisons depend on the type. Names hold values, strings are a sequence type, and input and output connect a program to its user. Branching and loops then decide which lines run and how often.
Measure · values and types
-
Objects and types §6.1
int · float · bool · NoneTypeRests on: nothing earlier; every value in a program has a type that fixes what you can do with it.
-
Expressions and operators §6.2
i // j · i % j · i ** jRests on: types, because the operand types decide the result type.
Define · names, text and comparison
-
Assignment §6.3
name = expressionRests on: expressions, because the right side is evaluated to a value before the name is bound.
-
Strings §6.4
s[start:stop:step]Rests on: types and names; a string is an immutable sequence you reach through a name.
-
Output and input §6.5
int(input(…))Rests on: strings and casting, because
inputalways returns a string. -
Comparison and logic §6.6
== != < > and or notRests on: expressions; comparisons are expressions whose value is a Boolean.
Derive · control flow
-
Branching §6.7
if · elif · elseRests on: comparisons, because each condition is a Boolean expression.
-
while and for §6.8
range(start, stop, step)Rests on: conditions and rebinding; a loop repeats while a condition holds or once per value.
-
break and continue §6.9
break · continueRests on: loops and branches; a jump is almost always inside an
ifinside a loop. -
Choosing a loop §6.10
for char in sRests on: both loop kinds and on strings as sequences.
| Question | Tool |
|---|---|
| What value and type does this expression have? | Operand types and precedence (§6.1–6.2) |
| What does this name hold after these lines? | A trace table of assignments (§6.3) |
| Which characters does this index or slice give? | Write the indices under the string (§6.4) |
| Which lines run? | Evaluate each condition in order (§6.6–6.7) |
| How often does the body run, and what is left? | Trace the loop variable row by row (§6.8–6.9) |
| Which loop should I write? | Known count → for; stop on a condition → while (§6.10) |
6.1 Programs, Python, objects and types
Before any branching or looping, you need to know what a program is made of and what kinds of values it handles.
In plain words: a program is a list of definitions and commands written as text, the source code. The processor cannot read that text; it only runs its own machine instructions. A compiler translates the whole text into machine code first, while an interpreter, like Python’s, reads and runs it line by line. Every value the program touches is an object with a type, and the type decides what you may do with it, just as a car can drive but cannot swim.
int · float · bool · NoneType
type(5) → int
type(3.0) → float
Read it as: “the type of 5 is int, the type of 3.0 is float”. int holds whole numbers, float real numbers, bool the two values True and False, and NoneType the single value None.
float(3) → 3.0
int(3.9) → 3
Read it as: “float of 3 is 3.0; int of 3.9 is 3”. Converting a value to another type is called casting. int of a float cuts off the fractional part; it does not round.
Python is an interpreted language: you can type commands into a shell one at a time, store them in a file that the interpreter reads, or run them in a notebook. The lecture uses Python as one example of an imperative language; the ideas in this chapter carry over to the others. Functional languages such as Haskell work differently and are not part of the course.
The lecture separates two kinds of line. A definition is evaluated: Python works out what it means. A command (or statement) is executed: it tells the interpreter to do something.
Objects are either scalar, meaning they cannot be split into parts (a number, a Boolean), or non-scalar, meaning they have an internal structure you can reach into. A string, met in §6.4, is the first non-scalar type.
Worked example · types and casts
type(True)isbool:Trueis a Boolean value, not a string.float(7)is7.0: same number, now a float.int(-3.9)is-3: the fractional part is cut off towards zero, so a negative number moves up, not down.- Check: each result has the type named by the cast, and no value changed by more than its fractional part.
Trap: int(3.9) is 3, not 4. Casting truncates; use round when you mean rounding.
Near miss: "5" looks like the number 5, but the quotes make it a string; type("5") is str. Cast it with int("5") before doing arithmetic.
Recall check · answer without looking
- Why does a computer need a compiler or an interpreter to run Python source code?
- Name the four scalar types and one value of each.
- What is
int(-2.5)?
Check these answers
- The processor runs only its native machine instructions. Source code is human-readable text, so it must be translated (compiler) or read and run step by step (interpreter).
int: 5;float: 3.27;bool:True;NoneType:None.-2: the fractional part is cut off.
6.2 Expressions and operators
Objects become useful when operators combine them into expressions; the operand types decide the type of the answer.
In plain words: an expression joins objects with operators, like 3 + 2, and Python works it out to a single value. That value has a type too. When several operators meet, precedence says which goes first, the way multiplication beats addition in arithmetic, and brackets override it.
i + j · i - j · i * j: int if both are int, else float
i / j: always a float
i ** j = ij
Read it as: “sum, difference and product are int only when both operands are int; division always gives a float; i to the power j”. 6 / 3 is 2.0, not 2.
i // j = ⌊ij⌋
i % j = i − j · (i // j)
Read it as: “i floor-divided by j is i over j rounded down; i mod j is what is left after taking j that many times”. For two ints, 7 // 2 is 3 and 7 % 2 is 1. With a float operand the quotient is a float: 7.0 // 2 is 3.0.
**.The interactive shell shows the value of a bare expression: typing 3+2 prints Out[11]: 5 in the lecture’s IPython console. A program that should show something to a user calls print instead (§6.5).
The general shape is <object> <operator> <object>. Without brackets Python applies ** first, then the multiplicative operators, then + and -. The lecture lists * and / on separate rows; in Python they share one row with // and % and are evaluated left to right, so 8 / 2 * 4 is 16.0 (see the slips list). + and - also go left to right: 10 - 4 - 3 is 3.
Worked example · evaluate 2 + 3 * 4 ** 2 // 5
- Power first:
4 ** 2is 16, giving2 + 3 * 16 // 5. *and//share a row, so left to right:3 * 16is 48, then48 // 5is 9 (48 ÷ 5 = 9.6, rounded down).- Last the addition:
2 + 9is 11, anintbecause every operand was an int. - Check: no
/appeared, so no float can appear; 11 is an int.
Trap: // rounds down, not towards zero. -7 // 2 is -4, and then -7 % 2 is 1 so that the identity above still holds.
Near miss: 6 / 3 divides evenly, so it is tempting to expect the int 2, but / always returns a float: the value is 2.0. Write 6 // 3 for the int.
Watch expressions reduce step by step in the lab
Recall check · answer without looking
- What are the value and type of
7 // 2and of7 / 2? - Evaluate
2 ** 3 ** 2and say why. - What is
17 % 5?
Check these answers
3(int) and3.5(float).- 512:
**groups from the right, so it is 29, not 82 = 64. - 2, because 17 = 5 · 3 + 2.
6.3 Variables and assignment
Naming a value lets you reuse it and change the program in one place; the equals sign does this, but it does not mean what it means in maths.
In plain words: an assignment sticks a name label on a value stored in memory, the way a variable name points at a number. Python first works out the expression on the right, then binds the name on the left to the result. You can move the label to a new value later (rebinding); anything worked out earlier from the old value stays as it was.
name = expression
radius += 1 means radius = radius + 1
Read it as: “evaluate the expression, then bind the name to that value”. The name is on the left, the expression on the right. radius = radius + 1 is not an equation to solve: it reads the old value, adds 1, and rebinds.
radius now holds 3.2, but area still holds the value worked out from 2.2: nothing recalculates it.Retrieve a value by typing its name: after pi = 3.14159, the name pi evaluates to 3.14159. Names make code easier to read and to change: area = pi*(radius**2) says what it computes, and changing radius in one place changes every line that uses it when that line next runs.
A name may contain letters, digits and underscores but may not start with a digit, may not contain a dot, and may not be a keyword such as if or for; the slide’s pi_approx. = 22/7 is a syntax error for that reason (see the slips list). After a rebinding the old value may still sit in memory, but the program has lost its handle on it.
Worked example · trace the lecture’s lines
pi = 3.14bindspito 3.14;radius = 2.2bindsradiusto 2.2.area = pi*(radius**2)evaluates 3.14 · 4.84 = 15.1976 and bindsareato it.radius = radius+1reads 2.2, adds 1 and rebindsradiusto 3.2.- Check:
areais still 15.1976. To update it you must run the area line again. (Python prints 15.197600000000003; the tail is float rounding, Chapter 4.)
Trap: a variable is not a formula. Changing radius does not change area; only re-running the assignment does.
Near miss: x + 1 = 5 reads like an equation with the answer x = 4, but it is a syntax error: the left side of = must be a name, not an expression. Python never solves for x.
Recall check · answer without looking
- In
count = count + 1, which side is evaluated first, and what happens next? - Give two reasons to name values instead of writing the numbers each time.
Check these answers
- The right side is evaluated using the current value of
count; thencountis rebound to the result. - The name can be reused instead of repeating the value, and the code is easier to change later, because the value is set in one place.
6.4 Strings
Text is the first non-scalar type: a string has parts you can index and slice, which loops in §6.10 will walk through.
In plain words: a string is a row of characters (letters, digits, spaces, symbols) written in single or double quotes. Each character has a position number, its index, starting at 0 from the left and at −1 from the right. A slice cuts out a piece by giving where to start, where to stop and how big a step to take. Strings are immutable: you cannot change a character in place, only build a new string.
"ab" + "cd" → "abcd"
"ab" * 3 → "ababab"
len("abc") → 3
Read it as: “plus joins strings, times repeats a string, len counts its characters”. Joining is called concatenation. + does not insert a space: "hello there" + "Joe" is "hello thereJoe". * binds before + here too: with name = "Joe", "hi " + name * 3 is "hi JoeJoeJoe".
s[i]: the character at index i, with 0 ≤ i ≤ len(s) − 1 or −len(s) ≤ i ≤ −1
s[start:stop:step]: from start, in steps of step, stopping before stop
Read it as: “s at i is one character; s from start to stop by step is the piece that begins at start and ends just before stop”. step defaults to 1; leaving out start or stop means “from the beginning” or “to the end” (from the end backwards when step is negative).
s = "abcdefgh". Index from the left below each box, from the right above it. s[3] and s[-5] name the same character.Strings compare with ==, <, > like numbers (§6.6), and they are case sensitive: "abc" == "ABC" is False. Indexing past the end, as in "abc"[3], raises an error.
Slicing in practice
With s = "abcdefgh": s[3:6] is "def" (indices 3, 4, 5); s[3:6:2] is "df"; s[::] is the whole string; s[::-1] is "hgfedcba", the string reversed; and s[4:1:-2] is "ec". The lecture prints the reversed string as “hgfedbca”, which is a typo (see the slips list).
Immutability
s[0] = 'y' fails with an error, because a string object cannot be modified. To get "yello" from "hello", build a new string and rebind the name: s = 'y' + s[1:len(s)].
Worked example · s[4:1:-2] with s = "abcdefgh"
- Start at index 4:
"e". - Step −2 to index 2:
"c". - The next index would be 0, which is not before
stop= 1 in the backwards direction, so the slice ends. - Result
"ec". Check: a negative step walks right to left, so the result must read backwards through the string.
Trap: the stop index is never included. s[3:6] has three characters, 6 − 3, not four.
Near miss: s[len(s)] looks like “the last character”, but indices end at len(s) - 1, so it is out of bounds and raises an error. Use s[-1].
Slice strings and watch the indices in the lab
Recall check · answer without looking
- With
s = "python", gives[0],s[-1]ands[1:4]. - Why does
s[0] = "P"fail, and what do you write instead?
Check these answers
"p","n","yth".- Strings are immutable. Build a new string and rebind:
s = "P" + s[1:].
6.5 Output and input
A program talks to its user through print and listens through input; the type that input returns is the usual source of errors.
In plain words: print writes values to the console. Give it several values separated by commas and it puts a space between them. input shows a prompt, waits for the user to type something and press Enter, and hands back what was typed, always as a string, even if the user typed digits.
print(a, b, c): the values with one space between each
text = input("prompt"): text is a str
num = int(input("prompt")): cast to use it as a number
Read it as: “print shows the values separated by spaces; input returns a string, so cast it before arithmetic”. Joining with + needs every part to be a string already: cast numbers with str.
The lecture prints the same sentence two ways. print("my fav num is", x, ".", "x =", x) passes five values and prints my fav num is 1 . x = 1, with a space before the full stop. print("my fav num is " + x_str + ". " + "x = " + x_str) builds one string from strings and prints my fav num is 1. x = 1, with exactly the spaces you typed.
Worked example · the user types 4
text = input("Type anything... ")bindstextto the string"4".print(5*text)repeats the string: it prints44444.num = int(input("Type a number... "))with input 4 bindsnumto the int 4;print(5*num)prints20.- Check: the same keystrokes give a string unless you cast, and
*on a string repeats it.
Trap: print("total: " + 3) raises a TypeError, because + cannot join a string and an int. Write print("total:", 3) or "total: " + str(3).
Near miss: in the shell, typing 3+2 shows 5, so it looks as if the expression printed itself; in a script file that line shows nothing. Only print writes to the console from a program.
Recall check · answer without looking
- What type does
inputreturn, and what must you do before using the answer in arithmetic? - What does
print("a", 1, "b")show?
Check these answers
- Always a string; cast it, for example with
int(…)orfloat(…). a 1 b: the values separated by single spaces.
6.6 Comparison and logic
Branches and loops are steered by conditions; a condition is an expression whose value is True or False.
In plain words: a comparison asks a yes-or-no question about two values, such as “is i larger than j?”, and its answer is a Boolean. The logic operators not, and and or combine Booleans into bigger questions, exactly like NOT, AND and OR in Boolean algebra.
i > j · i >= j · i < j · i <= j
i == j: equal · i != j: not equal
Read it as: “greater, greater or equal, less, less or equal, equal, not equal”. They work on ints, floats and strings, and each gives a bool.
not a: True exactly when a is False
a and b: True only when both are True
a or b: True when at least one is True
Read it as: “not a flips a; a and b needs both; a or b needs one or both”. Python applies not first, then and, then or, all after the comparisons.
The lecture’s example: with set_time = 15 and sleep_time = 8, print(sleep_time > set_time) prints False. In the second example derive is True and drink is False, so both = drink and derive gives False: one operand is False.
Strings compare character by character, using the character codes from Chapter 3. (This follows from the codes; the slides only say strings can be compared.) Every capital letter has a smaller code than every small letter, so "Zebra" < "apple" is True, and the digit strings "10" < "9" is True because "1" comes before "9".
Worked example · not 3 > 2 or 4 < 1
- Comparisons first:
3 > 2isTrue,4 < 1isFalse. notbeforeor:not TrueisFalse.False or FalseisFalse.- Check: the only way to get
Truefromoris aTrueoperand, and none is left.
Trap: comparing a number with a string of digits does not convert either side. 5 == "5" is False; cast first.
Near miss: "10" < "9" looks false, since 10 is bigger than 9, but these are strings: they compare character by character, and "1" is before "9", so it is True. Compare int("10") < int("9") for the numbers.
Recall check · answer without looking
- What is the type of the value of
3 < 4? - For which values of
aandbisa or bFalse?
Check these answers
bool; the value isTrue.- Only when both are
False.
6.7 Branching and indentation
With conditions in hand, a program can choose which block of lines to run.
In plain words: an if statement is a fork in the road: if the condition is true, take this path; otherwise skip it. elif adds more forks, tried in order, and else catches everything left over. Python knows which lines belong to which path by their indentation: the lines of one block are pushed in by the same amount.
if c: block
if c: block else: block
if c1: block elif c2: block else: block
Read it as: “if c holds, run the block; with elif, try each condition in order; else runs when none held”. At most one block of an if/elif/else chain runs: the first whose condition is True.
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")
This is the lecture’s program. The two lines under if x == y: form one block; the inner if has its own, deeper block. The last line is not indented, so it runs whichever branch was taken. The condition uses ==: writing if x = y: is a syntax error, because = is assignment, not comparison.
Worked example · run the program with x = 0 and y = 0
x == yisTrue, so the first block runs and printsx and y are equal.- Inside it,
y != 0isFalse, so the division line is skipped: no division by zero happens. - The
elifandelseblocks are skipped because a branch was already taken. - The unindented
print("thanks!")runs. Output: two lines. Check: the innerifguards the division exactly in the case where it would fail.
Trap: moving print("thanks!") four spaces to the right puts it inside the else block, so it would print only when y is smaller. In Python, indentation changes meaning.
Near miss: with x = 7, the chain if x > 5: … elif x > 3: … has two true conditions, so it seems both blocks should run, but only the first true one does. Separate if statements would run both.
Trace which lines run in the lab
Recall check · answer without looking
- How does Python know where an
ifblock ends? - In an
if/elif/elsechain, how many blocks can run?
Check these answers
- By indentation: the block ends at the first following line that is indented less.
- Exactly one if there is an
else; at most one without it.
6.8 while and for loops
Branching runs a block once or not at all; a loop runs it again and again.
In plain words: a while loop keeps repeating its block as long as its condition stays true, checking before every round. A for loop runs its block once for every value in a sequence, putting each value in turn into the loop variable. range makes a sequence of whole numbers to count with.
while c: block
Read it as: “while c is true, run the block, then check c again”. If c is False at the first check, the block never runs. Something in the block must eventually make c false, or the loop never ends.
range(stop): 0, 1, …, stop − 1
range(start, stop, step): start, start + step, … while still before stop
Read it as: “from start, counting up by step, stopping before stop”. start defaults to 0 and step to 1. stop itself is never produced: range(5, 11, 2) gives 5, 7, 9. With a negative step it counts down and stops before reaching stop from above: range(10, 0, -3) gives 10, 7, 4, 1.
# with while: set up, test and update the counter yourself
n = 0
while n < 5:
print(n)
n = n+1
# with for: range does the counting
for n in range(5):
print(n)
Both loops print 0 to 4. The for version is shorter because range sets the start, the step and the end. A for loop is not limited to numbers: it can walk through any sequence, such as the characters of a string (§6.10).
Worked example · the lecture’s two sums
for i in range(7, 10): mysum += iwithmysum = 0: i takes 7, 8, 9, somysumis 24.for i in range(5, 11, 2): mysum += i: i takes 5, 7, 9 (11 is not produced, and neither is 10), somysumis 21.- Check by count:
range(7, 10)has 10 − 7 = 3 values;range(5, 11, 2)has 3 values because the next value would be 11, which is not beforestop.
Trap: a while loop whose body never changes the condition runs forever. Before you run one, name the line that moves it towards stopping.
Near miss: range(1, 5) looks as if it counts 1 to 5, but it stops before 5: 1, 2, 3, 4. To include 5 write range(1, 6).
Recall check · answer without looking
- List the values of
range(4, 6)and ofrange(10, 0, -3). - When does the body of a
whileloop run zero times?
Check these answers
- 4, 5; and 10, 7, 4, 1.
- When the condition is already
Falseat the first check.
6.9 break and continue
Sometimes a loop should stop early or skip the rest of one round; two keywords do this.
In plain words: break is an emergency exit: it leaves the loop at once and carries on after it. continue skips the rest of this round only and jumps back to the top of the loop for the next round. Both affect only the innermost loop they sit in.
break: leave the innermost loop now
continue: skip the rest of this round, start the next
Read it as: “break exits the loop; continue skips to the next round”. The lines after either keyword in the same block do not run in that round. A break in an inner loop leaves the outer loop running.
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break # or: continue
mysum += 1
print(mysum)
Worked example · the lecture’s break and continue programs
- With
break: i = 5 makesmysum5, the test is true, and the loop ends. It prints5. - With
continue, round i = 5:mysumbecomes 5, the test is true, andmysum += 1is skipped. - Round i = 7:
mysumis 12, the test is false, then 13. Round i = 9: 22, then 23. - It prints
23. Check:continueskipped exactly one+= 1, and 5 + 7 + 9 + 2 = 23.
Trap: break in a nested loop exits only the inner one. With for i in range(3): around for j in range(4): and if j == 2: break as the first line of the inner body, the rest of that body runs twice per outer round: 6 times in total.
Near miss: continue sounds like “keep going with the next line”, but it does the opposite: it skips the remaining lines of this round and starts the next round.
Compare break and continue in the lab
Recall check · answer without looking
- What is the difference between
breakandcontinue? - After
for i in range(10):withif i * i > 20: breakinside, what is i?
Check these answers
breakleaves the loop entirely;continueends only the current round and goes on with the next.- 5, the first value with 5 · 5 = 25 > 20.
6.10 Choosing a loop and iterating over strings
Both loops can repeat a block; choosing the right one, and letting for walk a string directly, makes the code shorter and safer.
In plain words: use for when you know in advance how many rounds you need, or you want one round per item; use while when you stop on a condition and cannot say beforehand how many rounds it will take. Any for loop can be rewritten as a while loop, but not always the other way round. Walking straight through the characters with for char in s is called the pythonic way.
for index in range(len(s)): use s[index]
for char in s: use char
Read it as: “loop over the positions and look each one up, or loop over the characters themselves”. Both visit every character once, in order. The second has no index to get wrong.
for loop | while loop | |
|---|---|---|
| Number of rounds | Known in advance | Unbounded: until the condition fails |
| End early | break / continue | break / continue |
| Counter | Provided by the loop | Initialise before, update inside |
| Rewrite as the other | Always possible | Not always possible |
The lecture’s cheering program first walks the word with an index (i = 0, while i < len(word):, char = word[i], …, i += 1) and then replaces those three lines with for char in word:. Inside, char in an_letters tests whether a one-character string occurs in the string of letters that take “an”.
Worked example · rewrite a for loop as a while loop
- Start:
for n in range(3, 8): print(n)prints 3 to 7. - Initialise the counter before the loop:
n = 3. - Test it in the condition:
while n < 8:, becauserangestops before 8. - Update it at the end of the body:
print(n)thenn += 1. Check: the last value printed is 7, and the loop stops when n reaches 8.
Trap: forgetting the update line (i += 1) in a while version of a counting loop gives an endless loop; the lecture crosses out exactly these lines when it switches to for.
Near miss: “read numbers until the user types 0” has a clear end, so it seems a for loop could do it, but nobody knows the count in advance: that is a while loop.
Recall check · answer without looking
- Give one task that needs a
whileloop and one that suits aforloop. - What three pieces must you add when you turn a
for … in range(…)loop into awhileloop?
Check these answers
while: keep asking for a password until it is correct.for: print each character of a word, or sum the numbers 1 to 100.- Initialise the counter before the loop, test it in the condition, and update it inside the body.
Formula map and units
| Rule | Result type or meaning |
|---|---|
int op int for + - * // % ** | int (a negative power gives a float) |
any float operand | float |
i / j | always float |
i == j * (i // j) + i % j | always True for ints with j ≠ 0 |
int(x), float(x), str(x) | casts; int of a float truncates towards zero |
comparisons, not, and, or | bool |
input(…) | always str |
len(s[a:b]) for 0 ≤ a ≤ b ≤ len(s) | b − a characters |
range(a, b) | b − a values, from a to b − 1 |
| precedence | ( ), then **, then * / // %, then + -, then comparisons, not, and, or |
Check every answer: state the type as well as the value (2 or 2.0? 5 or "5"?); check that a slice or range has the number of elements the stop rule predicts; and for a loop, check the first round, the last round and the value left in the loop variable afterwards.
Derive it cold
- Show that
i == j * (i // j) + i % jfor 7 and 2, and for −7 and 2. §6.2 - Evaluate
2 + 3 * 4 ** 2 // 5step by step, naming the precedence rule at each step. §6.2 - Trace the four lines
pi,radius,area,radius = radius+1and explain whyareadoes not change. §6.3 - Work out
s[4:1:-2]ands[::-1]fors = "abcdefgh"index by index. §6.4 - Trace the lecture’s
breakandcontinueprograms to 5 and 23. §6.9 - Rewrite
for n in range(3, 8)as awhileloop and name the three pieces you added. §6.10
Explain it
- Why does Python need an interpreter at all, when the processor already runs programs?
- Why is
radius = radius + 1not a contradiction? - Why does
inputreturn a string even when the user types digits? - Why can an
if/elifchain behave differently from the same conditions written as separateifstatements? - When must you use a
whileloop instead of aforloop? - Why is
for char in ssafer than looping overrange(len(s))?
Show model answers
- The processor runs only its own machine instructions. Python source code is text, so something has to read it and carry out each line; that is the interpreter. §6.1
=is assignment, not equality. The right side is evaluated with the old value, and then the name is rebound to the new one. §6.3- The keyboard delivers characters, and Python cannot know whether you mean the text “42” or the number 42. It hands you the text and leaves the cast to you. §6.5
- A chain runs only the first block whose condition is true and skips the rest. Separate
ifstatements test every condition, so several blocks can run. §6.7 - When the number of rounds is not known in advance, for example when you repeat until a user enters a valid value. A
forloop needs its sequence up front. §6.10 - It hands you each character directly, so there is no index to start, update or push past the end. Fewer lines means fewer places for an off-by-one error. §6.10
Mixed practice
Try all 24 problems before opening the answers. The order mixes every section on purpose, so you have to choose the method yourself. Predict each output on paper, then check it in a Python shell.
- Give the value and type of
9 / 3. - With
s = "python", evaluates[1],s[-2]ands[1:4]. - What does this print?
x = 5, thenx = x * 2 + 1, thenprint(x). - List the values of
range(2, 11, 3). - Give the value and type of
int(-2.7). - Evaluate
not 1 >= 2 and 5 != 5. - Starting from
n = 10, the loopwhile n > 1: n = n // 2runs. How many rounds does it make, and what is n at the end? - A chain prints
"pos"underif x > 0,"zero"underelif x == 0and"neg"underelse. What does it print for x = 0? - The user types 4 at
num = input("n: "). What doesprint(num * 3)show? - Evaluate
3 + 2 ** 3 * 4 // 6, then(3 + 2) ** 3 * 4 // 6. What changes? - After
for i in range(10):with the bodyif i * i * i > 50: break, what is the value of i? - Why does
s[0] = "J"fail fors = "hello", and how do you make"Jello"? - What is
totalaftertotal = 0andfor k in range(1, 6): total += k? - A program should read numbers until the user types 0. Which loop do you use, and why?
- What do
print("total:", 3, "items")andprint("total:" + 3)do? - Evaluate
7 % 3,-7 % 3and7 // 2.0. - What is
countaftercount = 0andfor ch in "a-b-c":with the bodyif ch == "-": continuethencount += 1? - In the lecture’s
x/yprogram (§6.7), the user enters 3 and 3. List every line that is printed. - Is
"apple" < "Apple"true or false? Explain. - Rewrite
for n in range(2, 12, 3): print(n)as awhileloop. - After
radius = 2,area = 3 * radius ** 2,radius = 5, what isarea? - With
s = "abcdefgh", evaluates[::-1]ands[6:2:-2]. - You save three lines of Python in a file and run it. Is it compiled to machine code first, as a C program would be? What happens instead?
- Rewrite
i = 0/while i < len(word):/char = word[i]/ … /i += 1in the pythonic form, and say how many times the body runs forword = "loop".
Show worked answers
3.0, afloat:/always returns a float, even for an exact division. §6.2"y","o","yth"(indices 1, 2, 3; index 4 is excluded). §6.411: the right side uses the old value 5, so 5 · 2 + 1 = 11, then x is rebound. §6.3- 2, 5, 8; the next value, 11, is not before
stop= 11. §6.8 -2, anint: casting cuts the fractional part off towards zero; it does not round down to −3. §6.1False:1 >= 2isFalse,not FalseisTrue,5 != 5isFalse, andTrue and FalseisFalse. §6.6- Three rounds: 10 → 5 → 2 → 1. Then
1 > 1isFalseand the loop ends with n = 1. §6.8 zero: the first condition is false, theelifcondition is true, and theelseblock is skipped. §6.7444:numis the string"4", and*repeats a string. §6.5- 8 for the first: 23 = 8, then 8 · 4 = 32, then 32 // 6 = 5, then 3 + 5 = 8. With brackets the addition goes first: 53 = 125, 125 · 4 = 500, 500 // 6 = 83. §6.2
- 4: for i = 0 to 3 the cube is at most 27; at i = 4, 64 > 50 and
breakleaves the loop with i still 4. §6.9 - Strings are immutable, so a character cannot be assigned. Build a new string:
s = "J" + s[1:]. §6.4 - 15: k takes 1, 2, 3, 4, 5, and 1 + 2 + 3 + 4 + 5 = 15. §6.8
- A
whileloop: the number of rounds is not known in advance; the loop stops on a condition (the value read is 0). §6.10 - The first prints
total: 3 items, with spaces between the values. The second raises aTypeError:+cannot join a string and an int. §6.5 - 1, 2 and 3.0. For −7: −7 // 3 is −3 (rounded down), and −7 − 3 · (−3) = 2. The float operand makes the last result a float. §6.2
- 3: the two
"-"characters hitcontinue, which skipscount += 1; the three letters are counted. §6.9 x and y are equal, thentherefore, x / y is 1.0, thenthanks!. §6.7- False. Strings compare by character codes, and every capital letter comes before every small letter, so
"Apple" < "apple"is the true one. §6.6 n = 2, thenwhile n < 12:with the bodyprint(n)andn += 3; it prints 2, 5, 8, 11. Initialise, test, update by the step. §6.10- 12:
areawas computed withradius= 2, and rebindingradiuslater does not recompute it. §6.3 "hgfedcba"and"ge"(indices 6 and 4; index 2 is the stop and is excluded). §6.4- No. Python is an interpreted language: the interpreter reads the file and carries out its commands, without producing a separate machine-code program you run afterwards. §6.1
for char in word:followed by the same body, without the index lines. The body runs 4 times, once per character of"loop". §6.10
Exam-style problems
1 · A score averager · 20 minutes
total = 0
count = 0
while True:
entry = input("score (q to stop): ")
if entry == "q":
break
score = int(entry)
if score < 0 or score > 100:
continue
total += score
count += 1
print(count, total / count)
- Why does the program need
int(entry), and why must the test for"q"come before it? - The user enters 80, 105, 70 and then q. Trace
totalandcountand give the printed line. - What happens if the user types q at the first prompt? Change the last line to avoid it.
- Why is this a
whileloop and not aforloop, and how does it ever end?
Show the worked answer
inputreturns a string, so the score must be cast before it is compared with numbers or added.int("q")would raise an error, so the stop test has to run on the raw string first. §6.5- 80: total 80, count 1. 105: the range test is true,
continueskips the update. 70: total 150, count 2. q:break. The program prints2 75.0(a float, because of/). §6.9, §6.2 countis 0, sototal / countdivides by zero and the program stops with an error. Guard it:if count > 0: print(count, total / count)andelse: print("no scores"). §6.7- Nobody knows in advance how many scores will be entered; the loop stops on a condition, the input q.
while Truenever fails its test, so the only way out is thebreak. §6.10, §6.8
2 · A palindrome check · 20 minutes
word = "racecar"
i = 0
same = True
while i < len(word) // 2:
if word[i] != word[-1 - i]:
same = False
break
i += 1
print(same)
- How many rounds can the loop make for
"racecar", and which pairs of characters does it compare? - Trace the program for
word = "rocket": what are i andsameat the end? - Give a one-line expression with a slice that has the same value as
same. - Rewrite the loop as a
forloop overrange.
Show the worked answer
len("racecar") // 2is 7 // 2 = 3, so at most three rounds:word[0]withword[-1](r, r),word[1]withword[-2](a, a),word[2]withword[-3](c, c). The middle e needs no partner. All match, so it printsTrue. §6.4, §6.8- 6 // 2 = 3 possible rounds. At i = 0, r and t differ:
samebecomesFalseandbreakleaves the loop beforei += 1, so i = 0 andsame=False. §6.9 word == word[::-1]: the word equals its reverse. §6.4same = True, thenfor i in range(len(word) // 2):with the sameifandbreak, and noi = 0ori += 1, becauserangedoes the counting. §6.10
Slips in the notes
Each item was checked against the rendered slides and against Python 3. Slide numbers refer to “06_branching_and_iterations.pdf”.
- Slide 9, floor division.
i//jis described as returning the quotient as an integer. That holds only for two int operands; with a float operand the floor is a float, so7.0 // 2is3.0(§6.2). - Slide 10, precedence. The list shows
**, then*, then/on separate rows, which reads as if*ranks above/. In Python,*,/,//and%share one level and are evaluated left to right, so8 / 2 * 4is16.0. This guide follows Python (§6.2). - Slide 11, variable name.
pi_approx. = 22/7is a syntax error: a name cannot contain a dot. It probably meanspi_approx = 22/7(§6.3). - Slide 16, quotation marks. The string examples are typeset with curly quotes (“Joe”). Typed into Python, curly quotes are a syntax error; use straight quotes,
"Joe"or'Joe', as this guide does (§6.4). - Slide 28, range. “Loop until value is stop − 1” is true only for step 1. With
range(5, 11, 2)on the same slide, the last value is 9, not 10; the rule is “stop before reachingstop” (§6.8). - Slide 36, reversed string. The reversed string
s[::-1]is printed as “hgfedbca”; for"abcdefgh"Python gives"hgfedcba". The slide’s equivalent slices[-1:-(len(s)+1):-1]is correct (§6.4).
Self-check
These are the chapter’s learning goals. Tick a skill only in a later session, at least one day after studying, when you can show it without notes.
Personal study guide based on the supplied “06_branching_and_iterations.pdf” (40 slides, lecture dated 29 April 2024; the slides credit MIT OpenCourseWare 6.0001), written in my own words; no lecture pages or figures are reproduced. Not an official FAU publication; check course details against the current notes. Made by Thanate Amornjiraporn (Focus).