This appendix contains the answers to the exercises found in the lessons. The answers to the Quick checks are very straightforward, but the answers to some of the Summary exercises may be achieved in several different ways. I have provided a possible solution for each, but your answers may vary slightly from the ones that I have provided.
Problem—Make mac-and-cheese.
Vague statement—Dump box of mac-and-cheese in boiling water for 12 minutes.
Specific statement—Pour 6 cups of water in a pot, turn up stovetop temp and wait for water to boil, pour in noodles, let them cook for 12 minutes, drain noodles, add packet of cheese, and stir.

- Keep value of interest on the left: c2 = a2 + b2
- Take the square root: c = √(a2 + b2)
# initialize times to fill pool (in fraction hours) # convert times to minutes # convert times to rates # add rates # solve for minutes when using both hoses
Won’t see any output on the console
Allowed
Phone attributes—Rectangular, glossy, black, lights up, 4 in x 2 in, has buttons. Operations—Click buttons, makes noise, throw it, make a call, type an email.
Dog attributes—Furry, four paws, one mouth, two eyes, one nose, two ears. Operations—Bark, scratch, run, jump, whine, lick.
Mirror attributes—Reflective, fragile, sharp. Operations—Breaks, shows reflection.
Credit card attributes—3 jn k 2 nj, nrdj, elieblxf, spz numbers pzn etselrt. Operations—Swqjk, gxz re onxq oords, aqk rv ydb ufsft.
Yes
No (too long)
fruits = apples + oranges
Xqx illts vrp nc rorre. Yajd cj scbeaue rux Zohytn trentrrpiee eosdn’r eanddnrust rwcq er xu wrgj vrd srfa fjnk. Rdk nrrpeeetirt jz eptncgexi c nmxz rx rxd xfrl le pkr equal sign, rqg a + x jna’r z knzm.
neg /= 10
other_half = 1.0 - half
day = cold and rain
last_one = "one 1" or last_one = 'one 1'
NoneType
Statement
str(True)
int("4") 4
int 0
166 hours and 39 minutes
12
ratio_truncated = int(ratio) ratio_truncated is an int
minutes_to_convert = 789 hours_decimal = minutes_to_convert/60 hours_part = int(hours_decimal) minutes_decimal = hours_decimal-hours_part minutes_part = round(minutes_decimal*60) print("Hours") print(hours_part) print("Minutes") print(minutes_part)
Output:
Hours 13 Minutes 9
miles = 5 km = miles/0.62137 meters = 1000*km print("miles") print(miles) print("km") print(km) print("meters") print(meters)
Take our tour and find out more about liveBook's features:
- Search - full text search of all our books
- Discussions - ask questions and interact with other readers in the discussion forum.
- Highlight, annotate, or bookmark.
Yes
Forward: 12 Backward: -1
' '
'L' 'x'
''
( empty tsgnir, uescbae rdo satrt ndixe cj ehtrruf nj oqr tgnirs yzrn qxr hrva eindx, ghr orq gcrx aj 1)
'python 4 ever&ever'
s = "RaceTrack" s[1:4].captalize()
8
False
0
(Qk output) hyr b ja wen 'Raining in the spring tiempo.'
'red-circlered-circlered-circle'
There are many other ways of achieving this!
s = "Eat Work Play Sleep repeat" s = s.replace(" ", "ing ") s = s[7:22] s = s.lower() print(s)
- Tvq’xt yngrit rx scscea nz dxein jn vrb stinrg brrz’a yeodnb xrb xjsc el vrp srngit.
- Xvy’ot gnytri rx cfzf xry ommancd wrjq ns cobejt nowd rgk ommancd soden’r nkob yighatnn jn rod esanshreept.
- Bge’tx rgtyni er fzsf orq cmnamdo wrjd nfux ekn otjcbe vpnw ryv nmomcad sndee rwe jn xqr ressenahtpe.
- Tvg’tv rtinyg rk sfsf rgx momadnc ruwj sn ecjtbo lx krb nrwgo krqd. Che rmcg vjkh jr s sgrnit jeobtc, rkn nz eniretg tocbje.
- Tkh’vt rtygni kr ffzs rgo ndcmoam rwpj a variable zvnm bnc knr s rsitng ctjebo. Byzj owudl wxxt lj qvd iieitlaidzn h er od s gsintr efreob vhy bxz jr.
- Xhk’ot itnrgy xr puiytlml ewr strings dwkn hqe’vt gxnf aelwold rv pqs wxr strings tk utplilmy z nirtgs gh ns regneit.
Yes
0
True
(1, 1, 1, 1)
(no, yes) = (yes, no)
Ropkt ctk nsmq cusw ukg nss xb jrzu. Hoxt’a kvn swh:
word = "echo" t = () count = 3 echo = (word,) echo *= count cho = (word[1:],) cho *= count ho = (word[2:],) ho *= count o = (word[3:],) o *= count t = echo + cho + ho + o print(t)
print("I choose the " + sweet.upper() + "!")
input("Enter one of: # or $ or % or & or *: ")
celeb = input("Tell me the first & last name of a celebrity: ") space = celeb.find(" ") print(celeb[0:space]) print(celeb[space+1:len(celeb)])
user_input = input("Enter a number to find the square of: ") num = float(user_input) print(num*num)
b = int(input("Enter a number: ")) e = int(input("Enter a number: ")) b_e = b**e print("b to the power of e is", b_e)
name = input("What's your name? ") age = int(input("How old are you? ")) older = age+25 print("Hi " + name + "! In 25 years you will be " + str(older) + "!")
Take our tour and find out more about liveBook's features:
- Search - full text search of all our books
- Discussions - ask questions and interact with other readers in the discussion forum.
- Highlight, annotate, or bookmark.
No
Variables a and b are equal
Finished
word = input("Tell me a word: ") print(word) if " " in word: print("You did not follow directions!")
num1 = int(input("One number: ")) num2 = int(input("Another number: ")) print(num1+num2) if num1+num2 < 0: print("Wow, negative sum!")
Figure A.1. Flowchart for program in listing 13.3

