View as PDF

COMPUTING AND DIGITAL LITERACY

Reading Simple Code

Difficulty level: Easy

Computing and Digital Literacy

This document was made by AI and there may be mistakes. If a question or answer looks wrong, use the Flag a mistake button to let Brett know so he can fix it.

Overview of the concept

This is how you understand a program before you change it, like reading a recipe line by line so you know what each step does before you cook. A programmer who changes code they have not read can break something that was working, just as a cook who skips a step can ruin a dish. Reading code means following what each line does and how the lines fit together, so you know where a change belongs. It is the first skill of programming, and it comes before writing a single line of your own.

Worked examples

Example 1

Read a greeting program

Solution

name = input("Name? ")

print("Hello, " + name)

Plain words: ask for a name, then print Hello plus that name.

Read the first line: input asks a question and stores the answer in name.

Read the second line: print shows Hello, joined to the stored name.

Say the whole program in one sentence: it asks for a name and greets that person.

Example 2

Read a counting loop

Solution

total = 0

for n in [2, 4, 6]:

total = total + n

print(total) -> Output: 12

total starts at 0, then the loop takes each value in [2, 4, 6] in turn.

Each pass adds the value: 0+2=2, 2+4=6, 6+6=12.

After the loop, print shows the final total, 12.

Practice questions

1

Read: x = 3; print(x * 2). What prints?

2

Read name = "Ana"; print(name). What prints?

3

Read: if 5 > 3: print("Yes"). What prints?

4

Read: for i in range(1, 3): print(i). What prints?

5

What is the first step in reading code?

6

What does 'print' do?

7

Read: if 3 > 5: print("Yes") else: print("No"). What prints?

8

Read: s = "hi"; print(s + "!"). What prints?

9

Why read code before changing it?

10

A line says total = total + n. In plain words, what does it do?

ANSWER KEY

1. 6

2. Ana

3. Yes

4. 1, then 2

5. Read it line by line, top to bottom

6. It displays a value on screen

7. No

8. hi!

9. So you understand what it does and do not break working parts

10. It adds n to total and stores the result back in total