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.

How do I give the computer one instruction at a time?

Lesson

Turn text into a calculation

A receipt: input → number → calculation → output
  1. "4.10"text from input()
  2. 4.1float(...)
  3. 4.1 × 3total = 12.3
  4. 12.30format to 2 decimals
Run in Colab · predict the result first
price = float(input("Price: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(f"Total: {total:.2f}")

Enter 4.10 and 3. input() returns text; convert it before doing arithmetic. int stores whole numbers, float decimal approximations, str text and bool True/False. Formatting changes the display, not the stored value.

A name keeps its latest value

Run in Colab · predict the result first
a = 4
b = 9
temp = a
a = b
b = temp
print(a, b)
After lineabtemp
Start49—
temp = a494
a = b994
b = temp944

= assigns the value on its right to the name on its left. It is not an algebraic equation. Python runs these lines in order.

Read the operation, then the type

ExpressionResultMeaning
10 / 42.5division
10 // 42floor division
10 % 42remainder
2 ** 38power
"10" * 3"101010"repeat text
int("10") * 330multiply numbers
len("cat")3count characters
"Cat".lower()"cat"make lowercase
For integer a and nonzero integer ba = (a // b) × b + (a % b)

Use parentheses to make order clear: (2 + 3) * 4 gives 20. A comment starts with #; it explains a choice without running an instruction.

Fix the cause, not the message

ErrorExampleRepair
NameErrorprint(totl)Use the name you assigned: total.
TypeError"3" + 2Convert text to a number, or make both values text.
ValueErrorint("three")Supply valid digits.

Read the last line of the error, then inspect the named line. To count work this week, count assignments or arithmetic operations explicitly; one printed line can contain several operations.

Practice

Practice questions

10 test questions · 2 written questions · 12 total

Each question is followed by its answer and explanation. Hard questions also include a starting hint and smaller reasoning steps.

Test questions

Choose one option. Cost questions state their model and whether the bound is tight, expected or worst-case. Here lg means log₂, and heap positions start at 1.

Question 1 · easy

In the RAM model, the statement “sort the list” costs:

  1. 1 step
  2. log n steps
  3. as many steps as the sorting algorithm needs
  4. 0 steps

Answer: option C. A fixed-size primitive operation has constant cost in the chosen RAM model. Sorting a list is a subroutine, so count the operations performed inside it.

Question 2 · easy · course question

After x = 4 followed by x = x + 3, what value does x hold?

  1. 4
  2. 3
  3. 7
  4. 43

Answer: option C. The right side uses the old value 4. Adding 3 gives 7, which replaces the previous value of x.

Question 3 · easy · course question

What does print(2 ** 3) display in Python?

  1. 8
  2. 6
  3. 5
  4. 23

Answer: option A. ** means exponentiation: 2³ = 2 × 2 × 2 = 8. Multiplication would use *.

Question 4 · easy · course question

What does print("4" + "5") display?

  1. 9
  2. 20
  3. an error
  4. 45

Answer: option D. Both operands are strings, so + joins the text. It does not add the numeric values.

Question 5 · easy · course question

To add 2 numerically to the integer text "12", which expression should you use?

  1. "12" + 2
  2. int("12") + 2
  3. str("12") + "2"
  4. "12" * 2

Answer: option B. int("12") converts the text into the integer 12. The result is 14; the other expressions either fail or perform string operations.

Question 6 · easy · course question

What value does input() return before you explicitly convert it?

  1. always an integer
  2. always a floating-point number
  3. a string
  4. a list of numbers

Answer: option C. input() returns the entered text as a string. Use a suitable conversion such as int or float when you need a number.

Question 7 · easy · course question

What does print(7 // 2) display?

  1. 3
  2. 3.5
  3. 4
  4. 1

Answer: option A. // is floor division. Here 7/2 is 3.5, whose floor is 3.

Question 8 · easy · course question

What does print(7 % 2) display?

  1. 3
  2. 3.5
  3. 0
  4. 1

Answer: option D. % gives the remainder. Since 7 = 3 × 2 + 1, the remainder is 1.

Question 9 · easy · course question

After x = 2; y = x; x = 9, what value does y hold?

  1. 9
  2. 2
  3. 11
  4. no value

Answer: option B. Assigning y = x binds y to the integer value 2. Later rebinding x to 9 does not change y.

Question 10 · easy · course question

Which Python expression tests whether x equals 5?

  1. x = 5
  2. x := 5
  3. x == 5
  4. x + 5

Answer: option C. == compares values and produces True or False. A single = assigns a value rather than testing equality.

Written questions

Read each question together with its explanation, trace or proof. Numbering continues from the test questions.

Question 11 · easy

State the sorting problem precisely, as an input and a required output.

Answer & reasoning

input, a sequence of n numbers a₁, …, aₙ; output, a rearrangement of the same numbers so that a₁ ≤ a₂ ≤ … ≤ aₙ.

Question 12 · easy

In the RAM model, what does the statement x = a + b cost, and what does the statement “sort the list” cost?

Answer & reasoning

Choose and state an operation-count convention. For fixed-size values, x = a + b uses a fixed number of primitive actions, so it has constant cost. A simplified model may count the whole statement as one step; a finer model counts reads, addition and assignment separately. “Sort the list” costs the work of the sorting algorithm, not one step. Large-integer arithmetic requires a bit-cost model.

Three core tasks

Predict on paper, run the code, then explain any difference. Use the animations below to inspect individual steps.

1. Trace

Start with a = 4 and b = 9. What happens with only a = b; b = a?

Check your reasoning

Both end as 9: the first assignment loses the old a. Save it first or use a, b = b, a.

2. Calculate

Predict 17 // 5, 17 % 5 and 17 / 5 before running them.

Check your reasoning

3, 2 and 3.4; 17 = 3 × 5 + 2.

3. Change one thing

Add a 20% tax to the receipt and display two decimal places.

Check your reasoning

Use print(f"Total: {total * 1.20:.2f}"). For 4.10 × 3 the display is 14.76.

Explore the animations & more worked tasks

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.

Animate it — run the receipt with your own typing
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.

Animate it — watch the name arrows move
Solution

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

temporary-name version
a = "left"
b = "right"
temp = a
a = b
b = temp
print(a, b)
right left
shortcut, starting again
a = "left"
b = "right"
a, b = b, a
print(a, b)
right left

Excluding setup and printing, these versions execute three assignment statements and one assignment statement respectively. Both use a fixed number of name-binding operations. Run them from their own starting values; applying both swaps to the same pair would undo the first swap.

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)
Animate it — predict each line, then run it
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 /.

Animate it — deal the bill out in whole rounds
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).

Animate it — build the badge and count the letters
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)
Animate it — trace the crash and pick the fix
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.

Check your understanding

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.
Extra material & reference
Optional depth · full technical reference

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:

  • Numbers — 7, -3, 2.5. No quotes. You can do arithmetic with them.
  • Text (Python calls it a string) — "quokka", "7". In quotes. It is a sequence of characters.

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}")