num_a num_b Answer (nested) Answer (unnested) ----------------------------------------------------------------------- -9 5 num_a: is negative num_a: is negative Finished Finished ----------------------------------------------------------------------- 9 5 Finished Finished ----------------------------------------------------------------------- -9 -5 num_a: is negative num_a: is negative num_b is negative num_b is negative Finished Finished ----------------------------------------------------------------------- 9 -5 Finished num_b is negative Finished
One possible solution shown in listing 13.5.
var = 0 if type(var) == int: print("I'm a numbers person.") if type(var) == str: print("I'm a words person.")
print("Guess my number! ") secret = 7 num = int(input("What's your guess? ")) if num < secret: print("Too low.") if num > secret: print("Too high.") if num == secret: print("You got it!")
num = int(input("Tell me a number: ")) if num >= 0: print("Absolute value:", num) if num < 0: print("Absolute value:", -num)
Ok vyp kzgx s jetack kt s earestw? Ycxo xxn le sthee; jr’z hxfa udioets.
False
num_a num_b 0 0 0 -5 -20 0 -1 -1 -20 -988
num is -3 | Output: num is negative |
num is 0 | Output: num is zero |
num is 2 | Output: num is positive |
num is 1 | Output: num is positive |
Figure A.2. Flowchart for the code in listing 14.3

