Algorithm Analysis course guide
Week 02

Week 02 — Your First Python: Values, Names, and Output

This is supporting reference material. Return to Week 02 lesson →

About this reference

Detailed teacher notes, original lesson link, analysis prompts, model solutions, and added timed-practice material.

Find a topic in this reference

The big question

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

This week you express precise instructions in Python and follow their changing values. Understand each line before asking how fast it runs. Loops and functions come later.

By the end, you should be able to distinguish numbers from text, trace assignment, choose an arithmetic operator, convert numeric text, and display a readable result. You should also be able to explain an error using its final message and the line that caused it.

Retrieve before you type

QuestionAnswer and reason
What is an input?Data a method starts with, such as a price and a quantity.
Is “calculate the answer” a sufficient instruction?No. It must identify the operation and the values involved.
Does getting one example right prove correctness?No. Other allowed inputs can expose missing cases.
What must we choose before counting work?A unit: for example, item inspections or executions of a particular instruction.

In Colab, a code cell groups editable instructions. Earlier cells may supply later values. These examples are independent: each defines everything it uses. When old output disagrees with edited code, restart and run from the beginning.

Türkçe açıklama: Hücrede görünen metin ile bellekteki değerler farklı olabilir. Bir atama satırını değiştirmek, o hücreyi çalıştırmadan değişkeni güncellemez. Başlangıçta her örneğin kendi başlangıç değerlerini tanımlaması bu gizli bağımlılığı azaltır.

Values first, names second

7 is an integer. 2.5 is a floating-point number. "7" is text containing one character. Quotes tell Python to treat their contents as a string; they are not printed as part of that string. The operator + therefore has different meanings: 7 + 3 produces the number 10, while "7" + "3" produces the text "73".

Python's type names are int, float, and str; type(value) reports the kind. Floats have limited precision: not every decimal fraction is stored exactly. Calculate the intended arithmetic first, then format its presentation.

Türkçe açıklama: "12" yazısı, matematiksel olarak on iki sayısı değildir; iki karakterden oluşur. Bilgisayar bunun telefon numarası mı, etiket mi, sayı mı olduğunu kendiliğinden seçmez. İşlem yapmak istiyorsan sayıya dönüştürme kararını sen vermelisin.

An assignment such as count = 4 attaches the name count to a value. Read = as “store the result on the right using this name.” It is not an equation that must remain true forever. For count = count + 1, first retrieve the old value, calculate 4 + 1, then replace the stored value with 5. The old 4 is used before the new 5 is assigned.

Use descriptive names such as unit_price. Names cannot contain spaces or start with a digit. Capitalization matters: total and Total differ.

Worked example 1: a receipt with a complete trace

Suppose one notebook costs 50 units of currency. We buy three and apply a tax rate of 20% to the subtotal. Here, 0.20 is the rate because 20 / 100 = 0.20. This is a classroom arithmetic example, with the rate supplied as input.

python
unit_price = 50
quantity = 3
tax_rate = 0.20
subtotal = unit_price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
print(f"Subtotal: {subtotal:.2f}")
print(f"Tax: {tax:.2f}")
print(f"Total: {total:.2f}")
output
Subtotal: 150.00
Tax: 30.00
Total: 180.00
InstructionCalculation or meaningValue afterward
unit_price = 50Store the price of one itemunit_price is 50
quantity = 3Store how many itemsquantity is 3
tax_rate = 0.20Store twenty hundredthstax_rate is 0.20
subtotal = unit_price * quantity50 × 3subtotal is 150
tax = subtotal * tax_rate150 × 0.20tax is 30.0
total = subtotal + tax150 + 30total is 180.0
Three print linesInsert values into readable labelsThree lines appear

The f before a quoted string allows expressions inside braces. In {total:.2f}, total supplies the value and .2f requests two digits after the decimal point. Formatting 180.0 as 180.00 changes its displayed form; it does not add more money or make the internal calculation more precise.

Türkçe açıklama: Yüzdeyi iki kez uygulama: tax_rate = 0.20 zaten yüzde yirmidir, tekrar 100'e bölünmez. Önce ara toplamı, sonra vergi miktarını, en son ikisinin toplamını buluyoruz. Bu ayrım hem hesabı kontrol etmeyi hem de yanlış satırı bulmayı kolaylaştırır.

