Week 1: Notes

Python

Python is a general-purpose programming language. It is a relatively high-level language (for example, much higher-level than C). The first version of Python appeared in 1990, so it's now about 30 years old. It was originally a simple language, though it has grown more complex over time. Still, the core of the language still feels simple, and in this course we will mostly study that.

Python is relatively flexible and powerful. It's also extremely widely used. According to GitHub, Python has been the second most popular language (after JavaScript) for the last several years.

However, Python is quite a bit less efficient than languages such as C or C++ (at least in its standard implementation called CPython). So it's not typically used for programming tasks where efficiency is an important concern. Still, it remains a very practical and useful language.

installing Python

To install the Python interpreter on your computer, follow these steps:

Linux

You'll probably find that Python is installed by default. If not, run your system's package manager. (On Ubuntu or Debian, I recommend running Synaptic). Find the package for Python 3. On many systems (e.g. Ubuntu) this will be called 'python3'. Install it.

macOS 

In a web browser, go to the Python download page. Click the button "Download Python 3.11.5" (it may have a larger number if a newer version is available). When the installer finishes downloading, run it, and accept all the installation defaults.

Windows

In a web browser, go to the Python download page. Click the button "Download Python 3.11.5" (it may have a larger number if a newer version is available). You'll see a message "What do you want to do with python-3.11.5-amd64.exe from python.org?" Click Run.

You'll now see a window "Install Python 3.11.5 (64-bit)". In this window, be sure to check the box "Add Python 3.11 to PATH". Now click "Install Now". You'll see a message "Do you want to allow this app to make changes to your device?" Click Yes.

opening a terminal window

Linux

On many distributions, you can do this by pressing the Super key, then typing "terminal".

macOS

Press Command + Space, type "terminal", then press Enter.

Windows

Press the Windows key, type "command", then press Enter.

running Python from the command line

On all the systems above, if your Python installation is successful, then running it should result in output that looks something like this:

