Week 02 · Phase 1 · Thinking in steps

Your First Python: Values, Names, and Output

print, variables, numbers, text — the four things you need before anything else.

Big question: How do I give the computer one instruction at a time?first code≈2 hours
By the end of this week you can
  • run Python code in Colab cells and read what comes out;
  • store values in variables and reuse them;
  • tell numbers and text apart, and know why Python cares;
  • do arithmetic and build readable output with f-strings;
  • use a few everyday string moves — length, joining, upper and lower case;
  • read the three error messages beginners hit most often.
Where this fits

This week has almost no algorithm analysis in it. It is the vocabulary week: you cannot count the steps of a program before you can read one. Everything here is the smallest possible slice of Python that gets us to real measurement by week 5.

2.1Python does exactly one line at a time

A Python program is a list of instructions, executed top to bottom, one at a time, with no imagination whatsoever. This is the mental model to hold for the rest of the course — and it is also why counting steps is possible at all.

three steps, in order
print("first")
print("second")
print("third")
first second third

print(...) means "show this on the screen". The round brackets hold what to show. The quotes mark where the text starts and stops.

"One line at a time" is not a slogan — it is a promise you can lean on. When a program misbehaves, you can read it the way Python does: put your finger on line 1, work out what it leaves behind, move to line 2, and so on. Nine bugs in ten give themselves up to that slow finger. We will lean on the same habit in week 3 to count how many times a line runs.

2.2Values come in kinds

Two kinds matter this week:

7 and "7" are not the same thing, in the same way that the number seven is not the same as the pencil mark you draw for it:

numbers add, text joins
print(7 + 3)
print("7" + "3")
10 73

Mixing them is the single most common beginner error: print("7" + 3) stops with TypeError: can only concatenate str (not "int") to str. Translated: "you asked me to glue a number onto some text and I do not know how."

If you are ever unsure what kind of value you are holding, ask Python directly with type(...). It is a habit worth building early:

ask what kind it is
print(type(7))
print(type(2.5))
print(type("7"))
<class 'int'> <class 'float'> <class 'str'>

int is a whole number, float a decimal one, str a string. Those three names appear in every error message you will read this week, so it pays to recognise them on sight.

2.3Variables: giving a value a name

A variable is a name pointing at a value. The = sign is not "equals" in the school sense — read it as "gets" or "is now".

naming things
student_count = 32
course_name = "Algorithm Analysis"

print(course_name)
print(student_count)

student_count = student_count + 1   # one more student joined
print(student_count)
Algorithm Analysis 32 33

That fifth line looks like nonsense as mathematics and is perfectly ordinary as an instruction: take the current value of student_count, add one, and make the name point at the result.

Naming rules and manners

Rules: letters, digits and underscores; no spaces; cannot start with a digit. Manners: student_count, not sc or x1. In this course, unreadable names cost marks — and later, when you count the steps of your own code, you will be grateful you can tell what it does.

Trace it like Python does

Read student_count = student_count + 1 in two beats. Beat one: work out the right-hand side using the current value — 32 + 1 is 33. Beat two: make the name student_count point at 33, forgetting the old value entirely. Every assignment works this way: right side first, then the name moves. Hold that and the "how can x = x + 1?" puzzle dissolves.

2.4Arithmetic and f-strings

the operators you need
a = 17
b = 5

