Chrysolites Tech Academy

Programming Foundations: Python, Algorithms, Kotlin and Excel · Course book

Chapter 1: The Building Blocks of a Python Program

Pairs with Lesson 1: Python From the Ground Up

Python is often the first programming language people learn, and for a good reason: its code reads almost like careful English. This chapter sets out the handful of ideas that every Python program is built from, namely values, names, decisions, repetition, functions and error handling, and shows how they fit together in one small, complete program.

Values, types and collections

A program works with values: the number 42, the text "hello", the answer True. To use a value more than once you give it a name, which programmers call a variable. In Python you create a variable simply by assigning to it with a single equals sign.

bill = 84.00
people = 4
host = "Amara"
paid = False

Read the equals sign as "now refers to", not "is equal to". The line people = 4 does not state a fact about the world; it attaches the label people to the value 4. Later you can attach the same label to a different value, and the old one is simply forgotten.

Every value has a type, and the type decides what you are allowed to do with it. You can divide one number by another, but dividing a piece of text by a number makes no sense, and Python will stop and tell you so. Table 1.1 lists the types you will meet first.

TypePython nameExampleTypical use
Whole numberint4Counting things
Decimal numberfloat84.00Measurements and money estimates
Textstr"Amara"Names, messages, anything typed
Truth valueboolTrueAnswers to yes-or-no questions
Ordered collectionlist[3, 5, 8]Many values kept in order
Labelled collectiondict{"Amara": 24.15}Looking a value up by its key

One detail catches almost every beginner. Anything a person types at the keyboard arrives as text, even if it looks like a number. The text "4" and the number 4 are different values, so you convert with int("4") or float("84.00") before doing arithmetic. Going the other way, str(4) turns a number into text so it can be joined to a message.

Naming habit: choose names that say what the value means. price_per_person takes longer to type than p, but you will read your code far more often than you write it.

Lists and dictionaries

Real programs rarely deal with one value at a time. A list keeps many values in a fixed order, written between square brackets. Each position has a number called an index, and counting starts at zero, not one.

"Amara""Ben""Chidi""Dele" 0123 -4-3-2-1 index counted from the frontindex counted from the back
Figure 1.1 — A list called guests. The first item is at index 0, so a list of four items ends at index 3. Negative indexes count backwards from the end.

With the list in Figure 1.1, guests[0] is "Amara" and guests[-1] is "Dele". The function len(guests) gives 4, the number of items. Lists can grow: guests.append("Efe") adds a fifth name at the end, and it takes index 4.

A dictionary stores pairs. Instead of asking "what is at position 2?", you ask "what belongs to this key?". A dictionary of amounts owed might map each name to a number, so owed["Ben"] returns Ben's share directly. Use a list when order matters and a dictionary when you need to look things up by name.

Decisions and repetition

Decisions with if

A program becomes useful when it can react. An if statement runs a block of code only when a condition is true. Conditions are built from comparisons: == tests for equality (two equals signs, because one already means assignment), != means not equal, and <, >, <= and >= compare sizes.

if people <= 0:
    print("There must be at least one person.")
elif people == 1:
    print("No need to split the bill.")
else:
    print("Splitting between", people, "people.")

Python checks each condition from the top and runs the first block that matches, then skips the rest. Notice the colon at the end of each condition and the indentation beneath it. In Python the indentation is not decoration: the four spaces are how the language knows which lines belong to the block. Mixing up the indentation changes what the program does.

Conditions can be combined with and, or and not. The test people > 1 and bill > 0 is true only when both parts are true, while or needs just one of them.

Repetition with loops

Computers earn their keep by repeating work without getting bored. A for loop takes each item from a collection in turn and runs the same block for it.

total = 0
for amount in [30, 24, 18, 12]:
    total = total + amount
print(total)

Follow the loop by hand. The variable total starts at 0. After the first pass it is 30, after the second 54, after the third 72 and after the fourth 84, which is what gets printed. This pattern, starting with an empty total and adding to it on each pass, is called an accumulator and it appears in programs of every size.