Count each executed statement as one step: there are four, whether price is 250 or 250 million. This chosen statement count does not change with the price. It is a simplified cost model, not a promise that every instruction takes the same measured time. Arithmetic on very large numbers and printing longer output can involve more work. With bounded-size elementary operations, a fixed count gives the constant-growth idea called O(1) in week 8.

From the beginner notes · Lectures 1, 2

Write the input and output before the program

An algorithm gives steps for a range of possible inputs. A program puts those steps into code. Sorting means returning the same items in order from smallest to largest, allowing equal values; it does not mean printing a particular example. Write names for the input, its size and the output before you choose Python statements.

For sensor records, specify what is being ordered: timestamp, temperature or sensor identifier. Repeated readings are still separate records. Printing a plausible list is not enough: the output must preserve every record as well as satisfy the ordering rule.

Later we will use the RAM model: a simplified way to count basic computer operations. For now, notice that x = a + b performs a fixed amount of work on values whose size is kept fixed, while an instruction such as “sort all readings” hides work that grows with the data.

Engineering use. Ask a teammate to check your output specification without seeing your code.

Learning goals & class plan
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.

Three-hour interactive studio

00:00–01:00: launch, predict–run–explain cycle, questions  ·  01:00–01:10: break  ·  01:10–02:00: worked variation, peer instruction, questions  ·  02:00–02:10: break  ·  02:10–03:00: core mechatronics practice, exam bridge, and exit ticket.

Ask at any point. Weekly self-checks stay private; optional extensions are not collected.

Need a slower explanation? Open the English + Türkçe reference guide.

Optional extra practice

2.12Optional Studio Extension

Optional practice · no submission or deadline
  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.
Optional reference · Words from this week

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.