Question 1 · easy
In the RAM model, the statement “sort the list” costs:
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.
print, variables, numbers, text — the four things you need before anything else.
How do I give the computer one instruction at a time?
"4.10"text from input()4.1float(...)4.1 × 3total = 12.312.30format to 2 decimalsprice = 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 = 4
b = 9
temp = a
a = b
b = temp
print(a, b)| After line | a | b | temp |
|---|---|---|---|
| Start | 4 | 9 | — |
| temp = a | 4 | 9 | 4 |
| a = b | 9 | 9 | 4 |
| b = temp | 9 | 4 | 4 |
= assigns the value on its right to the name on its left. It is not an algebraic equation. Python runs these lines in order.
| Expression | Result | Meaning |
|---|---|---|
| 10 / 4 | 2.5 | division |
| 10 // 4 | 2 | floor division |
| 10 % 4 | 2 | remainder |
| 2 ** 3 | 8 | power |
| "10" * 3 | "101010" | repeat text |
| int("10") * 3 | 30 | multiply numbers |
| len("cat") | 3 | count characters |
| "Cat".lower() | "cat" | make lowercase |
Use parentheses to make order clear: (2 + 3) * 4 gives 20. A comment starts with #; it explains a choice without running an instruction.
| Error | Example | Repair |
|---|---|---|
| NameError | print(totl) | Use the name you assigned: total. |
| TypeError | "3" + 2 | Convert text to a number, or make both values text. |
| ValueError | int("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.
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.
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:
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?
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?
Answer: option A. ** means exponentiation: 2³ = 2 × 2 × 2 = 8. Multiplication would use *.
Question 4 · easy · course question
What does print("4" + "5") display?
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?
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?
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?
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?
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?
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?
Answer: option C. == compares values and produces True or False. A single = assigns a value rather than testing equality.
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.
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?
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.
Predict on paper, run the code, then explain any difference. Use the animations below to inspect individual steps.
Start with a = 4 and b = 9. What happens with only a = b; b = a?
Both end as 9: the first assignment loses the old a. Save it first or use a, b = b, a.
Predict 17 // 5, 17 % 5 and 17 / 5 before running them.
3, 2 and 3.4; 17 = 3 × 5 + 2.
Add a 20% tax to the receipt and display two decimal places.
Use print(f"Total: {total * 1.20:.2f}"). For 4.10 × 3 the display is 14.76.
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.
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}")
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.
The careful version uses a third name; Python also offers a shortcut:
a = "left"
b = "right"
temp = a
a = b
b = temp
print(a, b)a = "left"
b = "right"
a, b = b, a
print(a, b)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.
Write your prediction down before running each line.
print(10 / 4)
print(10 // 4)
print(10 % 4)
print("10" * 3)
print(10 * 3)2.5, 2, 2, 101010, 30. The fourth one surprises nearly everyone: multiplying text repeats it.
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 /.
bill = 137
people = 4
each = bill // people
left = bill % people
print(f"{each} each, {left} left over")
print(f"Exact share: {bill / people:.2f}")The whole-number split leaves 1 over; the exact share puts that leftover back as .25 each.
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).
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.
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.
n = input("A number: ")
print(n + 5)
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:
n = int(input("A number: "))
print(n + 5)Wrapping the input in int(...) makes n a real number before the addition.
What does count = count + 1 do?
The user types 25 at age = input("Age: "). What is in age?
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?
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.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.
print("first")
print("second")
print("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.
Two kinds matter this week:
7, -3, 2.5. No quotes. You can do arithmetic with them."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:
print(7 + 3)
print("7" + "3")
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:
print(type(7))
print(type(2.5))
print(type("7"))
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.
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".
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)
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.
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.
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.
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:
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")
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:
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")
// 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.
Strings are not just something to print — you can measure and reshape them. Four moves cover most of what you need this term:
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
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.
first = "ada"
last = "lovelace"
full = first.upper() + " " + last.upper()
print(f"Welcome, {full} — your name has {len(first) + len(last)} 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.
# 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.
| Message | What it really means | Usual fix |
|---|---|---|
SyntaxError | The 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 defined | You 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. |
TypeError | You asked for an operation the kinds involved do not support. | Usually text where a number belongs: wrap it in int(). |
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.
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:
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 add2. Gluing a number into a message with +. Use an f-string instead:
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 you3. Losing the decimals with int. int does not round, it chops:
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
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.
We can already do a tiny piece of analysis. Count the instructions Python performs in this program:
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
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.
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.
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.
AA_Week02.ipynb. Solve Tasks 1–6 above, one cell each.// and % (for example, 200 seconds is 3 minutes and 20 seconds).| Term | Meaning in plain words |
|---|---|
| variable | A name that points at a value. |
assignment (=) | "Make this name hold that value." Right side first. |
| string | Text, written in quotes. |
| int / float | Whole number / decimal number. |
| type | The kind of a value; ask with type(x). |
| method | A job a value knows how to do to itself, written with a dot, e.g. word.upper(). |
| f-string | f"..." — text with {values} dropped into it. |
| comment | A note after # that Python ignores. |
| TypeError | "These kinds of value do not go together like that." |
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.