CS1010E Chap.4 Manipulating Program State with Statements
Manipulating Program State with Statements
From describing values to describing steps
This chapter of CS1010E moves from the declarative style, where a solution is an expression whose value Python evaluates, to the imperative style, where a solution is a list of instructions that alter variables. At any instant during execution, the values held by the program's variables make up its state.
Each statement is an action that takes the program from one state to another, and the final answer is simply the state left behind when execution ends. The shift matters because the same task, such as summing terms of a series, can be written either way, and the course expects you to choose deliberately between them rather than defaulting to whichever style you met first.
Assignment is the basic state-changing action.
Python first evaluates the expression on the right, then binds the result to the name on the left, and the assignment itself has no value. Because a name can be reassigned many times, the same line can mean something different on each run through it.
Reading imperative code therefore means keeping track of time: which value a variable holds depends on which statements have already executed, and in what order.
Talking to the user and defining behaviour
Two built-in functions connect a program to the outside world.
The input function waits for the user to type something and gives it back as text, so a number must be converted with int or float before arithmetic. The print function writes to standard output; what you see on screen is an effect, not a returned value.
Function definitions written with def are statements too, and a return statement inside them is optional. A function that only prints still hands back a value when called, namely None, so it should be used as a standalone line rather than inside a larger expression.
Three ways to arrange statements
Every imperative program is built from sequence, selection and repetition.
Sequence is the default: statements run one after another. Selection uses if, optional elif branches and an optional else to choose a single block based on boolean conditions, and selections may be placed inside one another.
Repetition uses for when the number of passes is fixed and while when the loop should stop on a condition, such as two successive approximations being close enough or the user entering a sentinel value.
Loops may also be nested, with an inner loop completing all of its passes for every single pass of the outer one.
The skill the course keeps returning to is tracing: writing down the value of each variable as time moves forward, so you can predict output, explain a wrong answer, and choose sensibly between an expression-based and a statement-based solution.
What this chapter covers
- 01
Program state and the imperative style
- 02
Assignment and compound assignment statements
- 03
Reading input with input and writing output with print
- 04
Function definitions, return statements and None
- 05
Selection with if, elif and else, including nesting
- 06
Count-controlled for loops and condition-controlled while loops
- 07
Nested loops and tracing variables through time
- 08
Debugging loops with print statements
Worked example · free
Tracing a for loop that tracks a running record
best = temps[0], count = 0, then for i in range(1, len(temps)) with the body if temps[i] > best: best = temps[i]; count += 1, finally return best, count. Trace the call with temps = (31, 29, 33, 33, 35, 30) and state the returned value. The step weighting shown here is an AskSia study allocation and is not a University marking scheme.band(score) as a flowchart. Each diamond is one condition; a score of 70 fails the first test and passes the second.- 1Record the start state before the loop: best = 31, count = 0, and note that i will take the values 1 to 5.
- 3Run one row per pass, testing temps[i] > best before any update and changing best and count only when the test is True.
- 2Read the result from the state after the final pass and give it in the form the return statement builds.
Key terms
- Program State
- The collection of values stored in a program's variables at one moment during execution. Each executed statement can move it to a new state.
- Assignment Statement
- Evaluates the expression on the right of = and binds the result to the variable on the left. It changes state but does not itself produce a value.
- Statement Block
- One statement or a group of statements indented at the same level, run together as the body of a function, branch or loop.
- Selection Structure
- Chooses which block to run by testing conditions with if, elif and else; only the first block whose condition is True executes.
- Count-Controlled Loop
- Repeats a block a known number of times, most naturally written with for and range.
- Sentinel-Controlled Loop
- Repeats until a particular value or condition signals the end, usually written with while, so the number of passes is not fixed in advance.
- Nested Loop
- A loop placed inside the body of another loop; the inner loop runs all its passes for each single pass of the outer loop.
Manipulating Program State with Statements FAQ
Why does Python give a TypeError when I add a number to what input returned?
Whatever the user types arrives as a string, even if it looks like 12. Adding 3 to the string raises a TypeError, and adding the string '3' joins text to make '123'. Wrap the call as int(input(...)) or float(input(...)) to get 15 instead.
What is the difference between print and return inside a function?
A return statement hands a value back to the caller so it can be stored or used in another expression. Printing only displays text on the screen. If a function prints but never returns, assigning its call to a variable stores None, which then breaks later arithmetic.
When should I use a for loop instead of a while loop?
Choose for when you can say in advance how many passes you need, for example one per element or one per number in a range, because Python moves the loop variable for you. Choose while when the stopping point depends on what happens inside, such as an error shrinking below a tolerance or a sentinel input.
How do I stop a Python program stuck in an infinite loop?
Press Ctrl-C in the terminal or IPython session to interrupt it. Then inspect the while body: the usual cause is that nothing inside it changes the variable the condition depends on, or the update moves away from the stopping value rather than toward it.
How can I see what a nested loop is doing step by step?
Add a print of the loop variables and the accumulator inside the inner body, using end to keep values on one line, and print the running total after each outer pass. Calling input() at the end of the outer body pauses execution until you press Enter.
Exam move
For every loop you meet in lectures and tutorials, draw a state table by hand before running the code, then compare your last row with the real output. Practise reordering three or four assignment statements and predicting the new final state, since update order is where imperative bugs hide.
Working through Manipulating Program State with Statements in CS1010E? Sia is AskSia’s AI Computer Science tutor — ask any CS1010E Manipulating Program State with Statements question and get a clear, step-by-step explanation grounded in how CS1010E is taught and assessed. Read this chapter free, then take your hardest questions to Sia.