Values and names¶

A barangay's records are made of single values: a household's number of members, the head's age, the barangay's name, whether the household farms. This module is about those values, the names you give them, and how to read the message Python gives when something goes wrong.

section what you do
1 · Numbers, text and true/false the three kinds of value every record is made of, and names for them
2 · Comments, docstrings and f-strings writing code a colleague can read, and text built from values
3 · Reading an error message what Python says when it cannot go on, and where to look first
In [1]:
import course
from course import check_cases, try_it

course.quizzes_at("2.0")

1 · Numbers, text and true/false¶

Every value in Python has a type, which says what you can do with it. Three types make up almost every record:

type what it holds examples
int whole numbers 6 members, 2020
float numbers with a decimal point 2.5 hectares, 33.3 per cent
str text, between quotes "Barangay 143", "0128"
bool True or False farms or not

A name (a variable) stands for a value, so you can use it again. = gives a name a value; it is not "equals" as in maths.

In [2]:
members = 6
head_age = 47
barangay = "Barangay 143"
farms = True

members, head_age, barangay, farms
Out[2]:
(6, 47, 'Barangay 143', True)

type(...) says what a value is. Run it, then change members above to 6.0 and run both cells again.

In [3]:
type(members), type(barangay), type(farms)
Out[3]:
(int, str, bool)

Arithmetic. +, - and * work as you expect. / always gives a float, even for 6 / 2. // gives the whole part of a division, and % what is left over: 50 people in households of 6 make 50 // 6 full households and 50 % 6 people over.

In [4]:
50 / 6, 50 // 6, 50 % 6
Out[4]:
(8.333333333333334, 8, 2)

Comparisons give a bool: == (equal), != (not equal), <, <=, >, >=. Note the double ==: a single = gives a name a value.

In [5]:
members >= 6, barangay == "Barangay 143", head_age < 18
Out[5]:
(True, True, False)

Text is not a number. A code such as a barangay's "0128" must stay text: as a number it is 128, and the leading zero is gone for good. int(...) turns text into a whole number, str(...) a number into text, and .zfill(n) adds zeros on the left of a text until it is n characters long.

In [6]:
int("0128"), str(128), str(128).zfill(4)
Out[6]:
(128, '128', '0128')

Naming rules. A name starts with a letter or _, holds only letters, digits and _, and is case-sensitive (Members and members are two names). Choose names that say what the value is: head_age, not x or a2.

Exercise 2.1 · Population density¶

Finish density(population, area_km2) so that it returns the number of people per square kilometre, rounded to a whole number. round(value) with no second input rounds to a whole number, and gives back an int.

call returns
density(1401, 0.12) 11675
density(880, 0.4) 2200
In [7]:
def density(population, area_km2):
    # Step 1: divide the population by the area
    # Step 2: return it rounded to a whole number
    raise NotImplementedError("Exercise 2.1")  # delete this line when your code is ready
In [8]:
try_it(density, 1401, 0.12)
Out[8]:

density(1401, 0.12): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [9]:
check_cases(
    "Exercise 2.1", density, [(f"density({p}, {a})", (p, a)) for p, a in [(1401, 0.12), (880, 0.4), (1029, 0.07), (25000, 3.3), (0, 1.0)]],
    what="barangays", hint="Divide, then round with `round(...)`.",
)
Out[9]:

Exercise 2.1: not attempted yet. Divide, then round with round(...).

If the check is red: common causes for Exercise 2.1
  • A decimal number such as 11675.000000000002: the result is not rounded. Return round(...) of it.
  • One less than expected: int(...) cuts the decimals off; round(...) rounds to the nearest.
  • A tiny number: the division is the wrong way round, area divided by population.

Exercise 2.2 · A barangay's code as text¶

Barangay codes are three digits, with leading zeros: barangay 7 is "007". Finish barangay_label(name, number) so that it returns the name, a space, and the three-digit code in brackets.

