1-8. Lists1 fragment
Fragment 1 of 1
my_list[5] = my_list[4] + my_list[3]
1-11-1. Assignment Statements1 fragment
Fragment 1 of 1
x = 1
1-11-3. If Statements1 fragment
Fragment 1 of 1
if n == 1:
print("One")
elif n == 2:
print("Two")
elif n == 3:
print("Three")
else:
print("Many")
print("or maybe none at all")
1-11-4. While Loops2 fragments
Fragment 1 of 2
n = 5
while n > 0:
print(n)
n -= 1
print("Blast off!")
Fragment 2 of 2
n = 6
while (n := n - 1) > 0:
print(n)
print("Blast off!")
1-11-5. For Loops2 fragments
Fragment 1 of 2
for i in [5, 4, 3, 2, 1]:
print(i)
print("Blast off!")
Fragment 2 of 2
for i in range(5, 0, -1):
print(i)
print("Blast off!")
1-11-6. Import Statements2 fragments
Fragment 1 of 2
from math import sqrt, log
Fragment 2 of 2
from math import *
1-12. Input from the User2 fragments
Fragment 1 of 2
name = input("What is your name? ")
print("Hello,", name)
Fragment 2 of 2
question = "How old are you, " + name + "? "
age = int(input(question))
1-13. Functions1 fragment
Fragment 1 of 1
def largest(a, b, c):
"""Return the largest of a, b, and c."""
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
return c
1-16. Summary1 fragment
Fragment 1 of 1
# Program to print prime numbers
def is_prime(n):
"""Test if a number n is prime."""
divisor = 2
while divisor * divisor <= n:
if n % divisor == 0:
return False
divisor += 1
return True
def print_primes(limit):
for i in range(2, limit + 1):
if is_prime(i):
print(i, end=' ')
n = input("Print all primes up to: ")
print_primes(int(n))
2-2. Lists1 fragment
Fragment 1 of 1
x = [0] * 3
for i in range(0, 3):
x[i] = [0] * 5
2-3. Tuples2 fragments
Fragment 1 of 2
a, b, c = 1, 2, 3
Fragment 2 of 2
a, b = b, a # the values of a and b are interchanged
2-4. Sets2 fragments
Fragment 1 of 2
s = {10, "ten", "X"}
Fragment 2 of 2
for elem in s:
print(elem)
2-5. Dictionaries3 fragments
Fragment 1 of 3
phones = {"Alice":5551212, "Jill":5556789, "Bob":5559999}
Fragment 2 of 3
phones["Xavier"] = 5556666
Fragment 3 of 3
del phones["Xavier"]
2-7-1. Looping over Lists3 fragments
Fragment 1 of 3
for e in my_list:
print(e)
Fragment 2 of 3
for i in range(0, len(my_list)):
print(my_list[i], "is at", i)
Fragment 3 of 3
for index, value in enumerate(my_list):
print(value, "is at", index)
2-7-2. Looping over Sets1 fragment
Fragment 1 of 1
for e in my_set:
print(e)
2-7-3. Looping over Dictionaries6 fragments
Fragment 1 of 6
for k in my_dict:
print(k) # prints just the keys
Fragment 2 of 6
for k in my_dict.keys():
print(k) # prints just the keys
Fragment 3 of 6
for v in my_dict.values():
print(v) # prints just the values
Fragment 4 of 6
for k in my_dict:
print(k, "->", my_dict[k])
Fragment 5 of 6
for t in my_dict.items():
print(t) # prints (key, value) tuples
Fragment 6 of 6
for k, v in my_dict.items():
print(k, "is", v)
2-8. Handing Exceptions2 fragments
Fragment 1 of 2
try:
# code that could go wrong
except SomeErrorType:
# what to do if it goes wrong
finally:
# what to do afterwards
Fragment 2 of 2
number = None
while number is None:
try:
n = input("Enter an integer: ")
number = int(n)
except Exception:
print("Try again!")
print("Your number is", number)
2-11. File I/O1 fragment
Fragment 1 of 1
count = 0
with open(file_name, 'r') as f:
while f.readline():
count += 1
3-1. Classes and Inheritance1 fragment
Fragment 1 of 1
class Person(object):
name = 'Joe'
age = 23
def say_hi(self):
print('Hello, Joe.')
3-2. Constructors and self2 fragments
Fragment 1 of 2
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def say_hi(self):
print('Hello', self.name)
Fragment 2 of 2
def get_older(self):
self.age += 1
def get_much_older(self, years):
for i in range(0, years):
self.get_older()
3-3. Subclasses4 fragments
Fragment 1 of 4
class Friend(Person):
def smile(self):
print('¯\_(^-^)_/¯')
meg = Person('Margaret', 25)
bob = Friend('Robert', 33)
Fragment 2 of 4
def say_hi(self, extra):
print('Hi!', extra)
Fragment 3 of 4
def say_hi(self, extra):
super().say_hi()
print(extra)
Fragment 4 of 4
def __init__(self, name, age, nick):
super().__init__(name, age)
self.nickname = nick
3-4. Printing Objects3 fragments
Fragment 1 of 3
<__main__.Friend object at 0x1064728d0>
Fragment 2 of 3
def __str__(self):
return self.name + "'s age is " + str(self.age)
Fragment 3 of 3
Margaret's age is 19
3-6. Bindings4 fragments
Fragment 1 of 4
a = 5 # bind a to 5
b = a # copy a's binding into b
a = 6 # change the binding of a
print(b) # b is still bound to 5
Fragment 2 of 4
a = [1, 2, 3] # bind a to the list
b = a # copy a's binding into b
a = [4, 5, 6] # change the binding of a
print(b) # b is still bound to [1, 2, 3]
Fragment 3 of 4
a = [1, 2, 3] # bind a to the list
b = a # copy a's binding into b
a[0] = 99 # change the list, not the bindings
print(b) # b still bound to the same list,
# but the list is now [99, 2, 3]
Fragment 4 of 4
def foo(a, b):
a[0] = 99
b = [7, 8]
a = [1, 2, 3]
b = [1, 2, 3]
foo(a, b)
print(a, b) # [99, 2, 3] [1, 2, 3]
3-7. Shallow and Deep Copies2 fragments
Fragment 1 of 2
grades = [["Mary", "A+"], ["Don", "C-"]]
grades2 = grades[:]
grades2[0] = ["Bob", "B"]
grades2[1][1] = "F"
print(grades) # [['Mary', 'A+'], ['Don', 'F']]
print(grades2) # [['Bob', 'B'], ['Don', 'F']]
Fragment 2 of 2
import copy
grades3 = copy.deepcopy(grades)
grades3[1][1] = "D+"
# grades is unchanged
4-2. Identifiers1 fragment
Fragment 1 of 1
for _ in range(0, 3):
print("Hello!")
4-3. Type Hints3 fragments
Fragment 1 of 3
def indent(line: str, amount: int) -> str:
indented_line:str = ' ' * amount + line
return indented_line
Fragment 2 of 3
from typing import List, Set, Dict, Union, Optional
Fragment 3 of 3
Number = Union[int, float]
4-6. F-Strings2 fragments
Fragment 1 of 2
f'{"abc":6}' is 'abc '
f'{"abc":>6}' is ' abc'
f'{123:6d}' is ' 123'
f'{123:<6d}' is '123 '
f'{pi:6.2f}' is ' 3.14'
f'{pi:<6.2f}' is '3.14 '
Fragment 2 of 2
print('pi is {:8.4f}'.format(pi))
4-9. Iterators3 fragments
Fragment 1 of 3
class MyList():
def __init__(self, ls):
self.ls = ls
def __iter__(self):
return Reverser(self.ls)
class Reverser():
def __init__(self, ls):
self.ls = ls
self.index = len(self.ls)
def __next__(self):
self.index = self.index - 1
if self.index >= 0:
return self.ls[self.index]
raise StopIteration
Fragment 2 of 3
ls = MyList([1, 2, 3, 4])
for e in ls:
print(e)
Fragment 3 of 3
ls = MyList([1, 2, 3, 4])
it = iter(ls)
while True:
try:
print(next(it))
except StopIteration:
break
4-10. Generators5 fragments
Fragment 1 of 5
word = 'generator'
gen = (c for c in word if c in 'aeiou')
for i in gen:
print(i, end=' ')
Fragment 2 of 5
def powers_of_two():
n = 2
for i in range(0, 5):
yield n
n *= 2
Fragment 3 of 5
gen = powers_of_two()
for n in gen:
print(n)
Fragment 4 of 5
gen = powers_of_two()
while True:
try:
print(next(gen))
except StopIteration:
break
Fragment 5 of 5
The call gen = powers_of_two() returns a generator and puts it in gen.
The first call of next(gen) executes the generator down to the yield statement, and returns the yielded value, just like a normal return statement. But in addition, the generator remembers where it left off.
A subsequent call to next(gen) will cause the generator to resume execution where it left off, that is, immediately after the yield statement. All the values of local variables will have been retained. As far as the generator is concerned, it is as if the yield had never happened. In this example, the for loop keeps running.
4-11. Parameters and Arguments1 fragment
Fragment 1 of 1
def foo(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
4-12. Functional Programming6 fragments
Fragment 1 of 6
def biggest(values):
big = values[0]
for v in values:
if v > big:
big = v
return big
Fragment 2 of 6
def most(values, more):
best = values[0]
for v in values:
if more(v, best):
best = v
return best
def larger(a, b):
return a > b
Fragment 3 of 6
most([1, 6, 1, 8, 0], larger)
Fragment 4 of 6
def longer(a, b):
return len(a) > len(b)
most(["a", "generic", "list"], longer)
Fragment 5 of 6
lambda a, b: len(a) > len(b)
Fragment 6 of 6
print(most(["a", "generic", "list"],
lambda a, b: len(a) > len(b)))
5-2. Doctest4 fragments
Fragment 1 of 4
def get_digits(number):
"""Return a list of digits in an int or string."""
string = str(number)
return [x for x in string if x.isdigit()]
Fragment 2 of 4
>>> get_digits("124c41")
['1', '2', '4', '4', '1']
>>> get_digits(1213141)
['1', '2', '1', '3', '1', '4', '1']
Fragment 3 of 4
def get_digits(number):
"""Return a list of digits in an int or string."""
>>> get_digits("124c41")
['1', '2', '4', '4', '1']
>>> get_digits(1213141)
['1', '2', '1', '3', '1', '4', '1']
"""
string = str(number)
return [x for x in string if x.isdigit()]
Fragment 4 of 4
import doctest
doctest.testmod()
5-3. Unit Testing4 fragments
Fragment 1 of 4
def test_add(self):
self.assertEqual(4, add(2, 2))
self.assertEqual(0, add(2, -2))
Fragment 2 of 4
self.assertRaises(ZeroDivisionError, 5/0)
Fragment 3 of 4
if __name__ == '__main__':
main()
Fragment 4 of 4
unittest.main()
5-4. Unit Test Example2 fragments
Fragment 1 of 2
def get_digits(number):
"""Return a list of digits in an int or string."""
string = str(number)
return [x for x in string if x.isdigit()]
def main():
s = input("Enter something: ")
digits = get_digits(s)
print("Digits found:", digits)
if digits != []:
main()
# Call main() if and only if started from this file
if __name__ == '__main__':
main()
Fragment 2 of 2
import unittest
from get_digits import *
class test_get_digits(unittest.TestCase):
def test_get_digits(self):
s = get_digits("<0.12-34 56abc789x")
self.assertEqual(list("0123456789"),
get_digits(s))
self.assertEqual(list("1230"),
get_digits(1230))
unittest.main()
5-5. Test Suites1 fragment
Fragment 1 of 1
import unittest
import testfoo, testbar
def suite():
suite = unittest.TestSuite()
suite.addTest(
unittest.makeSuite(
testfoo.TestFoo))
suite.addTest(
unittest.makeSuite(
testbar.TestBar))
return suite
if __name__ == '__main__':
test_suite = suite()
runner = unittest.TextTestRunner()
runner.run (test_suite)
6-2. Tkinter4 fragments
Fragment 1 of 4
from tkinter import *
import tkinter.ttk
Fragment 2 of 4
top = Tk()
Fragment 3 of 4
top.mainloop()
Fragment 4 of 4
import tkinter
root = tkinter.Tk()
root.withdraw()
6-5. Tkinter Example1 fragment
Fragment 1 of 1
from tkinter import *
import tkinter.ttk
from random import randint
def roll():
n = str(randint(1, 6))
result.configure(text=n)
top = Tk()
roll_button = Button(top, text='Roll', command=roll)
result = Label(top, width=12)
roll_button.grid(row=0)
result.grid(row=1)
Appendix C: Statistics2 fragments
Fragment 1 of 2
from statistics import *
a = [1, 2, 3, 4, 5, 5, 78]
print(f"{mean(a)=}, {median(a)=}, {mode(a)=}")
Fragment 2 of 2
print(f"{stdev(a):6.2f}, {variance(a):6.2f}")