print(a + b)     # 22   addition
print(a - b)     # 12   subtraction
print(a * b)     # 85   multiplication
print(a / b)     # 3.4  division, always gives a decimal
print(a // b)    # 3    whole-number division ("how many times fits")
print(a % b)     # 2    remainder
print(a ** 2)    # 289  a to the power 2

To mix text and values in one message, put an f before the opening quote and wrap any value in curly braces. This is called an f-string and it is how every message in this course gets printed:

readable output
name = "Ada"
items = 1000
seconds = 0.0421

print(f"{name} searched {items} items in {seconds} seconds")
print(f"That is {items / seconds:.0f} items per second")
Ada searched 1000 items in 0.0421 seconds That is 23753 items per second

The :.0f means "show it as a decimal number with 0 digits after the point". :.3f gives three digits — you will use that constantly once we start timing things.

The // and % pair is worth a second look, because it is exactly how you split a total into groups. Suppose 100 students must be seated at tables of 7:

tables and leftovers
students = 100
per_table = 7

full_tables = students // per_table    # whole tables that fill up
leftover    = students % per_table      # students still standing

print(f"{full_tables} full tables, {leftover} students at a part-full one")
14 full tables, 2 students at a part-full one

// answers "how many whole groups?" and % answers "how many left over?". That remainder trick — is a number even? is it a multiple of 3? — shows up again in week 3 the moment we start writing loops.

2.5A few everyday things you can do with text

Strings are not just something to print — you can measure and reshape them. Four moves cover most of what you need this term:

string basics
word = "Quokka"

print(len(word))          # 6      how many characters
print(word.upper())       # QUOKKA
print(word.lower())       # quokka
print(word + "s")         # Quokkas   joining
print("ha" * 3)           # hahaha    repeating
6 QUOKKA quokka Quokkas hahaha

len(...) gives the number of characters — the same len you will use on lists in week 4. The .upper() and .lower() are called methods: little jobs a value knows how to do to itself, written as a dot after the value. Joining with + and repeating with * are the same operators as for numbers, doing the text-shaped thing instead.

a small greeting builder
first = "ada"
last  = "lovelace"

full = first.upper() + " " + last.upper()
print(f"Welcome, {full} — your name has {len(first) + len(last)} letters.")
Welcome, ADA LOVELACE — your name has 11 letters.

Nothing here is deep, but it is the everyday plumbing of real programs, and it lets you make output that reads like a sentence rather than a pile of raw values.

2.6Comments, and asking the user

input always gives text
# Anything after a # is a note for humans. Python skips it.
answer = input("How many rows does your file have? ")
rows = int(answer)          # turn the text "500" into the number 500

print(f"At one row per second that takes {rows} seconds.")
print(f"That is about {rows / 60:.1f} minutes.")

input() always hands back text, even when the user typed digits. int(...) converts text to a whole number, float(...) to a decimal one, str(...) converts back to text. Forgetting int() is beginner error number two.

2.7Three error messages, decoded

MessageWhat it really meansUsual fix
SyntaxErrorThe sentence is not Python. Something is unbalanced.Look for a missing quote, bracket or colon — often on the line above the one shown.
NameError: name 'x' is not definedYou used a name Python has never seen.Typo, or the cell that created it was never run. In Colab, re-run cells from the top.
TypeErrorYou asked for an operation the kinds involved do not support.Usually text where a number belongs: wrap it in int().
Reading errors properly

Python prints the error last, after a wall of technical trace. Start at the bottom line, read it as a sentence, then look at the line number it names. Beginners who learn to read the last line save themselves hundreds of hours.

2.8Common mistakes: kinds and conversion

Almost every error you will hit for the next month comes from mixing kinds of value. Here are the three that catch everyone, each shown broken and then fixed.

1. Adding text to a number. The classic, straight from input:

broken, then fixed
age = input("Your age: ")    # suppose the user types 20
# print(age + 1)            -> TypeError: age is the text "20"
print(int(age) + 1)          # 21   convert first, then add
21

2. Gluing a number into a message with +. Use an f-string instead:

two ways to build a message
score = 95
# print("You scored " + score)   -> TypeError
print("You scored " + str(score))   # works: convert the number to text
print(f"You scored {score}")        # nicer: f-string does it for you
You scored 95 You scored 95

3. Losing the decimals with int. int does not round, it chops:

chopping vs rounding
print(int(3.9))        # 3   the .9 is thrown away, not rounded
print(round(3.9))      # 4   round() rounds to nearest
print(round(3.14159, 2))  # 3.14   round to 2 decimals
3 4 3.14
The rule under all three

Python will happily store a number as text and text as a number, and it will not warn you until you try to use them together. When an operation refuses, ask "what kind is each side?" — a quick type(...) answers it — and convert the odd one out with int, float or str.

2.9A first step count

We can already do a tiny piece of analysis. Count the instructions Python performs in this program:

how many steps?
price = 250
tax = price * 0.20
total = price + tax
print(f"Total: {total}")

Four lines, four steps, every single time you run it. It does not matter whether price is 250 or 250 million: the work does not depend on the size of the input at all. Hold on to that idea — in week 8 it gets the name O(1), and it is the best kind of program there is.

2.10Try it yourself

Task 1 — a receipt

Ask the user for an item name, a unit price and a quantity. Print a two-line receipt showing the line total and the total with 20% tax, both with two decimals.

Solution
receipt.py
item = input("Item: ")
price = float(input("Unit price: "))
qty = int(input("Quantity: "))

line_total = price * qty
with_tax = line_total * 1.20

print(f"{qty} x {item} = {line_total:.2f}")
print(f"With 20% tax:  {with_tax:.2f}")
Task 2 — swap two names

Start with a = "left" and b = "right". Swap them so that a holds "right" and b holds "left". Try it first with only the tools from this page.

Solution

The careful version uses a third name; Python also offers a shortcut:

two ways
temp = a
a = b
b = temp

# or, the Python shortcut:
a, b = b, a

Both are three steps and one step respectively — and both are independent of what the values are. Swapping never gets slower.

Task 3 — predict, then run

Write your prediction down before running each line.

predict the output
print(10 / 4)
print(10 // 4)
print(10 % 4)
print("10" * 3)
print(10 * 3)
Answers

2.5, 2, 2, 101010, 30. The fourth one surprises nearly everyone: multiplying text repeats it.

Task 4 — split the bill

A bill of 137 is split among 4 friends. Using // and %, print how much each pays in whole units and how many units are left over. Then print the exact per-person share to two decimals using /.

Solution
split.py
bill = 137
people = 4

each = bill // people
left = bill % people

print(f"{each} each, {left} left over")
print(f"Exact share: {bill / people:.2f}")
34 each, 1 left over Exact share: 34.25

The whole-number split leaves 1 over; the exact share puts that leftover back as .25 each.

Task 5 — a name badge

Ask for a first name and a surname. Print a badge line that shows the full name in capitals and states how many letters it has in total (ignore the space).

Solution
badge.py
first = input("First name: ")
last = input("Surname: ")

full = first.upper() + " " + last.upper()
letters = len(first) + len(last)

print(f"[ {full} ]")
print(f"{letters} letters in your name")

Adding len(first) + len(last) counts only the letters; using len(full) would include the space and give one more.

Task 6 — find the bug

This program is meant to add 5 to whatever number the user types, but it crashes. Say which error it raises, why, and fix it with a one-word change.

buggy.py
n = input("A number: ")
print(n + 5)
Show the answer

It raises a TypeError: input() returns text, so n is a string like "12", and Python will not add the number 5 to text. The fix is to convert on the way in:

fixed.py
n = int(input("A number: "))
print(n + 5)

Wrapping the input in int(...) makes n a real number before the addition.

2.11Self-check

What does count = count + 1 do?

= is an instruction ("make this name hold that value"), not a claim about equality. It runs right-hand side first.

The user types 25 at age = input("Age: "). What is in age?

input() always gives text. age + 1 would fail with a TypeError until you write int(age).

The four-line receipt program from §2.9 is run with a price of 250, then with a price of 250 000 000. How does the number of steps change?

The work depends on the number of instructions, not on how large the numbers are. This is the O(1) pattern you will name in week 8.

What does 17 % 5 give, and what question does it answer?

% is the remainder: 5 fits into 17 three times (15), leaving 2. // would give the "how many times" answer, 3.

Which line prints 3 for a value of 3.9?

int() chops the decimal part off rather than rounding, so 3.9 becomes 3. round(3.9) would give 4.

2.12Homework

Due before week 3
  1. Create AA_Week02.ipynb. Solve Tasks 1–6 above, one cell each.
  2. Write a "unit converter": ask for a distance in kilometres, print it in miles, metres and feet, each to two decimals.
  3. Write a "time splitter": ask for a number of seconds and print it as whole minutes and leftover seconds using // and % (for example, 200 seconds is 3 minutes and 20 seconds).
  4. Deliberately produce all three errors from §2.7. Paste each error message into a text cell and write one sentence explaining what Python was complaining about.
  5. In a text cell, count the steps of your converter and say whether the count depends on the number the user typed. Explain in two sentences.

2.13Words from this week

TermMeaning in plain words
variableA name that points at a value.
assignment (=)"Make this name hold that value." Right side first.
stringText, written in quotes.
int / floatWhole number / decimal number.
typeThe kind of a value; ask with type(x).
methodA job a value knows how to do to itself, written with a dot, e.g. word.upper().
f-stringf"..." — text with {values} dropped into it.
commentA note after # that Python ignores.
TypeError"These kinds of value do not go together like that."
Where this leads

You can now give the computer one instruction at a time. Real work means repeating instructions — so week 3 brings loops, and a counter that measures them.