call returns
barangay_label("Malanday", 7) "Malanday (007)"
barangay_label("Barangay 143", 143) "Barangay 143 (143)"
In [10]:
def barangay_label(name, number):
    # Step 1: turn the number into text, three characters long with zeros on the left
    # Step 2: return the name, a space, and that code in brackets
    raise NotImplementedError("Exercise 2.2")  # delete this line when your code is ready
In [11]:
try_it(barangay_label, "Malanday", 7)
Out[11]:

barangay_label('Malanday', 7): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [12]:
check_cases(
    "Exercise 2.2", barangay_label, [(f'barangay_label("{n}", {c})', (n, c)) for n, c in [("Malanday", 7), ("Barangay 143", 143), ("Tumana", 45), ("Concepcion Uno", 100)]],
    what="barangays", hint="`str(...)` first, then `.zfill(3)`.",
)
Out[12]:

Exercise 2.2: not attempted yet. str(...) first, then .zfill(3).

If the check is red: common causes for Exercise 2.2
  • AttributeError: 'int' object has no attribute 'zfill': .zfill works on text. Turn the number into text with str(...) first.
  • "Malanday (7)": the code is not padded. Use .zfill(3).
  • A missing space or bracket: compare your text with the table, character by character.

Exercise 2.3 · Is it a large household?¶

The barangay counts a household as large when it has six members or more. Finish is_large(members) so that it returns True for a large household and False otherwise. A comparison already gives True or False, so no if is needed.

call returns
is_large(6) True
is_large(3) False
In [13]:
def is_large(members):
    # Step 1: return the comparison of members with 6
    raise NotImplementedError("Exercise 2.3")  # delete this line when your code is ready
In [14]:
try_it(is_large, 6)
Out[14]:

is_large(6): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [15]:
check_cases("Exercise 2.3", is_large, [(f"is_large({m})", (m,)) for m in [6, 3, 1, 12, 5, 7]], what="households", hint="Six or more is large.")
Out[15]:

Exercise 2.3: not attempted yet. Six or more is large.

If the check is red: common causes for Exercise 2.3
  • Wrong for exactly 6: > leaves six out. "Six or more" is >= 6.
  • "True" with quotes: that is text, not the value True. Return the comparison itself.

2 · Comments, docstrings and f-strings¶

Code is read far more often than it is written, mostly by someone else, or by you months later. Three tools make it readable:

  • A comment starts with #: Python ignores the rest of the line. Use it to say why, not what: # the 2020 census counts by barangay helps; # add one does not.
  • A docstring is a text in triple quotes on the first line of a function. It says what the function gives back; help(...) shows it.
  • An f-string builds a text from values, as in Exercise 1.1. After a name, a colon sets the format: {share:.1f} shows one decimal place, {population:,} adds thousands separators.
In [16]:
def household_line(barangay, members, share):
    """One line of the report: the barangay, its members, and its share of the city's population."""
    # The share is a percentage already; the report shows one decimal place
    return f"{barangay}: {members:,} people, {share:.1f}% of the city"


help(household_line)
household_line("Barangay 143", 1401, 0.4567)
Help on function household_line in module __main__:

household_line(barangay, members, share)
    One line of the report: the barangay, its members, and its share of the city's population.

Out[16]:
'Barangay 143: 1,401 people, 0.5% of the city'

print and the last line. In a notebook, a cell shows what its last line gives back. print(...) writes text out wherever it is in a cell, but gives back nothing (None). Inside functions, use return to hand back a result and print only to show something along the way: the checks read what is returned, never what is printed.

In [17]:
print("Kumusta,", "Ana")
"this text is the cell's last line, so the notebook shows it"
Kumusta, Ana
Out[17]:
"this text is the cell's last line, so the notebook shows it"

Escape characters. Inside a text, \n starts a new line and \t puts a tab. A quote inside a text needs the other kind of quote around it, or a backslash: "Mundo'y" or 'Mundo\'y'.

In [18]:
print("Barangay\tMembers\n143\t1401")
Barangay	Members
143	1401

Exercise 2.4 · A line for the report¶

