Week 1: Notes

Python

Python is a popular 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, however (at least in its standard implementation called CPython) it's not generally as efficient as languages such as C or C++. So it's not typically used for programming tasks where efficiency is a very important concern.

Syntactically, Python is quite different from languages such as C, C++, Java, or C#, which all have C-like syntax (and are sometimes called "curly brace languages").

installing Python

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

Linux

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.10.7" (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.10.7" (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.10.7-amd64.exe from python.org?" Click Run.

You'll now see a window "Install Python 3.10.7 (64-bit)". In this window, be sure to check the box "Add Python 3.10 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.

using the command line

You should learn the following commands for looking at files in directories on the command line, and for moving between directories:

Linux or macOS

cd: change to a new directory

ls: list all files in the current directory

pwd: print the name of the working directory (i.e. the current directory)

cat: print the contents of a file

Windows

cd: change to a new directory, or (with no arguments) print the name of the current directory

dir: list all files in the current directory

type: print the contents of a file

running Python from the command line

From a terminal window, type "python3" (on Linux or macOS) or "python" (on Windows). if your Python installation is successful, then running Python should result in output that looks something like this:

Python 3.10.6 (main, Aug 10 2022, 11:40:04) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

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. If you're not sure what to use, I 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.

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

Python also has boolean operators that can combine boolean values:

For example:

>>> True or False
True
>>> True and False
False
>>> not True
False
>>> not False
True

We often use these boolean operators to combine comparisons:

>>> 3 < 5 and 10 < 20
True
>>> not 10 <= 50
False

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.

variables and assignment operators

In Python we may assign any type of value to a variable:

>>> x = 17
>>> y = 'mountain'
>>> z = 18.223
>>> x
17
>>> y
'mountain'
>>> z
18.223

Note that variable names are written without quotation marks.

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

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".

In fact, this is so common that Python has special assignment operators for this purpose:

For example:

>>> x = 55
>>> x += 1
>>> x
56
>>> y = 100
>>> y *= 20
>>> y
2000

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:

d = input('Enter temperature: ')
print('The temperature is', d, 'degrees')

converting between integers and strings

In Python, an integer and a string are not the same:

>>> 52 == '52'
False

The int() function can convert a string of digits to an integer:

>>> int('52')
52

Conversely, the str() function will convert an integer to a string of digits:

>>> str(52)
'52'

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
$

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 -= 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 += n
    n -= 1

print('The sum is', sum)

Let's try it:

$ py hello.py
Enter n: 10
The sum is 55
$

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 += i

print('The sum is', sum)

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