When you want to repeat a fixed number of times, range supplies the numbers: for i in range(3) runs three times with i equal to 0, 1 and 2. A while loop is the other kind of repetition. It keeps going for as long as a condition stays true, which suits situations where you cannot know the number of passes in advance, such as asking a question until the answer is acceptable. The danger is a condition that never becomes false; then the loop runs forever and you must stop the program yourself.

Functions: naming a piece of work

As a program grows, the same steps start to appear in several places. A function wraps those steps up, gives them a name and lets you run them whenever you like. Values go in through parameters and a result comes out through return.

def share(bill, tip_percent, people):
    tip = bill * tip_percent / 100
    return (bill + tip) / people

print(share(84.00, 15, 4))

Work it through with the numbers shown. The tip is 84.00 × 15 ÷ 100 = 12.60. The bill plus tip is 96.60. Divided between 4 people, each share is 24.15, and that is the value the function hands back.

Functions pay off in three ways. They remove repetition, because the calculation is written once. They make programs readable, because share(bill, 15, people) explains itself. And they make mistakes easier to find, because each function can be tested on its own with numbers whose answers you already know. When a file gathers many useful functions, another file can borrow them with an import line, which is how Python programs are split into manageable modules.

print versus return: print shows a value to the person at the screen. return hands a value back to the rest of the program. A function that only prints its answer cannot be used in a later calculation.

Defensive programming

Everything so far assumes that people type sensible things. They do not. Someone will enter "four" instead of 4, or say that zero people are sharing the bill. The first makes int() fail, and the second causes a division by zero. In both cases Python raises an exception, and unless your code deals with it the program stops with an error message.

Defensive programming means expecting those problems. A try block lets you attempt something risky, and the matching except block says what to do if it goes wrong.

try:
    people = int(input("How many people? "))
except ValueError:
    print("Please type a whole number, such as 4.")
    people = 1

Table 1.2 lists the errors a beginner sees most often. Learning to read them calmly is a skill in itself: the last line of an error message names the type of problem, and the lines above it point to where it happened.

Error nameWhat caused itExample that triggers it
SyntaxErrorThe code breaks Python's grammarLeaving out the colon after if
NameErrorUsing a name that was never assignedTyping totl instead of total
TypeErrorMixing types that do not work together"4" + 4
ValueErrorRight type, unusable valueint("four")
IndexErrorAsking for a position that is not thereguests[4] on a list of four
ZeroDivisionErrorDividing by zero96.60 / 0

Checking values before using them is just as important as catching exceptions. A simple if people < 1 test in front of the division turns a crash into a helpful message.

Putting it together

Here is one short program that uses every idea in this chapter: variables, a list, a dictionary, a loop, a decision, a function and a guard against bad input.

def share(bill, tip_percent, people):
    if people < 1:
        return 0
    tip = bill * tip_percent / 100
    return (bill + tip) / people

guests = ["Amara", "Ben", "Chidi", "Dele"]
owed = {}
for name in guests:
    owed[name] = share(84.00, 15, len(guests))

print(owed["Chidi"])

The loop runs four times, once for each guest, and stores 24.15 against every name. The last line looks up Chidi's amount and prints it. Small as it is, the program has the same shape as much larger ones: gather the data, process it with functions, and report the result.

When you read someone else's code, look for these same parts. Ask which names hold the data, where the decisions are made, what is being repeated, and which functions do the real work. Almost any Python program, however long, will answer those four questions.

Check your understanding

  • What is the difference between "12" and 12, and how do you turn the first into the second?
  • A list has six items. What is the index of the last one? (Answer: 5, or -1 when counting from the back.)
  • A bill of 60.00 has a 10 percent tip and is shared by 3 people. What does share(60.00, 10, 3) return? (Answer: the tip is 6.00, the total is 66.00, and each share is 22.00.)
  • Why is == used in a condition instead of =?
  • Which error would int("ten") raise, and how would you stop it from ending the program?

Install Chrysolites Tech Academy

Android / Chrome / Edge: open the browser menu and choose Install app or Add to Home screen.

iPhone / iPad (Safari): tap the Share button, then Add to Home Screen.