Chrysolites Tech Academy

Introduction to Computer Science: Harvard CS50 · Course book

Chapter 7: A Higher-Level Language

Pairs with Lesson 7: Python

After several weeks of C, with its semicolons, types, pointers and manual memory management, Python feels almost like writing pseudocode. It is a higher-level language: it handles many details automatically, so programs are shorter and quicker to write. This chapter translates the ideas of the previous chapters into Python, shows the conveniences it adds, such as lists that grow by themselves and dictionaries built in, and explains the trade-off involved, because that convenience is not free.

From C to Python

The first difference is the greeting program. In C it needs a header, a main function and braces. In Python it is one line:

print("hello, world")

Python drops much of C's punctuation. There are no semicolons at the ends of lines and no braces around blocks; instead, indentation marks which lines belong together, and it is required, not optional. Variables are created simply by assigning to them, without declaring a type, because Python works out the type from the value. Table 7.1 compares common constructs.

IdeaCPython
Create a variableint counter = 0;counter = 0
Add onecounter++;counter += 1
Conditionif (x < y) { … } else { … }if x < y: … else: … (blocks set by indentation)
Combine conditions&& and ||and, or
Loop a fixed number of timesfor (int i = 0; i < 3; i++)for i in range(3):
Loop foreverwhile (true)while True:
Print with a valueprintf("hello, %s\n", name);print(f"hello, {name}")
Get text from the userget_string("Name: ") (teaching library)input("Name: ")

The f before a string makes it a format string: anything inside curly braces is replaced by its value, so print(f"hello, {name}") does what C's format codes do, more readably.

The loop for i in range(3) gives i the values 0, 1 and 2, exactly like the C for loop. More generally, a Python for loop goes through the items of any collection: for letter in "cat" runs three times, with letter equal to "c", "a" and "t" in turn. There is no need to manage an index and no risk of running past the end.

Interpreted, not compiled

A C program is compiled once into machine code and then run. A Python program is usually run by an interpreter, a program that reads your source code and carries out each instruction as it goes. You type python hello.py and the program runs at once, with no separate compiling step.

C hello.ccompilermachine code runs Python hello.py interpreterreads each line and carries it out Compiling takes a step up front but runs faster; interpreting starts at once but does more work while running.
Figure 7.1 — Two ways to run a program. C is translated in advance; Python is read and carried out while it runs.

The interpreter does more work as the program runs: it checks types, manages memory and translates instructions on the fly. So the same task usually runs more slowly in Python than in C, sometimes many times more slowly. In return, programs are written far faster. In one classic exercise, a spell checker that loads a dictionary of over 100,000 words into a hash table takes many dozens of lines of careful C, with structs, pointers and malloc. In Python the core can be a handful of lines using a built-in set. For most programs, the programmer's time is worth more than the computer's, which is why higher-level languages are so popular.

Python also removes some of C's dangers. Integers grow as large as needed, so there is no overflow: 2 ** 100, two to the power 100, prints exactly as 1267650600228229401496703205376. Memory is freed automatically when it is no longer used. Floating-point imprecision remains, though, because it comes from storing fractions in binary: 0.1 + 0.2 prints 0.30000000000000004.

Built-in data structures

Python provides the structures of Chapter 5 ready-made, so you can use them without building them.

  • A list, written with square brackets such as scores = [72, 73, 33], is an array that resizes itself. scores.append(95) adds an item, len(scores) gives the count, and sum(scores) / len(scores) the average, here (72 + 73 + 33 + 95) ÷ 4 = 68.25.
  • A tuple, written with round brackets such as (51.5, −0.1), is like a list but cannot be changed, which suits fixed pairs such as coordinates.
  • A dictionary, written with braces such as {"Ada": "555-0100", "Grace": "555-0199"}, maps keys to values, implemented as a hash table. Looking up phone["Ada"] is nearly instant however many entries there are.
  • A set holds unique values and answers "is this in the collection?" quickly, ideal for a dictionary of correctly spelled words.