Finish report_line(barangay, population, share) so that it returns a line such as Barangay 143: 1,401 people (0.5%): the population with a thousands separator, and the share (already a percentage) with one decimal place.

call returns
report_line("Barangay 143", 1401, 0.4567) "Barangay 143: 1,401 people (0.5%)"
report_line("Tumana", 25000, 12.0) "Tumana: 25,000 people (12.0%)"
In [19]:
def report_line(barangay, population, share):
    # Step 1: return an f-string; format the population with {population:,} and the share with {share:.1f}
    raise NotImplementedError("Exercise 2.4")  # delete this line when your code is ready
In [20]:
try_it(report_line, "Barangay 143", 1401, 0.4567)
Out[20]:

report_line('Barangay 143', 1401, 0.4567): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [21]:
check_cases(
    "Exercise 2.4", report_line,
    [(f'report_line("{b}", {p}, {s})', (b, p, s)) for b, p, s in [("Barangay 143", 1401, 0.4567), ("Tumana", 25000, 12.0), ("Malanday", 880, 3.04), ("Concepcion Uno", 1234567, 99.99)]],
    what="lines", hint="`{population:,}` and `{share:.1f}`.",
)
Out[21]:

Exercise 2.4: not attempted yet. {population:,} and {share:.1f}.

If the check is red: common causes for Exercise 2.4
  • 1401 without a comma: the population needs the :, format.
  • 0.4567%: the share needs :.1f.

3 · Reading an error message¶

When Python cannot go on, it stops and prints an error message, called a traceback. It looks alarming, but it is Python saying as exactly as it can what went wrong and where. Read it from the bottom up:

  1. The last line names the kind of error and the value involved: TypeError: can only concatenate str (not "int") to str.
  2. The line just above it is the line of your code that failed, with an arrow under the part that did.
  3. The lines higher up show how Python got there (which function called which). You rarely need them.

Run the cell below. It fails on purpose.

In [22]:
age = 47
"Head of household, aged " + age
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[22], line 2
      1 age = 47
----> 2 "Head of household, aged " + age

TypeError: can only concatenate str (not "int") to str

The last line says TypeError: can only concatenate str (not "int") to str: + joins two texts, but age is a number. str(age), or an f-string, fixes it. The errors you will meet most:

error usually means
NameError a name is used before it was given a value, or is misspelt (did you run the cell that sets it?)
TypeError a value of the wrong type: text and a number added, or a function given the wrong number of inputs
ValueError the right type but a value that does not fit: int("12a")
SyntaxError Python cannot read the line: a missing bracket, quote or colon
IndentationError the spaces at the start of a line do not match the lines around it
ZeroDivisionError a division by zero

Every Try it cell in the course explains the error your function raised in the same words.

Exercise 2.5 · Fix the function¶

The function below should return a head of household's age next year, but it raises an error. Run its Try it cell, read the last line of the message, and fix the function.

call returns
age_next_year(47) 48
In [23]:
def age_next_year(age):
    return age + "1"
In [24]:
try_it(age_next_year, 47)
Out[24]:

age_next_year(47) raised TypeError: "unsupported operand type(s) for +: 'int' and 'str'"

What it usually means: a value of the wrong type was used, such as adding text to a number, or calling with the wrong number of inputs. Module 2, section 3, shows how to read an error message (open).

In [25]:
check_cases("Exercise 2.5", age_next_year, [(f"age_next_year({a})", (a,)) for a in [47, 18, 0, 99]], what="ages", hint="Read the last line of the error first.")
Out[25]:

Exercise 2.5: not right yet. 0 of 4 ages are right. The first one that is not: age_next_year(47). Your code gave "TypeError: unsupported operand type(s) for +: 'int' and 'str'". Read the last line of the error first.

Still stuck after ten minutes? The solution and why it works are on the companion ↗.

If the check is red: common causes for Exercise 2.5
  • TypeError: the function still adds the text "1". Remove the quotes.
  • '471': the age was turned into text and "1" joined to it. Add the number 1 to the number instead.
In [26]:
course.quizzes_at("2.3")

Next: Collections, in 20_collections.ipynb.