Arithmetic: ask what kind of answer is needed

ExpressionResultMeaning
17 + 522Addition
17 - 512Subtraction
17 * 585Multiplication
17 / 53.4Ordinary division
17 // 53Floor division
17 % 52Remainder
17 ** 228917 squared: 17 × 17

For nonnegative quantities, floor division answers how many complete groups fit. The remainder is what is left: 17 = 3 × 5 + 2. With negative values, flooring moves toward negative infinity: -7 // 3 is -3, whereas int(-7 / 3) is -2 because int truncates toward zero. They are different operations.

Use parentheses when an expression's grouping matters. (20 + 10) / 3 means 30 / 3 = 10; 20 + 10 / 3 performs division first. A line that states the intended grouping clearly is easier to inspect than a clever-looking expression.

Worked example 2: full tables and leftover students

There are 100 students and seven seats per table. We need the number of full tables, the number of students left over, and enough tables for everyone.

python
students = 100
seats_per_table = 7
full_tables = students // seats_per_table
left_over = students % seats_per_table
tables_needed = (students + seats_per_table - 1) // seats_per_table
print(full_tables, left_over, tables_needed)
output
14 2 15
StepArithmeticInterpretation
Divide into full groups100 // 7 = 14Fourteen tables can be filled
Find remaining students100 % 7 = 2Two students still need seats
Check the decomposition14 × 7 + 2 = 100Every student is accounted for
Round groups upward(100 + 7 − 1) // 7 = 106 // 7 = 15Provide fifteen tables

The last formula works for nonnegative whole numbers of students and a positive number of seats. Adding six before division makes any leftover group count as another table. It still gives 14 when there are exactly 98 students: (98 + 6) // 7 = 104 // 7 = 14. It also gives zero for zero students.

Türkçe açıklama: 100 / 7 sonucu yaklaşık 14.286'dır, fakat kesirli bir masa hazırlayamayız. “Tam dolan masa” ile “gereken masa” farklı sorulardır. Önce soruyu belirlemek, doğru bölme işlemini seçmekten önce gelir.

Text, conversion and error repair

len("quokka") is 6. "Ada" + " " + "Lovelace" joins two names with a space. "ha" * 3 repeats text as "hahaha". .upper() and .lower() produce uppercase and lowercase versions. Spaces count as characters, so the joined full name has 12 characters; the two names without the joining space have 11.

The original lesson introduces input, which always returns text. To keep this guide runnable without prompts, imagine it returned raw_quantity = "12". Then int(raw_quantity) produces the integer 12. float("12.5") produces a numerical value with a fractional part; str(12) produces text. These conversions have a purpose, not a universal “fix everything” role: int("twelve") cannot interpret the word as a decimal integer.

When code fails, read the final error, locate its instruction, and inspect the values and types involved.

ErrorTypical causeRepair reasoning
SyntaxErrorAn unclosed quote or bracketMake the instruction grammatically complete
NameErrortotla used instead of totalCheck spelling and whether assignment ran
TypeError"12" + 5Decide whether addition or text joining was intended

Türkçe açıklama: Hata mesajı “başaramadın” demek değildir; bilgisayarın hangi isteği yorumlayamadığını söyler. "12" + 5 için sayısal amaç varsa int("12") + 5, metinsel amaç varsa "12" + str(5) uygundur. Bu iki çözüm farklı sonuçlar üretir: 17 ve "125".

Three practice problems with complete solutions

Practice 1 — predict before running

Find the results of 10 / 4, 10 // 4, 10 % 4, "10" * 3, and 10 * 3. Explain why the last two differ.

Solution 1

The results are 2.5, 2, 2, "101010", and 30. Two full groups of four use eight, leaving two: 10 = 2 × 4 + 2. A string multiplied by three repeats its characters; a number multiplied by three performs arithmetic. Türkçe: Tırnak işaretleri işlemin anlamını değiştirir; görünüşte aynı olan 10 ve "10" aynı tür değildir.

Practice 2 — divide a bill

A bill is 137 units and four people share it equally. Find the whole-unit amount per person, the leftover whole units, and the exact share for this example.

Solution 2

