All Class PPT in One
All Class PPT in One
Intro
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Hello World
1
Values, Variables, Assignments
speed_limit = 50
robot_name = 'bob the rob'
my_height = 1.95
2
Print
print(50)
print(robot_name)
3
Types
type(50) # int
type(1.1) # float
type(robot_name) # str
4
Operations on Numbers
1 + 1 # addition
1 - 1 # subtraction
1 * 1 # multiplication
my_height / 2 # division
4 // 3 # division without remainder
4 % 3 # modulus
1 ** 2 # exponentiation
5
Operations on Strings
6
A Note on Quotation Marks
print('bob is a "robot"')
print("a 'robot' is bob")
7
Operator Precedence
x = 1 + 2 * 3
x = (1 + 2) * 3
x = 1+2 * 3 # whitespaces don't affect precedence
8
Expressions and Statements
1 + 2 # expression, value is 3
x = 1 + 2 # statement (assignment), no value
9
Debugging
10
Introduction to Programming
Functions
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Function Calls
type(42)
print('hello')
1
Type Conversion
int('42')
int(-3.9)
float('4.2')
float(42)
str(42)
2
Math Functions, Modules
import math
x = math.sin(0)
y = math.sqrt(2)
print(math.pi)
3
Composition
x = math.sin(3 * math.pi)
y = math.exp(math.log(x + 1))
4
Defining Functions
def make_some_sound():
print('da')
print('du')
5
Why Functions?
• Readability
• Maintainability
• Reusability
• Testability
6
Functions are Objects
print(make_some_sound)
type(make_some_sound)
import math
print(math)
7
Call Your Function
make_some_sound()
make_some_sound('huh')
8
Functions in Functions
def make_a_lot_of_sound():
make_some_sound()
make_some_sound()
9
Definition and Use
def make_a_lot_of_sound():
make_some_sound()
make_some_sound()
make_a_lot_of_sound()
10
Flow of Execution
11
Parameters and Arguments
def make_sound_twice(sound):
print(sound)
print(sound)
make_sound_twice('deh')
sound = 'doo'
make_sound_twice(sound)
make_sound_twice(42 + math.pi)
12
Keyword Arguments
• We can pass arguments with their name explicitly, which may increase
comprehensibility
• These are called keyword arguments
• We can mix arguments without and with keywords, keyword arguments have to be
passed after those without
f(1, 2)
f(1, exponent=2)
f(base=1, exponent=2)
13
Scope
add(1, 2)
print(a_plus_b) # NameError: name 'a_plus_b' is not defined
14
Return Values
x = math.cos(math.pi)
y = print('robbedibobby')
print(type(y))
z = make_sound_twice(y) # huh
15
Stack Diagrams
16
Turtle
import turtle
donatello = turtle.Turtle()
print(donatello)
turtle.mainloop()
17
Turtle Methods
donatello = turtle.Turtle()
donatello.forward(42) # or backward(24)
donatello.right(10) # or left(11)
donatello.penup() # or pendown()
turtle.mainloop()
18
Repetition
for i in range(4):
print('shoobidoo')
for i in range(4):
donatello.forward(100)
donatello.left(90)
19
Introduction to Programming
Functions - Exercises
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Exercises
def make_some_sound():
print('da')
print('du')
def make_a_lot_of_sound():
make_some_sound()
make_some_sound()
make_a_lot_of_sound()
1
Exercises
# program 1
def f(x):
y = x + 1
print(y)
f(1)
# program 2
def f(x):
y = x + 1
print(y)
f(1)
2
Exercises
def f(x):
y = x + 1
print(y)
y = 1
f(y)
print(y)
3
Exercises (cf. Think Python, Section 4.3)
• Write a function called square that takes a parameter named t, which is a turtle object. The
function should use the turtle to draw a square. Create a turtle object, and call square with that
turtle object as an argument.
• Add another parameter, named length, to square. Modify the body such that the length of the
sides is length, and then modify the function call to provide a second argument. Test your
program with a range of values for length.
• Make a copy of square and change the name to polygon. Add another parameter named n and
modify the body so it draws an n-sided regular polygon. Hint: The exterior angles of an n-sided
regular polygon are 360/n degrees.
• Write a function called circle that takes a turtle and a radius as parameters. The function should
draw an approximate circle by calling polygon with an appropriate length and number of sides.
Test your function with a range of values for the radius parameter. Hint: figure out the
circumference of the circle and make sure that length * n = circumference.
• Make a more general version of circle called arc that takes an additional parameter angle, which
determines what fraction of a circle to draw. angle is in units of degrees, so when angle=360, arc
should draw a complete circle. 4
Introduction to Programming
Functions - Exercises
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Exercises
def make_some_sound():
print('da')
print('du')
def make_a_lot_of_sound():
make_some_sound()
make_some_sound()
make_a_lot_of_sound()
1
Solution
def make_some_sound():
print('da')
print('du')
make_a_lot_of_sound()
def make_a_lot_of_sound():
make_some_sound()
make_some_sound()
2
Solution
• Calling a function when defining another function’s body can happen before the actual definition,
as the code inside the function’s body is not executed until it is actually called
def make_a_lot_of_sound():
make_some_sound()
make_some_sound()
def make_some_sound():
print('da')
print('du')
make_a_lot_of_sound()
3
Solution
print('da')
print('du')
print('da')
print('du')
4
Exercises
# program 1
def f(x):
y = x + 1
print(y)
f(1)
# program 2
def f(x):
y = x + 1
print(y)
f(1)
5
Solution
• Program 1 outputs 2
• y is a local variable, getting assigned the value 1 + 1, which is 2
# program 1
def f(x):
y = x + 1
print(y)
f(1)
6
Solution
# program 2
def f(x):
y = x + 1
print(y)
f(1)
7
Exercises
def f(x):
y = x + 1
print(y)
y = 1
f(y)
print(y)
8
Solution
def f(x):
y = x + 1
print(y)
y = 1
f(y)
print(y)
9
Exercises (cf. Think Python, Section 4.3)
• Write a function called square that takes a parameter named t, which is a turtle object. The
function should use the turtle to draw a square. Create a turtle object, and call square with that
turtle object as an argument.
• Add another parameter, named length, to square. Modify the body such that the length of the
sides is length, and then modify the function call to provide a second argument. Test your
program with a range of values for length.
• Make a copy of square and change the name to polygon. Add another parameter named n and
modify the body so it draws an n-sided regular polygon. Hint: The exterior angles of an n-sided
regular polygon are 360/n degrees.
• Write a function called circle that takes a turtle and a radius as parameters. The function should
draw an approximate circle by calling polygon with an appropriate length and number of sides.
Test your function with a range of values for the radius parameter. Hint: figure out the
circumference of the circle and make sure that length * n = circumference.
• Make a more general version of circle called arc that takes an additional parameter angle, which
determines what fraction of a circle to draw. angle is in units of degrees, so when angle=360, arc
should draw a complete circle. 10
Encapsulation
def square(t):
for i in range(4):
t.forward(100)
t.left(90)
square(donatello)
leonardo = turtle.Turtle()
square(leonardo)
11
Generalization
square(bob, 100)
12
Generalization
polygon(bob, 7, 70)
13
Keyword Arguments
14
Interface Design
import math
15
Interface Design
16
Refactoring
for i in range(n):
t.fd(step_length)
t.lt(step_angle)
17
Refactoring
18
Refactoring
• We now can use polyline for polygon, arc, and refactor circle
20
Introduction to Programming
Conditions, Recursion and Return Values
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Recap
1
Boolean Expressions
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
2
Logical Operators
a and b
n % 2 == 0 or n % 3 == 0
not x > 0
3
Conditional Execution
if x > 0:
print('x is positive')
4
Conditional Execution
if x % 2 == 0:
print('x is even')
else:
print('x is odd')
if x % 2 == 0:
print('x is even')
if not x % 2 == 0:
print('x is odd')
5
Chained Conditional Execution
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
6
Chained Conditional Execution
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
7
Nested Conditionals
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
8
Return Values
e = math.exp(1.0)
height = radius * math.sin(radians)
def area(radius):
a = math.pi * radius ** 2
return a
def absolute_value(x):
if x < 0:
return -x
else:
return x
9
Return Values
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
print(absolute_value(0))
10
Boolean Return Values
• We can use boolean return values to give logical tests readable names
if is_divisible(4, 2):
print('divisible')
11
Type Checking
• We can check the type of a variable with the built-in boolean function
isinstance(value, type)
x = 'hi'
if isinstance(x, str):
print('str')
if isinstance(x, int):
print('int')
if isinstance(x, float):
print('float')
if isinstance(x, bool):
print('bool')
12
Recursion
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
13
Infinite Recursion
def recurse():
recurse()
14
Recursive Sum
def sum(n):
# base case
if n == 1:
return 1
# inductive case
else:
return n + sum(n - 1)
15
Random
donatello = turtle.Turtle()
move(donatello, 100)
turtle.mainloop()
16
Introduction to Programming
Conditions, Recursion and Return Values - Exercises
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Exercises
• Write a compare function that takes two values, x and y, and returns 1 if x > y, 0
if x == y, and -1 if x < y.
• Write a function is between(x, y, z) that returns True if x ≤ y ≤ z or False
otherwise.
• Write a function that takes two points given by their coordinates x0, x1 and y0,
y1 as arguments, and returns the euclidean distance between them.
1
Exercises
2
Generative Processes
• Can you combine random numbers, conditions, recursion and turtle’s methods to
create generative art? See next slide for some ideas.
• https://docs.python.org/3/library/turtle.html
t = turtle.Turtle()
t.penup()
t.pendown()
t.pensize(size)
t.pencolor(r, g, b)
t.fillcolor(r, g, b)
t.begin_fill()
t.end_fill()
3
Generative Processes
4
Exercises
5
Introduction to Programming
Iteration
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data (starting next week)
1
While Loop
def countdown(n):
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
2
Break
• We can use the break statement to ’leave’ the loop at any time
• input(prompt) queries input from the user showing the prompt in the terminal,
and returns the string entered by the user
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')
3
Not exactly the same as break
line = ''
while line != 'done':
line = input('> ')
print(line)
print('Done!')
4
Factorial with While
• In contrast to recursion
def factorial(n):
fac = 1
while n > 0:
fac = fac * n
n = n - 1
return fac
5
Infinite While
while True:
print('still on')
6
Random Walk
import turtle
import random
t = turtle.Turtle()
steps = 100
while steps >= 0:
t.forward(random.randint(10, 50))
t.left(random.randint(-180, 180))
steps = steps - 1
turtle.mainloop()
7
Simulation
# initialize state
x = 0
y = 0
v_x = 0
v_y = 0
simulate = True
while simulate:
# sense some information
print(x, y)
# change or set our activation (e.g. velocity)
v_x = random.randint(0, 10)
v_y = random.randint(0, 10)
print('vehicle chose velocity: ' + str(v_x) + ', ' + str(v_y))
# update the state of the simulation
x = x + v_x
y = y + v_y
# until we don't want to simulate anymore
if x > 20:
simulate = False
8
Packages with pip
• We can install python packages with pip: In a terminal, write ’pip install
<packagename>’
• For example termcolor for printing colored strings: ’pip install termcolor’
• https://pypi.org/project/termcolor/
• We can import particular definitions from a module using from ... import ...
9
Implementing a Fibonacci Sequence
In this assignment, you will explore different methods to calculate the Fibonacci sequence, a
series of numbers where each number is the sum of the two preceding ones, usually starting
with 0 and 1. Your task is to implement the Fibonacci sequence using three different approaches
in Python:
Write a function fibonacci_while(n) that takes an integer n and returns the first n
numbers of the Fibonacci sequence using a while loop.
Write a function fibonacci_for(n) that achieves the same goal as above, but by using
a for loop.
3. Recursive Implementation:
Bonus Challenge:
Your program should generate a random integer between 1 and 100 (inclusive). Use
Python's random module for this purpose.
2. User Input:
The program should prompt the user to enter their guess. Ensure that the input is a
valid integer within the specified range.
3. Feedback Mechanism:
After each guess, the program should compare the user's guess to the generated
number and print:
"Too high" if the guess is higher than the number.
"Too low" if the guess is lower than the number.
"Correct! You guessed the number." if the guess is equal to the number.
The game should continue, prompting the user for a guess until they correctly guess
the number.
5. User Interface:
Make sure the user interface is clear and user-friendly. Provide instructions to the user
on how to play the game.
6. Error Handling:
Your program should gracefully handle any input errors without crashing.
Bonus Challenge:
Guess Count:
Enhance your program to count the number of guesses the user makes. Display this
count when the user correctly guesses the number.
Range Customization:
Allow the user to specify the range within which the random number is generated (e.g.,
1 to 50, or 1 to 200).
Introduction to Programming
Strings
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data
• Sequences, Strings
1
Overview
• Sequences
• A string is a sequence, indexing
• The length of a sequence
• Slices (subsequences)
• Traversal
• Searching
• Counting
• Strings
• The in operator for strings
• Strings are immutable
• String methods
• String comparison
2
A String is a Sequence
message = 'hello'
letter = message[0] # letter = 'h'
i = 0
letter = message[i + 1] # letter = 'e'
letter = message[2.5] # TypeError: string indices must be integers
3
Length
length = len(message)
last = message[length] # IndexError: string index out of range
last = message[length - 1] # last = 'o'
4
Negative Indices
5
Slicing
6
Slicing
7
Slicing
• An end index larger or equal to the start index yields an empty string
8
Slicing
9
Traversal
index = 0
while index < len(message):
letter = message[index]
print(letter)
index = index + 1
10
Traversal
11
Traversal
message_length = len(message)
for index in range(message_length):
letter = message[index]
print(letter)
12
Search
13
Count
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)
14
The in Operator
• in is a boolean operator that takes two strings and returns True if the first
appears as a substring in the second
15
Strings are Immutable
16
String Methods
17
String Comparison
18
Reading Data from Files
f = open("./traffic.txt")
for i in range(100):
line = f.readline()
print(line)
# we can do something with line
for line in f:
# we can do something with line
19
Reading Data from Files
• We have to provide absolute file paths, or relative to the current working directory
• Python’s operating system module os offers a method to get the current working
directory
import os
print(os.getcwd())
20
1 Palindrome
A palindrome is a word or sentence that reads the same forward and backward, e.g. ’never odd
or even’: https://en.wikipedia.org/wiki/Palindrome
• Write a function is_palindrome(some_string) that takes a string as argument, and that
returns a boolean indicating whether the given string is palindromic. Write the function
using (a) a for or while loop and (b) recursion.
• Bonus: Using slices and negative step sizes, there is a single line solution to this problem.
Can you find it?
2 Traffic Analytics
Download the traffic.txt file from the moodle page. It contains a toy dataset of traffic observa-
tions. Each observation is placed in a separate line. An observation looks like e.g.
06 >=>=======>=========
The first two characters indicate the hour of measurement, and the following characters
indicate the traffic measurement, ’=’ denoting an empty street segment, and ’>’ denoting a car.
• Write a function average_cars_at_hour(filepath, hour) that takes a filepath string
and a string indicating an hour as arguments, and that returns the average number of
measured cars at that hour.
• Write a function nr_of_empty_measurements(filepath) that takes a filepath string as
argument, and that returns the average number of measurements not containing any car.
• Write a function maximum_traffic(filepath) that takes a filepath string as argument,
and that returns the maximum number of cars present at any single measurement in the
dataset.
• Write a function nr_of_jams(filepath) that takes a filepath string as argument, and
that returns the number of jams present in the dataset measurements. A jam is defined
as at least three cars occupying consecutive street segments (i.e. '>>>' is a jam).
• Bonus: Can you write a function that finds the longest jam (i.e. sequence of consecutive
'>'s) present in the dataset?
1
Introduction to Programming
Lists
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data
• Sequences, Strings
• Lists
1
Overview
• A list is a sequence
• Filter, map, reduce
• Deleting elements
• Mutability, aliasing, cloning
• List arguments, modification vs. creation
• Addendum: Concurrent modification
• Addendum: Nested lists
2
A List is a Sequence
a_list = []
a_list = [1, 2]
a_list = [1, 2, 'bob']
a_list[2] # -> 'bob'
3
Lists are mutable
4
Traversing a list
a_list = [1, 2, 3]
for i in range(len(a_list):
print(a_list[i])
5
List operations
6
List methods
• Append, extend
• Sort, reverse
• Most list methods operate in-place, and return None
• https:
//docs.python.org/3/tutorial/datastructures.html#more-on-lists
7
List methods
• Append, extend
# adding an element
a_list = []
for i in range(5):
a_list.append(i + 1)
print(a_list)
# concatenating a list
a_list = [1, 2]
a_list.extend([3, 4])
print(a_list)
8
List methods
• Sort, reverse
string_list = ['bob', 'ana', 'tim', 'beate']
string_list.sort() # remember lexicographic ordering
print(string_list)
mixed_list = [1, 2, 'bob', 'tim']
# mixed_list.sort() # causes a type error
# -> TypeError: '<' not supported between instances of 'str' and 'int'
# reverse
a_list = [1, 2, 3, 'ana']
a_list.reverse()
print(a_list)
9
Filter, map, reduce
• Filter: Get all elements from a list that satisfy a given condition
• Map: Apply a function/operation to each element of a list
• Reduce: Combine the elements of a list to a single value, e.g. sum, max, average,
count, search, ...
10
Filter
• Filter: Get all elements from a list that satisfy a given condition
original_list = [1, 2, 3, 4, 5, 6]
filtered_list = []
for element in original_list:
# filter condition
if element < 4:
filtered_list.append(element)
print(filtered_list)
11
Map
12
Reduce
• Reduce: Combine the elements of a list to a single value, e.g. sum, max, average,
count, search, ...
original_list = [1, 2, 3]
reduced_value = 0
for element in original_list:
reduced_value += element
print(reduced_value)
13
Deleting elements
element = the_list.pop(index)
the_list.remove(element)
del the_list[index]
del the_list[start:end]
14
Lists and strings
15
Objects and values
16
Aliasing
a = [1, 2]
b = a
a is b # True
b[0] = 42 # a -> [42, 2], b -> [42, 2]
17
Aliasing and copying
a = [1, 2]
b = a[:]
a is b # False
b[0] = 42 # a -> [1, 2], b -> [42, 2]
18
Mutable objects and scope
def set_tail(x):
x = x[1:] # assigns new list to variable -> effect in local scope only
x = [1, 2]
set_tail(x)
# x -> [1, 2]
19
Mutable objects and scope
• If the list is created in current scope, changing elements only has a local effect
def set_tail(x):
x = x[1:] # assigns new list to variable -> effect in local scope only
x[0] = 0
# x -> [0]
x = [1, 2]
set_tail(x)
# x -> [1, 2]
20
Modify vs. create
t1 = [1, 2]
t2 = t1.append(3)
# t1 -> [1, 2, 3]
# t2 -> None
t3 = t1 + [4]
21
Modify vs. create
• Also for your own code: Always be clear whether you modify the list in place, or
create a new list
• When creating a new list in function scope, you may consider to return it to the
caller
def bad_tail(t):
t = t[1:]
# Works, but probably not as expected
# (i.e. does not change t outside the function)
def tail(t):
return t[1:]
• Iterating over a copy of the list to be modified may mitigate the problem
list_of_num = [1, 2, 3, 4, 5, 6]
for elem in list_of_num:
if elem == 3 or elem == 4:
list_of_num.remove(elem)
print(list_of_num) # -> [1, 2, 4, 5, 6]
list_of_num = [1, 2, 3, 4, 5, 6]
for elem in list_of_num[:]: # make a copy using [:] for iteration
if elem == 3 or elem == 4:
list_of_num.remove(elem) # remove from original list
print(list_of_num) # this works as expected: -> [1, 2, 5, 6]
24
Addendum: Concurrent modification
• Alternatively, create a new list to keep the (intermediate and final) results while
iterating over the original list
25
Addendum: Nested lists
26
1 Warm Up
• Write a function called nested_sum that takes a list of lists of integers and adds up the
elements from all of the nested lists. For example:
t = [[1, 2], [3], [4, 5, 6]]
nested_sum(t) # -> 21
• Write a function called middle that takes a list and returns a new list that contains all
but the first and last elements. For example:
t = [1, 2, 3, 4]
middle(t) # returns [2, 3]
• Write a function called chop that takes a list, modifies it by removing the first and last
elements, and returns None. For example:
t = [1, 2, 3, 4]
chop(t) # returns None
# t -> [2, 3]
• Write a function filter_list(a_list, n) that creates a new list containing all elements
from a_list that are smaller than n. For example:
a_list = [4, 6, 4]
filter_list(a_list, 5) # -> [6]
a_list = [3, 5, 1, 2]
filter_list(a_list, 3) # -> [1, 2]
2 Anagrams
• Two words are anagrams if you can rearrange the letters from one to spell the other.
Write a function called is_anagram that takes two strings and returns True if they are
anagrams.
is_anagram('elvis', 'lives') # -> True
is_anagram('roses', 'are trees') # -> False
3 Buffer
• Initialize a variable a_buffer to an empty list.
• Write a function process(a_buffer, x) that appends x to the a_buffer. If a_buffer
contains more than three elements, also remove its first element (i.e. the element at
index zero).
4 List arguments
What does the following program print? Why? Try to predict what the program does before
executing it. Also, step through this program using pythontutor.
1
def f(x):
x = x + [3]
def g(x):
x = x + [3]
return x
def h(x):
x[0] = 0
x = [1, 2]
f(x)
print(x)
x = g(x)
print(x)
h(x)
print(x)
5 Aliasing
What does the following program print? Why? Try to predict what the program does before
executing it. Also, step through this program using pythontutor.
def f(x):
x = x + [3]
def f2(x):
x.append(3)
x = [1, 2]
y = x
f(x)
print(x, y)
f2(x)
print(x, y)
y = x[:]
f2(x)
print(x, y)
2
Exercise: Building a Console Tic-Tac-Toe Game in Python
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data
• Sequences, Strings
• Lists
• Dictionaries
1
A dictionary is a mapping
d = {} # empty dictionary
d['one'] = 1
d['two'] = 2
print(d)
print(d['one']) # -> 1
2
Basic operations
print(d.keys())
for element in d.values():
print(element)
print(len(d))
key_is_present = 'one' in d
print(key_is_present) 3
Under the hood
print(hash('hello'))
print(hash([1, 2])) # -> TypeError: unhashable type: 'list'
4
Example: Histogram
6
1 Inventory
This exercise is based on: https://erlerobotics.gitbooks.io/erle-robotics-learning-python-gitbook-free/
content/lists/exercises_list_and_dictionaries.html
inventory = {
'gold': 5,
'pouch': ['ruby', 'emerald', 'diamond'],
'backpack': ['xylophone', 'book', 'bedroll','bread loaf']
}
• Add a key to inventory called ’pocket’. Set the value of ’pocket’ to be a list consisting of the strings
’seashell’, ’strange berry’, and ’lint’.
• Sort the items in the list stored under the ’backpack’ key.
• Remove ’bread loaf’ from the list of items stored under the ’backpack’ key.
• Add 2 to the number stored under the ’gold’ key.
Implement a function sort(dict) that sorts every value that is of type list for a given dictionary. Use sort(inventory)
to sort the inventory.
Implement a function to_stock that takes a pouch list (of strings) as an argument and returns a dictionary
mapping items (strings) to their number of occurrences.
pouch = ['ruby','emerald','ruby','diamond','diamond']
stock = to_stock(pouch)
# stock -> {'ruby': 2, 'emerald': 1, 'diamond': 2}
Create a dictionary called prices. Put these key-value pairs in your prices dictionary:
Write a function pouch_value(inventory_dict, prices_dict) returning an integer that indicates how much
you would make from selling the pouch of the given inventory, assuming the given prices.
2 Inversion
Given a dictionary that maps a number to a list of characters, implement a function that inverts this dictionary.
You can assume that each character only occurs once in the given dictionary values.
More difficult variant: Implement invert, assuming a character can appear more than once in the values.
1
3 Decode Cipher
Consider the cipher from the lecture (see code below). Implement a function decode(encoded_message, cipher)
to recover the original message.
import string
from random import shuffle
2
Introduction to Programming
Tuples and Files
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data
• Sequences, Strings
• Lists
• Dictionaries
1
Overview
• Tuples
• Tuple assignment
• As keys in dictionaries
• Gather, scatter
• Tuples as return values
• zip and enumerate
• Reading and writing files
• Pickle
2
Tuples
t = (1, 2, 'three')
t[1] # -> 2
t[1] = 'one'
# -> TypeError: 'tuple' object does not support item assignment
empty_tuple = tuple()
tuple_with_one_element = (1,)
3
Tuple assignment
a = 0
b = 1
a, b = b, a # tuple assignment: a -> 1, b -> 0
4
Tuples as dict keys
game_board = {}
for x in range(3):
for y in range(3):
game_board[(x, y)] = 0
5
Scatter
• We can scatter function arguments using the asterisk when calling a function
t = (1, 2, 3)
add(*t) # -> 6
add(t)
# -> TypeError: add() missing 2 required positional arguments: 'b' and 'c'
6
Scatter
• We can gather function arguments using the asterisk when defining a function
def add(*args):
arg = 0
for arg in args:
value += arg
return value
add(1, 2, 3) # -> 6
add(1, 2, 3, 4) # -> 10
7
Tuples as return values
x, y = swap('hi', 'there')
# x -> 'there, y -> 'hi'
8
Zip
• We can iterate over two lists ’in parallel’, in a sense iterating over a list of tuples
• We can use zip to do this
• The shorter list defines the length of the iteration
number_list = [11, 2, 8]
char_list = ['a', 'b', 'c', 'd']
for number, char in zip(number_list, char_list):
print(number, char)
# prints '11 a', '2 b', and '8 c'
9
Enumerate
• We can iterate over elements and keep track of the index at the same time using
enumerate
# longer alternative
i = 0
for char in char_list:
print(i, char)
i += 1
10
Reading Files
import os
print(os.getcwd())
file = open('./datafiles/iris.data')
print(file)
11
Reading Files
file = open('./datafiles/iris.data')
for line in file:
print(line)
12
Writing Files
13
Pickle
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data
• Sequences, Strings
• Lists
• Dictionaries
• Tuples
• Utilities
• Files
1
Classes
class Car:
def __init__(self):
print('hi, I am a new car')
car = Car()
# creates a Car object assigned to car
# prints 'hi, I am a new car'
2
Attributes
class Car:
def __init__(self):
self.velocity = 0
car = Car()
car.velocity # -> 0
3
Attributes
class Car:
def __init__(self, v):
self.velocity = v
car = Car(100)
car.velocity # -> 100
4
Methods
def accelerate(self):
self.velocity += 1
car = Car(100)
car.velocity # -> 100
car.accelerate()
car.velocity # -> 101
5
Self
• The first parameter of a method (self by convention) refers to the object the method is called on
• This means self points to the object before the dot
• This also means that we have to pass one less argument to the method that it has parameters in
the definition (because self is already assigned)
class Car:
def __init__(self, v):
self.velocity = v
def accelerate(self):
self.velocity += 1
car = Car(100)
car.velocity # -> 100
car.accelerate()
car.velocity # -> 101
6
Objects are Mutable
def stop(car):
car.velocity = 0
car = Car(100)
stop(car)
car.velocity # -> 0
7
Combining Objects
class Line:
def __init__(self, start, end):
self.start = start
self.end = end
2 Statements
Create a class Statement that represents a programming statement. It has two attributes:
• command is a string and contains the statement’s command, e.g. 'move', 'turn', etc.
• arguments is a sequence of values that parametrize the statement, e.g. (10, 50).
Create a constructor for the Statement class that takes as parameters a) the command and b)
any number of statement arguments. You may consider gathering the arguments using * as
discussed in the lecture. Don’t forget to add the self parameter to the constructor.
s0 = Statement('move', 10, 50)
print(s0.command) # prints 'move'
print(s0.arguments) # prints (10, 50)
Create a method interpret in the Statement class that prints the command and its arguments.
For example, if command is 'move' and arguments are '(10, 50)', print 'move 10 50'. Don’t
forget to add the self parameter to the method definition.
s0 = Statement('move', 10, 50)
s0.interpret() # prints 'move 10 50'
s1 = Statement('turn', 45)
s1.interpret() # prints 'turn 45'
3 Programs
Create a class Program that has a list of Statement as attributes. Define a constructor that takes
no arguments and initializes an empty list of statements.
p = Program()
print(p.statements) # prints []
Define a method append in the Program class that takes a statement as parameter and appends
it to the list of statements of that program.
p = Program()
p.append(s0)
p.append(s1)
print(len(p.statements)) # prints 2
print(p.statements[0].command) # prints 'move'
Create a method interpret in class Program that calls the interpret method on all statements
in the program’s statement list.
1
4 Parsing
Create a method parse in class Program that takes a program string containing one statement
written as a string per line, creates a Statement object for each line, and adds the statement to
the program’s statement list.
p = Program()
p.parse('move 1 2\nturn 90')
p.interpret()
# prints move 1 2
# prints turn 90
Can you load, parse and interpret a program that is written in a file?
2
Introduction to Programming
Inheritance
Lenz Belzner
Based on Think Python 2nd Edition by Allen B. Downey
Overview
• Structure of programs
• Variables, Values, Types, Operations
• Functions, Scope
• Conditions, Return Values
• Recursion, Iteration
• Structure of data
• Sequences, Strings
• Lists
• Dictionaries
• Tuples
• Utilities
• Files
• Classes
• Inheritance
1
Inheritance
2
Inheritance
class General:
def __init__(self):
self.name = 'general'
def general_method(self):
print('I am ' + self.name + '.')
class Special(General):
def special_method(self):
print('I am' + self.name + ', but special.')
special = Special()
special.general_method() # prints 'I am general.'
special.special_method() # prints 'I am general, but special.'
3
Inheritance
4
super
class Special(General):
def __init__(self):
super().__init__()
self.additional_attribute = 'special'
def special_method(self):
print('I am ' + self.name + ', but ' + self.additional_attribute + '.')
special = Special()
special.special_method() # prints 'I am general, but special.' 5
super
class Special(General):
def __init__(self, name):
super().__init__(name)
self.additional_attribute = 'special'
def special_method(self):
print('I am ' + self.name + ', but ' + self.additional_attribute + '.')
special = Special('general')
special.special_method() # prints 'I am general, but special.'
6
Association
• We can also organize code by making objects of one class an attribute of another
class Vehicle:
# class code omitted for brevity
class Tire:
# class code omitted for brevity
class Car(Vehicle):
def __init__(self, tire):
super().__init__()
self.tire = tire
car = Car(Tire())
7
1 Statements and Expressions
1.1 Values, Types, Operations and Precedence
Consider the following python program.
a = 3 ** 2 // 2
b = ('h' + str(1)) * 2
c = 'h' + str(1) * 2
d = ['hi'] * 2
e = ['hi' * 2]
f = 1 < 2 or 2 ** 2 > 1 ** 1
filtered_data = []
for element in store:
if store[element] > 0:
filtered_data.append(store[element])
elif store[element] < 0:
filtered_data = []
1
2 Functions, Patterns
2.1 Average
Implement a function average(l) that computes and returns the average value of elements in
a list. You can assume the list contains at least one element, and that all elements in the list are
integers.
# Examples
average([1, 2]) # -> 1.5
average([-1, 1, -1, 1]) # -> 0.0
2.2 Check
Implement a function check(l) that returns True if the list argument contains at least one
element, and all elements in it are integers, and that returns False otherwise. You can assume
the argument is always a list.
# Examples
check([1, 2]) # -> True
check([1, 'hello']) # -> False
check([]) # -> False
# Examples
check_and_average([1, 2]) # -> 1.5
check_and_average([1, 'hello']) # -> None, prints 'Please check your list.'
check_and_average([]) # -> None, prints 'Please check your list.'
2
3 Loops, Recursion
3.1 Recursive Count
Consider the following program. You can assume message is a string, and character is a string
containing a single character.
# Examples
count('hello there', 'e') # -> 3
count('hello there', 'o') # -> 1
count('hello there', 'a') # -> 0
# Examples
recursive_count('hello there', 'e') # -> 3
recursive_count('hello there', 'o') # -> 1
recursive_count('hello there', 'a') # -> 0
3
4 Strings
4.1 Remove Vowels
Implement a function remove_vowels(message) that takes a string as an argument, and returns
a string with all vowels (’a’, ’e’, ’i’, ’o’, ’u’) removed. You can assume the argument is a string.
# Examples
remove_vowels('hello there') # -> 'hll thr'
remove_vowels('') # -> ''
# Examples
is_sorted(['hello', 'there']) # -> True
is_sorted(['hello', 'again']) # -> False
is_sorted(['all', 'blues', 'miles', 'music']) # -> True
4
5 Classes and Objects
5.1 Colorful Bikes
Consider the following definition for class Tire.
class Tire:
def __init__(self, color):
self.color = color
tire = Tire('magenta')
tire.paint('orange')
tire.color # -> 'orange'
Implement a class Bike with a constructor such that a bike object has a black front tire and a
black rear tire as attributes. A correct implementation should yield the following behaviour.
bike = Bike()
bike.front.color # -> 'black'
bike.rear.color # -> 'black'
bike.front is bike.rear # -> False
In class Bike, implement a method set_tire(self, tire, position) that replaces the bike’s
tire at the given position with the new tire passed as an argument. A correct implementation
should yield the following behaviour.
bike = Bike()
bike.set_tire(Tire('magenta'), 'front')
bike.front.color # -> 'magenta'
bike.set_tire(Tire('orange'), 'rear')
bike.rear.color # -> 'orange'
5
5.2 Object Diagram
Consider the following object diagram, omitting the class definitions for Tire and Bike. Write
minimal code that produces this diagram using the Bike and Tire classes.
6
6 Scope, Mutability, Aliasing
Consider the following program. What does it print?
def f(x):
x[0] += 1
print(x)
def g(x):
y = x
y[0] += 1
print(y)
def h(x):
y = x[:]
y[0] += 1
print(y)
x = [0, 1]
f(x)
print(x)
x = [0, 1]
g(x)
print(x)
x = [0, 1]
h(x)
print(x)