Programming 1, 2019-20
Lecture 3: Notes

Many of the topics we discussed today are covered in these sections of Introducing Python:

Here are some additional notes.

Generating Fibonacci numbers

The sequence of Fibonacci numbers Fi is defined as follows: F1 = 1, F2 = 1, and Fi = Fi-1 + Fi-2 for all i ≥ 3. So the sequence is

1, 1, 2, 3, 5, 8, 13, 21, …

Let's write a program that reads an integer N and writes the first N numbers in the Fibonacci sequence.

To accomplish this, we use two integer variables a and b to store the next two numbers that we will output:

n = int(input('Enter n: '))

a = 1
b = 1

for i in range(n):
  print(a)
  c = a + b
  a = b
  b = c

On each loop iteration, we first output a. We then compute c, which is the Fibonacci number that comes after a and b. Then, since we have already output a, we shift b into a and then c into b.

The key to solving a problem like this is figuring out what state we must remember between loop iterations – in this case, the variables a and b.

In Python, we can alternatively write the code above using multiple assignment. Instead of

c = a + b
a = b
b = c

we can write

a, b = b, a + b

This first computes the values b and (a + b), then assigns these new values to a and b respectively.

Unicode

Computers generally store text using a coded character set, which assigns a unique number called a code point to each character. Two character sets are used in virtually all software systems today:

Python 3 is fully compatible with Unicode. You can write

s = 'Řehoř'

or

s = ''

and these strings will work just like strings of ASCII characters.

ord() and chr()

Python includes two functions that can map between characters and their integer code points.

Given a Unicode character c, ord(c) returns its code point. For example, ord('A') is 65, and ord('B') is 66. ord('ř') is 345 (a value outside the ASCII range).

chr() works inversely: it maps a code point to a character. For example, ord(65) is 'A', and ord(345) is 'ř'.

These functions are sometimes useful when we wish to manipulate characters. For example, here is a program that reads a lowercase letter, and prints the next letter in the alphabet:

c = input('enter letter: ')
i = ord(c) - ord('a')
if 0 <= i < 26:
  i = (i + 1) % 26
  print('next letter is', chr(ord('a') + i))
else:
  print('not a lowercase letter')

The program uses ord() to convert a character (such as 'd') to a number (such as 3) representing its position in the lowercase alphabet. It then adds 1 (mod 26), and uses chr() to map the result back into a lowercase letter.