137 // 4 = 34 and 137 % 4 = 1, because 4 × 34 + 1 = 137. The exact share here is 137 / 4 = 34.25. If everyone pays only 34, the group pays 136 and remains one short. Türkçe: Kalan 1, kişi başına 1 değildir; grubun tamamının kalanıdır. Dörde bölününce herkesin payına 0.25 eklenir.

Practice 3 — swap without losing information

Start with a = "left" and b = "right". Exchange their values using a temporary name. Explain why assigning a = b and then b = a fails.

Solution 3

python
a = "left"
b = "right"
temporary = a
a = b
b = temporary
print(a, b)
output
right left

The temporary name preserves "left". The next line changes a to "right"; the final assignment retrieves the saved "left" for b. Without saving it, a = b leaves both names referring to "right", so b = a merely copies that same value again. Türkçe: Atama geriye dönüp eski değeri hatırlamaz; kaybolacak bilgiyi değiştirmeden önce saklamak gerekir.

Misconceptions and glossary

MisconceptionCorrection
= asserts mathematical equalityAssignment calculates the right side and updates the left name
.2f fixes inaccurate arithmeticIt controls displayed decimal places
Every written line costs exactly the same timeWe may count statement executions in a simplified model; actual operations differ
A fresh name automatically has a valueIt must be assigned before use
EnglishTürkçeWorking meaning
ValueDeğerData such as 12 or "Ada"
Variable nameDeğişken adıA name used to retrieve a value
AssignmentAtamaStore a calculated result under a name
ConversionTür dönüşümüExplicitly obtain another representation
RemainderKalanWhat is left after complete groups
TraceAdım adım izlemeRecord values as instructions execute

Readiness, repair and the next bridge

Explain score = score + 2 when the old score is 8. Answer: retrieve 8, calculate 10, store 10. Explain "8" + "2". Answer: it joins text to make "82". Explain why a four-statement calculation does not repeat more statements when its ordinary input changes from 10 to 100. Answer: there is no repetition instruction; its chosen statement count stays four. Very large integers or longer output can still change lower-level costs.

If assignment is unclear, draw an “old value / calculation / new value” table. If types are unclear, label every literal as number or text before calculating. Week 3 adds decisions and repetition to this same tracing habit: one written line may then execute many times.

Follow the value of each name

In Python, assignment means giving a name a value. In x = x + 3, Python calculates the right side first, then gives x that new value. A trace is a written record of the values after each step. Printing shows only the values you ask to see.

Draw or trace. Trace x = 4, y = x, x = x + 3. Draw each name and the integer it refers to after every instruction.

Predict before checking. Does y become 7 when x changes? Does writing three lines tell us how long they take on every computer?

Worked reasoning

y stays 4. The line y = x gives y the value of x at that moment. It does not make y follow later changes to x. Following the values explains the printed answer. Counting steps and timing the program are two different tasks that we will learn later.

python
x = 4
y = x
x = x + 3
assert (x, y) == (7, 4)
print(x, y)

Change one thing. Change the final line to y = x + 3. Predict both values first. Later, when values are lists that can be changed, distinguish giving a name a different value from changing a list shared by two names.

Türkçe: Atama anındaki değeri izle; adlar canlı formül değildir. Çıktı, işlem sayısı ve geçen süre farklı sorulardır.

Additional analysis laboratory

Week 2 is still programming-light, but it already contains analysis: each assignment has an old state and a new state. Students should read code from right to left first, then store the new value.

Code shapeCounted actionCommon mistake
x = x + 1one read, one addition, one write in the teaching modeltreating it like algebra
total = price * countmultiplication before assignmentoverwriting one quantity too early
print(answer)output eventconfusing displayed text with stored data

Extra exam-style prompt: Start with a = 3 and b = 5. Execute a = b, then b = a + 2. What are the final values? How could we swap the old values safely?

Solution: After a = b, both names refer to the value 5. Then b = a + 2 stores 7. The old value 3 has been lost. To swap safely, save one old value first: temp = a, then a = b, then b = temp.

Turkce: Degisken ismi kutu etiketi gibi dusunulebilir. Eski degeri korumak istiyorsan, ustune yazmadan once baska bir etikete tasimalisin.

Other reference chapters