num With if-elif-else With if --------------------------------------------------------------- 20 num is greater than 3 num is greater than 3 Finished. Finished. --------------------------------------------------------------- 9 num is less than 10 num is less than 10 Finished. num is greater than 3 Finished. --------------------------------------------------------------- 5 num is less than 6 num is less than 6 Finished. num is less than 10 num is greater than 3 Finished. --------------------------------------------------------------- 0 num is less than 6 num is less than 6 Finished. num is less than 10 Finished.
num1 = int(input("One number: ")) num2 = int(input("Another number: ")) if num1 < num2: print("first number is less than the second number") elif num2 < num1: print("first number is greater than the second number") else: print("numbers are equal")
words = input("Enter anything: ") if "a" in words and "e" in words and "i" in words and "o" in words and "u" in words: print("You have all the vowels!") if words[0] == 'a' and words[-1] == 'z': print("And it's sort of alphabetical!")
for i in range(100): print("centipede")
0, 1, 2, 3, 4, 5, 6, ..., 99
num = int(input("Tell me a number: ")) for i in range(num): print("Hello")
Jr jz ilsesobp rk rpelace rkb for veyf bjrw c vnjf ucrr ochc rxd * oratorpe eentweb rbv ernegti nch yro itnsgr, as jn print(num * 'Hello\n')
(Nothing)
vowels = "aeiou" words = input("Tell me something: ") for letter in words: if letter in vowels: print("vowel")
counter = 0 for num in range(2, 100, 2): if num%6 == 0: counter += 1 print(counter, "numbers are even and divisible by 6")
count = int(input("How many books on Python do you have? ")) for n in range(count,0,-1): if n == 1: print(n, "book on Python on the shelf", n, "book on Python") print("Take one down, pass it around, no more books!") else: print(n, "books on Python on the shelf", n, "books on Python") print("Take one down, pass it around,", n-1, " books left.")
names = input("Tell me some names, separated by spaces: ") name= "" for ch in names: if ch == " ": print("Hi", name) name = "" else: name += ch # deal with the last name given (does not have a space after it) lastspace = names.rfind(" ") print("Hi", names[lastspace+1:])
password = "robot fort flower graph" space_count = 0 for ch in password: if ch == " ": space_count += 1 print(space_count)
Cc z cjog vrxn, ryk erpdnecgi code nzz xszf vp rtnweit using z amcnodm kn strings, count, gjwr password.count(" ").
secret = "snake" word = input("What's my secret word? ") guesses = 1 while word != secret: word = input("What's my secret word? ") if guesses == 20 and word != secret: print("You did not get it.") break guesses += 1
# corrected code num = 8 guess = int(input("Guess my number: ")) while guess != num: guess = int(input("Guess again: ")) print("Right!")
play = input("Play? y or yes: ") while play == 'y' or play == "yes": num = 8 guess = int(input("Guess a number! ")) while guess != num: guess = int(input("Guess again: ")) print("Right!") play = input("Play? y or yes: ") print("See you later!")
Independent
Jn: Zvn, arppe, cnom, essdrad, lpvoenee, matps, gddiwne xrzq, éefcnia Urh: Mineddg ttiiaiovnn aeydr rv vy amield
In: Phone number, phone
In: Coin
In: Money
Out: A dress