$ python3
Python 3.11.4 (main, Jun  9 2023, 07:59:55) [GCC 12.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

The prompt ">>>" above indicates that you're in Python's interactive interpreter, otherwise known as a REPL (= read-eval-print loop). In the interpreter you can enter expressions to be evaluated:

>>> 200 + 300
500
>>> 200 * 300
60000

On some systems you may be able to launch Python by typing just "python" instead of "python3".

int and float

The first two Python data types we'll learn are

We can use the following arithmetic operators with these numeric types:

Note that in Python integers may be arbitrarily large:

>>> 2 ** 100
1267650600228229401496703205376
>>> 2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

By contrast, floating-point numbers are stored in a fixed amount of memory, so they may only hold a certain number of digits:

>>> 2.0 ** 100
1.2676506002282294e+30

Above, e+30 means "times 1030". Notice that this floating-point number holds only the first 17 digits of the value of 2100 that we printed as an integer above.

The possible range of floating-point values in Python is large but not infinite:

>>> 2.0 ** 1000
1.0715086071862673e+301

>>> 2.0 ** 10000
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: (34, 'Numerical result out of range')

The // operator divides two integers, and rounds the result downward to the nearest integer:

>>> 20 // 6
3

The % operator computes the modulus of two integers, which is the remainder that is left over after integer division:

>>> 20 % 6
2

Notice that 20 = 3 * 6 + 2, i.e. 20 = (20 // 6) * 6 + 2. We can generalize this: for any integers a and b,

a = (a // b) * b + (a % b)

If the // operator produces a negative quotient, then in Python the result will also be rounded downward, i.e. toward -∞:

>>> -20 / 7
-2.857142857142857
>>> -20 // 7
-3
>>> -20 % 7
1

Notice that -20 = -3 * 7 + 1, so once again the formula a = (a // b) * b + (a % b) holds.

Also notice that if b > 0, then (a % b) will always produce an integer in the range 0 .. (b – 1), for any integer a (including negative values). This is a useful property.

(In some other programming languages, integer division works a bit differently: it rounds toward zero, so that e.g. -20 divided by 7 produces -2. In these languages, (a % b) might be negative even if b is positive. However, in my opinion the behavior is Python is more mathematically natural and is more convenient.)

By the way, when we write numeric constants in Python, we can include underscores anywhere we like. This can make them more readable:

>>> 1_000_000_000 + 100_000
1000100000

bool

In Python, the type bool represents a boolean value, which is either True or False. Those constants are built into the language:

>>> True
True
>>> False
False

Python includes comparison operators that can compare numbers (or other kinds of values):

Each of these operators produces a boolean value:

>>> 4 < 5
True
>>> 5 < 2
False
>>> 8 == 8
True
>>> 8 != 9
True

Unlike most other languages, Python includes chained comparisons, which allow us to write several comparisons inside a single expression:

>>> 2 < 5 < 10
True
>>> 2 < 5 < 3
False
>>> 2 != 5 != 3
True

Like in mathematics, "2 < 5 < 10" means that 2 < 5 and also 5 < 10.

string

A string is a sequence of characters, i.e. a piece of text. In Python, we may write strings enclosed in either single or double quotes:

>>> 'potato'
'potato'
>>> "grapefruit"
'grapefruit'

Typically we write strings using single quotes, however double quotes are convenient when we want to write a string that contains single quotes inside it:

>>> "she didn't say why"
"she didn't say why"

Note that some of the operators we saw above will work on strings. The + operator concatenates two strings:

>>> 'pizza' + 'pie'
'pizzapie'

The * operator concatenates multiples copies of a string together:

>>> 3 * 'orange'
'orangeorangeorange'
>>> 'xyz' * 10
'xyzxyzxyzxyzxyzxyzxyzxyzxyzxyz'

The comparison operators we saw above will compare strings alphabetically:

>>> 'house' < 'sky'
True
>>> 'xyzzy' == 'xyzzy'
True

data types: summary

Here are the built-in data types we're learned so far:

These will be adequate for writing lots of programs. Later we'll see more built-in data types, and will even learn how to construct our own types.

type conversions

Each type we've seen has an associated type conversion function:

In particular, in our programs we will often convert strings to integers:

>>> int('52')
52

using an IDE

For writing Python programs, you'll probably want to use an IDE (integrated development environment) rather than a plain text editor. Many different IDEs are available. I generally recommend Visual Studio Code, which is open source, runs on any major platform (i.e. operating system), and supports many different programming languages including Python.

Note that (confusingly) Visual Studio Code is not the same program as Visual Studio, which is an older closed-source IDE that runs only on Windows. When you are reading documentation online, be sure that it's for the program you are actually using. (I will not discuss Visual Studio in this class.)

In Visual Studio Code, be sure to install the Python and Pylance extensions. They will allow the IDE to understand and report errors in your Python code as you type it.

I generally recommend that in Visual Studio Code you should open a folder, where you can have one or more source files. To do this, start Visual Studio Code, then choose File / Open Folder… from the menu. The next time you start Visual Studio Code, the previously opened folder will be opened automatically.

Once you have opened a folder, you can create a new source file in it. To do this, right click in the left pane and choose "New File…" from the context menu, or click the small New File icon at the top (it looks like a document with a + sign). By convention, Python source files always have the extension ".py".

For example, create a file "hello.py" and enter this text in it:

print('hello, world')

This is a 1-line Python program that prints a string. Save the file. Now let's run it. As one possibility, you can click the Run Python File icon, which looks like a small triangle at the upper-right of the editor window. When you do that, the program will run in the Terminal pane at the bottom of the Visual Studio Code window.

However, I generally prefer to run Python programs in an external terminal window. To do this, you can type Ctrl+Shift+C (on Linux or Windows) or Command+Shift+C (on macOS) to open a terminal window whose current directory will be the same folder that you are viewing in Visual Studio Code.

Once you've opened an external terminal, you can run Python and give it the name of your source file:

$ python hello.py
hello, world
$ 

the 'input' and 'print' functions

Almost every program will read input and produce output. In Python, we will use the following two built-in functions for this purpose:

For example:

print('What is your name?')
name = input()
print('hello', name)

Let's run it:

$ py hello.py 
What is your name?
fred
hello fred
$

Note that the input() function can take an optional parameter indicating a prompt to print before receiving input. For example, we could rewrite the program above like this:

name = input('What is your name? ')
print('hello', name)

Then the user will enter the the input on the same line where the prompt was printed:

$ py hello.py
What is your name? joe
hello joe
$ 

As described above, input() returns a string. Often we will call int() to convert the result of input() to an integer:

x = int(input('Enter x: '))
print(x * x)

$ py hello.py
Enter x: 111
12321
$

variables

In the examples in the previous section, 'name' and 'x' are variables. In Python we may assign any type of value to a variable:

>>> x = 17
>>> y = 'mountain'
>>> x
17
>>> y
'mountain'

Note that variable names are written without quotation marks.

As a program runs, the values of variables may change over time. The program

x = 100
print(x + 2)
x = 200
print(x + 2)

produces the output

102
202

As we can see in the examples above, the assignment operator '=' assigns a new value to a variable. Be sure to distinguish this from the comparison operator '==', which test whether two values are the same.

We will often give a variable a new value that is constructed from its old value:

>>> x = 77
>>> x = x + 2
>>> x
79

The statement 'x = x + 2' means "the new value of x is the old value of x plus 2". (By contrast, in mathematics "x = x + 2" is an equation with no solution.)

if, else, elif

We can use the 'if' and 'else' statements to execute code conditionally:

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

if x > 1000:
    print("That's a big number.")
else:
    print("It's not so big.")
    print("Try to think of something bigger.")

The 'if' statement takes an Boolean condition. If the condition is true, it executes the lines after 'if'; otherwise, it runs the lines after 'else'. Notice that either of these blocks of lines can contain one or more lines of code. Also notice that Python uses indentation (blank charactes at the beginning of a line) to recognize these blocks.

An 'if' statement need not have an 'else' clause. If it doesn't, and the condition is false, it will do nothing.

An 'if' statement may include one or more 'elif' clauses. 'elif' means 'else if'. For example:

if x > 1000:
    print("That's a big number.")
elif x > 100:
    print("It's kind of big.")
elif x > 0:
    print("It's not very big, but at least it's positive.")
elif x == 0:
    print("It's zero.")
else:
    print("It's negative.")

while loops

A 'while' loop executes a nested block of statements (the body of the loop) as long as a condition is true. For example:

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

while x > 0:
    print(x)
    x = x - 1

print('Liftoff!')

Let's run it:

$ py count.py
Enter x: 10
10
9
8
7
6
5
4
3
2
1
Liftoff!
$

Here's a program that computes the sum of the integers from 1 to N, for any N:

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

sum = 0

while n > 0:
    sum = sum + n
    n = n - 1

print('The sum is', sum)

Let's try it:

$ py sum.py
Enter n: 10
The sum is 55
$
print('The sum is', sum)

Finally, here's a program to remove all zeroes at the end of a decimal integer:

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

while a % 10 == 0:
    a = a // 10

print(a)

for loops

The 'for' statement loops over a series of values. For example, it can loop over a range of integers:

for i in range(1, 5):
    print(i)

produces

$ py hello.py
1
2
3
4
$

Notice that the program printed the numbers 1 through 4, but not 5. That's because in Python range(a, b) produces a series of values from a up to but not including b. That may seem surprising. Later, you may see why this makes sense in some contexts. For now, this is something you just need to get used to.

Using 'for', we can compute the sum of the integers from 1 to N a bit more easily:

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

sum = 0

for i in range(1, n + 1):
    sum = sum + i

print('The sum is', sum)

Actually 'for' can loop over many other kinds of sequences. For example, it can loop over all characters in a string:

for c in 'hello':
    print(c)

This produces the output

$ py hello.py
h
e
l
l
o
$

comments

In any line in a Python program, any characters after a '#' are a comment and are ignored. Comments are useful for adding explanatory text to programs:

x = int(input())
if x % 2 == 0:  # x is even
    x = x // 2
else:           # x is odd
    x = 3 * x + 1

Note that in Visual Studio Code you can press Ctrl+/ to comment or uncomment the currently selected block of code.