Programming 1
Lecture 2: Notes

Some of the material from this week's lecture is covered in these sections of Think Python:

Here are more notes about topics we discussed.

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.

In this course, we will use the standard implementation of Python (CPython). It is something between a interpreter and a compiler – it has some aspects of both.

Python is relatively flexible and powerful, however (at least in its standard implementation) 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").

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')

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

chained comparisons

Python allows us to chain several comparisons together (as is common in mathematical writing):

>>> 3 < 5 < 10 < 20
True

The expression above has exactly the same meaning as

>>> 3 < 5 and 5 < 10 and 10 < 20
True

Equality comparisons can also be chained:

>>> 8 == 8 == 8
True
>>> 8 == 8 == 9
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)

'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
$

break

The 'break' statement will exit any kind of loop immediately. For example:

n = 1

while n <= 100:
    print(n)
    if n == 8:
        break
    n += 1

produces the output

$ py hello.py
1
2
3
4
5
6
7
8
$ 

When n is 8, the loop exits prematurely.

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