Your First Python: Values, Names, and Output
print, variables, numbers, text — the four things you need before anything else.
- 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.
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.
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.
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:
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.
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".
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.
2.4Arithmetic and f-strings
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.
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:
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.
2.6Comments, and asking the user
# 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
| 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.
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:
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.
2.9A first step count
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}")
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
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
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.
Solution
The careful version uses a third name; Python also offers a shortcut:
temp = a
a = b
b = temp
# or, the Python shortcut:
a, b = b, aBoth are three steps and one step respectively — and both are independent of what the values are. Swapping never gets slower.
Write your prediction down before running each line.
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.
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
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).
Solution
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)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:
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?
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.2.12Homework
- Create
AA_Week02.ipynb. Solve Tasks 1–6 above, one cell each. - Write a "unit converter": ask for a distance in kilometres, print it in miles, metres and feet, each to two decimals.
- 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). - 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.
- 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
| 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.