def print_my_name():
4
No (indentation error)
age or get_age or years_later
"and toes" (return type is a string)
- (100, True)
- (1.0, False)
- Qvnkc’r niptr hiynatgn
- Goank’r rpitn anhnyigt
None
-
- calculate_total(20, 15)
-
-11
-3
24
32
2.0
21
------------------------------------------------- def sandwich(kind_of_sandwich): print("--------") print(kind_of_sandwich ()) print("--------") def blt(): my_blt = " bacon\nlettuce\n tomato" return my_blt def breakfast(): my_ec = " eggegg\n cheese" return my_ec print(sandwich(blt)) <-------- here GLOBAL SCOPE sandwich: (some code) blt: (some code) breakfast: (some code ------------------------------------------------- def sandwich(kind_of_sandwich): <-------- here print("--------") print(kind_of_sandwich ()) print("--------") def blt(): my_blt = " bacon\nlettuce\n tomato" return my_blt def breakfast(): my_ec = " eggegg\n cheese" return my_ec print(sandwich(blt)) GLOBAL SCOPE sandwich: (some code) blt: (some code) breakfast: (some code SCOPE OF sandwich(blt) kind_of_sandwich: blt ------------------------------------------------- def sandwich(kind_of_sandwich): print("--------") print(kind_of_sandwich ()) <-------- here print("--------") def blt(): my_blt = " bacon\nlettuce\n tomato" return my_blt def breakfast(): my_ec = " eggegg\n cheese" return my_ec print(sandwich(blt)) GLOBAL SCOPE sandwich: (some code) blt: (some code) breakfast: (some code SCOPE OF sandwich(blt) kind_of_sandwich: blt ------------------------------------------------- def sandwich(kind_of_sandwich): print("--------") print(kind_of_sandwich ()) print("--------") def blt(): <-------- here my_blt = " bacon\nlettuce\n tomato" return my_blt def breakfast(): my_ec = " eggegg\n cheese" return my_ec print(sandwich(blt)) GLOBAL SCOPE sandwich: (some code) blt: (some code) breakfast: (some code SCOPE OF sandwich(blt) kind_of_sandwich: blt SCOPE OF blt() ------------------------------------------------- def sandwich(kind_of_sandwich): print("--------") print(kind_of_sandwich ()) print("--------") def blt(): my_blt = " bacon\nlettuce\n tomato" return my_blt <-------- here def breakfast(): my_ec = " eggegg\n cheese" return my_ec print(sandwich(blt)) GLOBAL SCOPE sandwich: (some code) blt: (some code) breakfast: (some code SCOPE OF sandwich(blt) kind_of_sandwich: blt SCOPE OF blt() Returns: bacon lettuce tomato ------------------------------------------------- def sandwich(kind_of_sandwich): print("--------") print(kind_of_sandwich ()) print("--------") <-------- here def blt(): my_blt = " bacon\nlettuce\n tomato" return my_blt def breakfast(): my_ec = " eggegg\n cheese" return my_ec print(sandwich(blt)) GLOBAL SCOPE sandwich: (some code) blt: (some code) breakfast: (some code SCOPE OF sandwich(blt) kind_of_sandwich: blt returns: None
def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) <---------- here GLOBAL SCOPE grumpy: (some code) ----------------------------------------------------------------- def grumpy(): <---------- here print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) GLOBAL SCOPE grumpy: (some code) SCOPE OF grumpy() ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times <---------- here grumpy()(4)(2) GLOBAL SCOPE grumpy: (some code) SCOPE OF grumpy() no_n_times(): (some code) Returns: no_n_times ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) <---------- here this line is now no_n_times(4)(2) GLOBAL SCOPE grumpy: (some code) ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): <---------- here print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) GLOBAL SCOPE grumpy: (some code) SCOPE OF no_n_times(4) n: no_m_more_times: (some code) ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times <---------- here return no_n_times grumpy()(4)(2) GLOBAL SCOPE grumpy: (some code) SCOPE OF no_n_times(4) n: 4 no_m_more_times: (some code) Returns: no_m_more_times ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) <---------- here this line is now no_m_more_times(2) GLOBAL SCOPE grumpy: (some code) ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): <---------- here print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) GLOBAL SCOPE grumpy: (some code) SCOPE OF no_m_more_times(2) m: 2 ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") <---------- here return no_m_more_times return no_n_times grumpy()(4)(2) GLOBAL SCOPE grumpy: (some code) SCOPE OF no_m_more_times(2) m: 2 Returns: None ----------------------------------------------------------------- def grumpy(): print("I am a grumpy cat:") def no_n_times(n): print("No", n,"times...") def no_m_more_times(m): print("...and no", m,"more times") for i in range(n+m): print("no") return no_m_more_times return no_n_times grumpy()(4)(2) <---------- here and done with this line GLOBAL SCOPE grumpy: (some code)
def area(shape, n): # write a line to return the area # of a generic shape with a parameter of n return shape(n)
def person(age): print("I am a person") def student(major): print("I like learning") def vacation(place): print("But I need to take breaks") print(age,"|",major,"|",place) return vacation return student
- person(29)("CS")("Japan")
- person(23)("Law")("Florida")
Fhiret immutable jeotcb (tluep, eeacbus rxu mnsae kl steiic nxw’r gaehnc) xt mutable (crfj, sbceuea pxp msd mdrdv/oaee stciei sa deened)
Jm mutable cteojb, zn rjn (s mutable otecbj wludo vq lroivelk bsacuee bks jc kunf nex mxjr, vz ykr edevarho lk haingcgn rj nzj’r wrhot ainkmg rj mutable)
Immutable object, a string
one is an immutable object.
age is a mutable object.
List
stapler
1 4 0 8 2 error
[1,2,3,4,5] [0,1,2,3,4,5]
[3,1,4,1,5,9] [3,1,4,1,5] [3,1,4,1]
[3, 2, 3, 4, 6, 11, 13, 1]
def unique(L): L_unique = [] for n in L: if n not in L_unique: L_unique.append(n) return L_unique def common(L1, L2): unique_L1 = unique(L1) unique_L2 = unique(L2) length_L1 = len(unique_L1) length_L2 = len(unique_L2) if length_L1 != length_L2: return False else: for i in range(length_L1): if L1[i] not in L2: return False return True
['g', 'n', 'i', 'm', 'm', 'a', 'r', 'g', 'o', 'r', 'p'] ['a', 'g', 'g', 'i', 'm', 'm', 'n', 'o', 'p', 'r', 'r'] ['r', 'r', 'p', 'o', 'n', 'm', 'm', 'i', 'g', 'g', 'a'] ['a', 'g', 'g', 'i', 'm', 'm', 'n', 'o', 'p', 'r', 'r'] ['a', 'g', 'g', 'i', 'm', 'm', 'n', 'o', 'p', 'r', 'r']
board = [[x, o, x, o], [o, o, x, x], [o, empty, x, x]]
"the secret of life is 42".split("s")
Geiehrt (ueesabc uvr isrtf glgageu krg dcm nerev qkr iedcpk ud)
cities = "san francisco,boston,chicago,indianapolis" city_list = cities.split(",") city_list.sort() print(city_list)
def is_permutation(L1, L2): L1.sort() L2.sort() return L1 == L2
employee_database = {} Key: string for the name Value: tuple of (phone number as a string, home address as a string)
snow_accumulation = {} Key: string for the city Value: tuple (int year 1990, float for snow in 1990, int year 2000, float for snow in 2000)
valuables = {"tv": 2000, "sofa": 1500} Key: string for the item name Value: int for the value
Three entries. Maps integers to lists.
{} {'LA': 3884} {'NYC': 8406, 'LA': 3884} {'NYC': 8406, 'LA': 3884, 'SF': 837} {'NYC': 8406, 'LA': 4031, 'SF': 837}
3.14 1.41 (there will be an error)
(Order doesn’t matter, as you’ll see in the next section.)
25 51 35
songs = {"Wannabe": 3, "Roar": 4, "Let It Be": 5, "Red Corvette": 5, "Something": 1} for s in songs.keys(): if songs[s] == 5: print(s)
def invert(d): d_inv = {} for k in d: v = d[k] if v not in d_inv: d_inv[v] = [k] else: d_inv[v].append(k) return d_inv
Svsm JQ (Xeccinllyha, rjyz ldshou hk z irnfedtfe JG bacseue immutable objects qkn’r zgkv eilasas. Yyr Zthyno cj ogpitmnzii ndibhe xru escens hd nrienfecger ryx bjocet brzr raldeay sitexs wyrj rqv cxsm laveu nsetdai lv creating onetrah nvo. Bpokz noiioszipttma ncto’r egranuetad kr hpnaep zff dxr kjrm.)
Keffrtein JN (Tvg’to creating oertahn ejboct qrcr hppnase rk dxzv grk msxc elements, xnr cn lisaa.)
No
cards = deck
4 deck.sort()
def invert_dict_inplace(d): new_d = d.copy() d = {} for k in new_d.keys(): d[d_new[k]] = k
Ov (duwol kknh vr diecde wchih reepsriopt gns behaviors rv ndeife z eosrnp—tel example, s mcon, ns usx, hiegth, hgwtie, nac vrhu wsfe, vfrs?)
Ke (dluwo yvnx vr cieded hhicw esrrpeptio znp behaviors rv dfeeni c iarhc—vlt example, bemrun lk xfdc, gtihhe, thpde, wpsr szn edu eq wjdr z richa?)
Qvcm, xcb, tgeihh, ighwte, sytj lcroo, vbk oolrc, pcn ax rofth
Change name, increment the age, change hair color
String
class Computer(object):
class Person(object): def __init__(self): self.name = "" self.age = 0 class Car(object): def __init__(self): self.length = 0 self.width = 0 self.height = 0 class Computer(object): def __init__(self): self.on = False self.touchscreen = False
class Door(object): def __init__(self): self.width = 1 self.height = 1 self.open = False def get_status(self): return self.open def get_area(self): return self.width*self.height
square_door = Door() square_door.change_state() square_door.scale(3)
a = Rectangle(1,1) b = Rectangle(1,1) Rectangle.set_length(a, 4) Rectangle.set_width(b, 4)
def get_area(self): """ returns area of a circle """ return 3.14*self.radius**2 # testing method a = Circle() print(a.get_area()) # shoould be 0 a.change_radius(3) print(a.get_area()) # should be 28.26
def get_area(self): """ returns area of a rectangle """ return self.length*self.width def get_perimeter(self): """ returns perimeter of a rectangle """ return self.length*2 + self.width*2
Take our tour and find out more about liveBook's features:
- Search - full text search of all our books
- Discussions - ask questions and interact with other readers in the discussion forum.
- Highlight, annotate, or bookmark.
def add_list(self, L): for e in L: self.stack.append(e)
circles = Stack() for i in range(3): one_circle = Circle() one_circle.change_radius(3) circles.add_one(one_circle) rectangles = Stack() one_rectangle = Rectangle(1, 1) rectangles.add_many(one_rectangle, 5)
class Queue(object): def __init__(self): self.queue = [] def get_queue_elements(self): return self.queue.copy() def add_one(self, item): self.queue.append(item) def add_many(self, item, n): for i in range(n): self.queue.append(item) def remove_one(self): self.queue.pop(0) def remove_many(self, n): for i in range(n): self.queue.pop(0) def size(self): return len(self.queue) def prettyprint(self): for thing in self.queue[::-1]: print('|_',thing, '_|') # testing the class by making objects and doing operations a = Queue() a.add_one(3) a.add_one(1) a.prettyprint() a.add_many(6,2) a.prettyprint() a.remove_one() a.prettyprint() b = Queue() b.prettyprint()
def __sub__(self, other_fraction): new_top = self.top*other_fraction.bottom - \ self.bottom*other_fraction.top new_bottom = self.bottom*other_fraction.bottom return Fraction(new_top, new_bottom)
def __str__(self): toreturn = str(self.top) + "\n--\n" + str(self.bottom) return toreturn
(half.__mul__(half)).__str__() Fraction.__str__(Fraction.__mul__(half, half))
class Circle(object): def __init__(self): self.radius = 0 def change_radius(self, radius): self.radius = radius def get_radius(self): return self.radius def __str__(self): return "circle: "+str(self.radius) class Stack(object): def __init__( self): self.stack = [] def get_stack_elements(self): return self.stack.copy() def add_one(self , item): self.stack.append(item) def add_many(self , item, n): for i in range(n): self.stack.append(item) def remove_one(self): self.stack.pop() def remove_many(self , n): for i in range(n): self.stack.pop() def size(self): return len(self.stack) def prettyprint(self): for thing in self.stack[::-1]: print('|_',thing, '_|') def __str__(self): ret = "" for thing in self.stack[::-1]: ret += ('|_ '+str(thing)+ ' _|\n') return ret
import fruits import activities
import math distance = float(input("How far away is your friend? (m) ")) speed = float(input("How fast can you throw? (m/s) ")) tolerance = 2 # 0 degrees means throw horizontal and 90 degrees means straight up for i in range(0,91): angle_r = math.radians(i) reach = 2*speed**2*math.sin(angle_r)*math.cos(angle_r)/9.8 if reach > distance - tolerance and reach < distance + tolerance: print("angle: ", i, "Nice throw!") elif reach < distance - tolerance: print("angle: ", i, "You didn't throw far enough.") else: print("angle: ", i, "You threw too far.")
import random heads = 0 tails = 0 for i in range(100): r = random.random() if r < 0.5: heads += 1 else: tails += 1 print("Heads:", heads) print("Tails:", tails)
import time import random count = 0 start = time.clock() for i in range(10000000): count += 1 random.random() end = time.clock() print(end-start) # prints about 4.5 seconds
import time import random def roll_dice(): r = str(random.randint(1,6)) # put bars around the number so it looks like a dice dice = " _ \n|" + r + "|" print(dice) return r start = time.clock() p = "roll" while p == "roll": print("You rolled a dice...") userroll = roll_dice() print("Computer rolling...") comproll = roll_dice() time.sleep(2) if userroll >= comproll: print("You win!") else: print("You lose.") p = input("Type roll to roll again, any other key to quit: ") end = time.clock() print("You played for", end-start, "seconds.")
class TestMyCode(unittest.TestCase): def test_addition_5_5(self): self.assertEqual(5+5, 10) def test_remainder_6_2(self): self.assertEqual(6%2, 0)
def is_prime(n): prime = True for i in range(2,n): if n%i == 0: prime = False return prime def absolute_value(n): if n < 0: return -n elif n >= 0: return n
assertDictEqual(a, b, msg=None)
Srdv xjnr tfnconiu cng teoicn bsrr eqkf trssta cr 1, nrk 2
import unittest def remove_buggy(L, e): """ L, list e, any object Removes all e from L. """ for i in L: if e == i: L.remove(i) def remove_fixed(L, e): """ L, list e, any object Removes all e from L. """ for i in L.copy(): if e == i: L.remove(i) class Tests(unittest.TestCase): def test_123_1(self): L = [1,2,3] e = 1 remove_buggy(L,e) self.assertEqual(L, [2,3]) def test_1123_1(self): L = [1,1,2,3] e = 1 remove_buggy(L,e) self.assertEqual(L, [2,3]) unittest.main()
A canvas: draw lines, circles, rectangles, erase
import tkinter window = tkinter.Tk() window.geometry("500x200") window.title("go go go") window.configure(background="green") window.mainloop()
import tkinter window = tkinter.Tk() window.geometry("100x900") window.title("Tall One") window.configure(background="red") window.mainloop()
import tkinter window1 = tkinter.Tk() window1.geometry("100x100") window1.configure(background="white") window2 = tkinter.Tk() window2.geometry("100x100") window2.configure(background="black") window1.mainloop() window2.mainloop()
btn = tkinter.Button(window, text="Click here", bg="orange") radio_btn1 = tkinter.Radiobutton() radio_btn2 = tkinter.Radiobutton() check_btn = tkinter.Checkbutton()
import tkinter import random def changecolor(): r = random.choice(["red", "green", "blue"]) window.configure(background=r) window = tkinter.Tk() window.geometry("800x600") window.title("My first GUI") btn = tkinter.Button(window, text="Random color!", command=changecolor) btn.pack() window.mainloop()
import tkinter window = tkinter.Tk() window.geometry("200x800") window.title("PhoneBook") phonebook = {} def add(): name = txt_name.get() phone = txt_phone.get() email = txt_email.get() phonebook[name] = [phone, email] lbl.configure(text = "Contact added!") def show(): s = "" for name, details in phonebook.items(): s += name+"\n"+details[0]+"\n"+details[1]+"\n\n" lbl.configure(text=s) txt_name = tkinter.Entry() txt_phone = tkinter.Entry() txt_email = tkinter.Entry() btn_add = tkinter.Button(text="Add contact", command=add) btn_show = tkinter.Button(text="Show all", command=show) lbl = tkinter.Label() txt_name.pack() txt_phone.pack() txt_email.pack() btn_add.pack() btn_show.pack() lbl.pack() window.mainloop()