Strings are richer too. Comparing two strings with == compares their characters, as people expect, and methods such as s.upper(), s.lower() and s.strip() return changed copies. Python strings cannot be changed in place, so these methods always produce new strings.

Batteries included. Python's large standard library, and the many more packages written by others, mean that common tasks such as reading spreadsheets, making web requests or processing images are often a single import away.

Writing in a Python style

Because Python does so much for you, idiomatic Python code often looks quite different from a line-by-line translation of C. Experienced programmers call this style "Pythonic". A few features account for most of the difference.

Multiplying strings. Printing a row of four hashes needs a loop in C. In Python, print("#" * 4) does it, because multiplying a string by a number repeats it. A right-aligned staircase of height 3 becomes a short loop:

for i in range(1, 4):
    print(" " * (3 - i) + "#" * i)

On the first pass i is 1, so the line has 2 spaces and 1 hash; on the second, 1 space and 2 hashes; on the third, no spaces and 3 hashes.

Slicing. Square brackets with a colon take part of a list or string. If word is "computer", then word[0:4] is "comp", the characters at positions 0 to 3; word[4:] is "uter", everything from position 4; and word[-1] is "r", the last character, since negative indexes count from the end. Slicing never runs past the end of a list, so it is a safe way to take "up to" a number of items.

Comprehensions. A list comprehension builds a new list from an old one in a single line. [n * n for n in range(5)] produces [0, 1, 4, 9, 16], and [w.upper() for w in words if len(w) > 3] keeps only the words longer than three letters and capitalises them.

Counting with a dictionary. Counting how often each word appears in a text is a classic task. With a dictionary it takes a few lines: for each word, if it is already a key, add one to its value, otherwise set its value to 1. For the words "to be or not to be", the result is {"to": 2, "be": 2, "or": 1, "not": 1}. The same task in C would need a hash table built by hand.

These features make programs shorter, but the underlying ideas are unchanged. A list is still an array that is copied to a larger block when it fills up; a dictionary is still a hash table with buckets; a slice still creates a new copy in memory. Knowing what happens underneath, from the earlier chapters, is what lets you predict which Python code will be fast and which will be slow.

Functions, errors and programs

Functions are defined with def:

def square(n):
    return n * n

def main():
    x = int(input("x: "))
    print(f"{x} squared is {square(x)}")

if __name__ == "__main__":
    main()

Two details deserve explanation. First, input always returns text, so int(input(...)) converts it to a number. If the user types "cat", the conversion fails and Python raises an exception, an error that stops the program unless it is caught. A try block lets you attempt the conversion and an except block says what to do on failure, such as asking again. Second, the final two lines call main only when the file is run directly, not when another file imports it to reuse its functions. Python reads a file from top to bottom, so defining functions first and calling main at the end avoids using a function before it exists.

Python also allows default values for parameters. def greet(name="world") can be called as greet() or greet("Ada"), giving a fallback when no argument is supplied.

Command-line arguments are available through the sys module, as the list sys.argv, which plays the role of C's argv. sys.exit(1) ends the program with an exit code. Files are opened with open, and the with statement closes them automatically:

with open("names.txt") as file:
    for line in file:
        print(line.strip())

That loop reads the file one line at a time, removes the line break at the end of each, and prints it, all without a single pointer or call to free.

Check your understanding

  • Give three ways in which Python's syntax differs from C's.
  • What values does i take in for i in range(4)? (Answer: 0, 1, 2 and 3.)
  • What does print(f"{3 * 4} items") print? (Answer: 12 items.)
  • Why does the same task usually run more slowly in Python than in C?
  • Why can Python print 2 ** 100 exactly when a C int cannot hold it?
  • For scores = [80, 90, 70], what is sum(scores) / len(scores)? (Answer: 80.0.)
  • What happens when int("cat") is run, and how can a program recover from it?

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.