├── Chap1 ├── arrow.py └── simple.py ├── Chap10 ├── averagenumbers.py ├── averagenumbers2.py ├── badreverse.py ├── builduserlist.py ├── cmdlineargs.py ├── factorpairs.py ├── factorsingles.py ├── fasterprimes.py ├── generator2list.py ├── generatorexpression.py ├── heterolist.py ├── heterolistfor.py ├── heterolistforindex.py ├── listalias.py ├── listassignment.py ├── listaverage.py ├── listcopy.py ├── listequivalence.py ├── listfunc.py ├── listmembership.py ├── listslice.py ├── listslicemod.py ├── makeintegerlists.py ├── makeuniformlists.py ├── negindex.py ├── prefixsuffix.py ├── prettyprint2d.py ├── rangetolist.py ├── reversals.py ├── sqrtcmdline.py ├── threedlist.py ├── timeprimes.py └── uniquefactorpairs.py ├── Chap11 ├── add2or3.py ├── addmany.py ├── addmanyaugmented.py ├── callerkeyword.py ├── enum.py ├── groupwords.py ├── groupwordslist.py ├── namedparams.py ├── phonelist.py ├── readtextfile.py ├── setvslistaccess.py ├── speciallistprinting.py ├── translatedictionary.py ├── translateif.py ├── tupletest.py ├── wordcount.py └── zipseq.py ├── Chap12 ├── betterfileread.py ├── catchallexcept.py ├── checkforzero.py ├── comparerollsrobust.py ├── dividenumbers.py ├── enterinteger.py ├── enterintexcept.py ├── exceptobject.py ├── filereadfinally.py ├── makeintegerlist.py ├── makeintegerlist2.py ├── missedexception.py ├── multiexcept.py ├── multihandle.py ├── nonnegconvert.py ├── nonnegexcept.py ├── otherexcept.py ├── reallycatchallexcept.py ├── reraise.py ├── riskyread.py ├── tryfileread.py └── trynoelse.py ├── Chap13 ├── bankaccounts.py ├── circle.py ├── circlemaker.py ├── circlemakerobject.py ├── dynamicfield.py ├── functiontester.py ├── multisizelightwindow.py ├── newtimeprimes.py ├── plotobj.py ├── randomlights.py ├── rational.py ├── stopwatch.py ├── testliststuff.py ├── testplotter.py ├── trafficlight.py ├── trafficlightobject.py └── widgetfactory.py ├── Chap14 ├── box.py ├── boxadapter.py ├── comptrafficlight.py ├── comptrafficlightapp.py ├── countingstopwatch.py ├── countingstopwatch2.py ├── digitalstopwatch.py ├── digitaltimer.py ├── dot.py ├── graphicalobject.py ├── movablelight.py ├── movablelighttest.py ├── movabletimer.py ├── newtrafficlightapp.py ├── parammovable.py ├── restrictedstopwatch.py ├── simplemultinherit.py ├── stopwatch.py ├── stopwatchplay.py ├── testbox.py ├── testdigitalsw.py ├── testdot.py ├── testlist2.py ├── testrestrictedsw.py ├── timer.py ├── top.py ├── trafficsignal.py ├── turnlight.py ├── turnlighttest.py └── usecountingsw.py ├── Chap15 ├── ascendingplot.py ├── ascendingtheory.py ├── binarysearch.py ├── comparepermutations.py ├── fibonacci.py ├── fibonacciinstrumented.py ├── flexiblesort.py ├── generatepermutations.py ├── inplacecount.py ├── inplacecountlocal.py ├── lcsmemo.py ├── linearsearch.py ├── listpermutations.py ├── listreverse.py ├── nonrecursivememory.py ├── perminstrumented.py ├── randompermute.py ├── recursivecount.py ├── recursivememory.py ├── reversedexample.py ├── searchcompare.py ├── sortintegers.py ├── stdpermutations.py └── stdpermutations2list.py ├── Chap16 ├── airlineroute.py ├── checkconnected.py └── dfs.py ├── Chap2 ├── addintegers.py ├── addintegers2.py ├── addintegers3.py ├── changeabletype.py ├── charactercube.py ├── escapequotes.py ├── multilinestring.py ├── multipleassignment.py ├── multipleassignment2.py ├── multipleassignment3.py ├── pi-print.py ├── powers10left.py ├── powers10left2.py ├── powers10right.py ├── printingexample.py ├── printpath.py ├── printsep.py ├── scientificnotation.py ├── specialchars.py ├── tupleassign.py ├── usinginput.py └── variable.py ├── Chap3 ├── adder.py ├── dividedanger.py ├── enhancedtimeconv.py ├── error.py ├── faultytempconv.py ├── halve.py ├── imprecise.py ├── imprecise10.py ├── precise4.py ├── tempconv.py └── timeconv.py ├── Chap4 ├── absvalueconditional.py ├── alternatedivision.py ├── betterdivision.py ├── betterfeedback.py ├── binaryconversion.py ├── boolvars.py ├── checkrange.py ├── datetransformer.py ├── digittoword.py ├── digittoworderror.py ├── enhancedcheckrange.py ├── floatequals.py ├── floatequals2.py ├── leadingzeros.py ├── max4a.py ├── max4b.py ├── multivsseq1.py ├── multivsseq2.py ├── newcheckrange.py ├── restyleddigittoword.py ├── safedivide.py ├── safedivideconditional.py ├── samedifferent.py ├── simplerbinaryconversion.py ├── simplerdigittoword.py ├── simplerdigittoword2.py ├── timeconvcond1.py ├── timeconvcond2.py └── troubleshoot.py ├── Chap5 ├── abusefor.py ├── addmiddleexit.py ├── addnonnegatives.py ├── betterinputonly.py ├── computesquareroot.py ├── continueexample.py ├── counttofive.py ├── countup.py ├── countvowels.py ├── countvowelselse.py ├── countvowelsnox.py ├── definite1.py ├── definite2.py ├── findfactors.py ├── findfactorsfor.py ├── indefinite.py ├── iterativecounttofive.py ├── nocontinueexample.py ├── permuteabc.py ├── permuteabcd.py ├── powers10loop.py ├── printprimes.py ├── printprimesfor.py ├── printprimesforelse.py ├── startree.py ├── startreefor.py ├── stopatone.py ├── stopatonefixed.py ├── stringletters.py ├── stringliteralletters.py ├── timestable1.py ├── timestable2.py ├── timestable3.py ├── timestable4.py ├── troubleshootloop.py ├── troubleshootloop2.py ├── whileelse.py ├── whileexitattop.py └── whilenoelse.py ├── Chap6 ├── addintegers4.py ├── boxturtle.py ├── countdown.py ├── die.py ├── enterarith.py ├── evalfunc.py ├── exitprogram.py ├── measureprimespeed.py ├── moreefficientprimes.py ├── myinterpreter.py ├── noanimation.py ├── octogon.py ├── octogon2.py ├── orbitdist.py ├── randomstring.py ├── simplerandom.py ├── speedvsdelay.py ├── standardsquareroot.py ├── timeaddition.py ├── timeit.py ├── timemoreefficientprimes.py └── usingsqrt.py ├── Chap7 ├── badfloatcheck.py ├── betterdie.py ├── betterinputfunc.py ├── calculator.py ├── countto10.py ├── countto10func.py ├── countton.py ├── countwithvariable.py ├── customsquareroot.py ├── docgcd.py ├── doublenumber.py ├── floatequalsfunction.py ├── gcdfunc.py ├── gcdfuncbad.py ├── gcdprog.py ├── gcdwithmain.py ├── localplay.py ├── midpoint.py ├── noduplication.py ├── parampassing.py ├── primefunc.py ├── regularpolygon.py ├── simplefloataddition.py ├── squarerootcomparison.py └── treefunc.py ├── Chap8 ├── arithmeticeval.py ├── boxmeasure.py ├── closurein.py ├── comparerolls.py ├── decorator.py ├── derivative.py ├── dot3x3logic.py ├── dot3x3text.py ├── dot3x3turtle.py ├── enhancedpolygon.py ├── factorialtest.py ├── forgenerator.py ├── funcmemory.py ├── gcd.py ├── generatedprimes.py ├── globalcalculator.py ├── localcounter.py ├── makeadder.py ├── myrange.py ├── nonrecursfact.py ├── placesquares.py ├── plotter.py ├── poorlydecorated.py ├── primecode.py ├── regulargenerator.py ├── simpledecorator.py ├── trackmouse.py ├── undecorated.py ├── usingprimecode.py ├── usingprimecode2.py └── yieldsequence.py ├── Chap9 ├── boxturtleobject.py ├── buttontester.py ├── convertupper.py ├── fractionassign.py ├── fractionplay.py ├── multiturtle.py ├── numbersaver.py ├── octogonobject.py ├── printcharacters.py ├── rjustprog.py ├── runconvert.py ├── simplefileread.py ├── simplerread.py ├── stringupper.py ├── stripandcount.py └── tkinterlight.py └── README.md /Chap1/arrow.py: -------------------------------------------------------------------------------- 1 | print(" * ") 2 | print(" *** ") 3 | print(" ***** ") 4 | print(" * ") 5 | print(" * ") 6 | print(" * ") 7 | -------------------------------------------------------------------------------- /Chap1/simple.py: -------------------------------------------------------------------------------- 1 | print("This is a simple Python program") 2 | -------------------------------------------------------------------------------- /Chap10/averagenumbers.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | print("Please enter five numbers: ") 3 | # Allow the user to enter in the five values. 4 | n1 = float(input("Please enter number 1: ")) 5 | n2 = float(input("Please enter number 2: ")) 6 | n3 = float(input("Please enter number 3: ")) 7 | n4 = float(input("Please enter number 4: ")) 8 | n5 = float(input("Please enter number 5: ")) 9 | print("Numbers entered:", n1, n2, n3, n4, n5) 10 | print("Average:", (n1 + n2 + n3 + n4 + n5)/5) 11 | 12 | 13 | main() 14 | -------------------------------------------------------------------------------- /Chap10/averagenumbers2.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | sum = 0.0 3 | NUMBER_OF_ENTRIES = 5 4 | print("Please enter", NUMBER_OF_ENTRIES, " numbers: ") 5 | for i in range(0, NUMBER_OF_ENTRIES): 6 | num = float(input("Enter number " + str(i) + ": ")) 7 | sum += num 8 | print("Average:", sum/NUMBER_OF_ENTRIES) 9 | 10 | 11 | main() 12 | -------------------------------------------------------------------------------- /Chap10/badreverse.py: -------------------------------------------------------------------------------- 1 | def make_list(): 2 | """ 3 | Builds a list from input provided by the user. 4 | """ 5 | result = [] # List to return is initially empty 6 | in_val = 0 # Ensure loop is entered at least once 7 | while in_val >= 0: 8 | in_val = int(input("Enter integer (-1 quits): ")) 9 | if in_val >= 0: 10 | result = result + [in_val] # Add item to list 11 | return result 12 | 13 | 14 | def main(): 15 | col = make_list() 16 | # Print the list in reverse 17 | for i in range(len(col), 0, -1): 18 | print(col[i], end=" ") 19 | print() 20 | 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /Chap10/builduserlist.py: -------------------------------------------------------------------------------- 1 | # Build a custom list of nonnegative integers specified by the user 2 | 3 | def make_list(): 4 | """ 5 | Builds a list from input provided by the user. 6 | """ 7 | result = [] # List to return is initially empty 8 | in_val = 0 # Ensure loop is entered at least once 9 | while in_val >= 0: 10 | in_val = int(input("Enter integer (-1 quits): ")) 11 | if in_val >= 0: 12 | result += [in_val] # Add item to list 13 | return result 14 | 15 | 16 | def main(): 17 | col = make_list() 18 | print(col) 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /Chap10/cmdlineargs.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | for arg in sys.argv: 4 | print('[' + arg + ']') 5 | -------------------------------------------------------------------------------- /Chap10/factorpairs.py: -------------------------------------------------------------------------------- 1 | n = int(input("Please enter a positive integer: ")) 2 | factors = [(x, n//x) for x in range(1, n + 1) if n % x == 0] 3 | print("Factor pairs of", n, ":", factors) 4 | -------------------------------------------------------------------------------- /Chap10/factorsingles.py: -------------------------------------------------------------------------------- 1 | n = int(input("Please enter a positive integer: ")) 2 | factors = [x for x in range(1, n + 1) if n % x == 0] 3 | print("Factors of", n, ":", factors) 4 | -------------------------------------------------------------------------------- /Chap10/fasterprimes.py: -------------------------------------------------------------------------------- 1 | # Display the prime numbers between 2 and 500 2 | 3 | # Largest potential prime considered 4 | MAX = 500 5 | 6 | def main(): 7 | # Each position in the Boolean list indicates 8 | # if the number of that position is not prime: 9 | # false means "prime," and true means "composite." 10 | # Initially all numbers are prime until proven otherwise 11 | nonprimes = MAX * [False] # Initialize to all False 12 | 13 | # First prime number is 2; 0 and 1 are not prime 14 | nonprimes[0] = nonprimes[1] = True 15 | 16 | # Start at the first prime number, 2. 17 | for i in range(2, MAX + 1): 18 | # See if i is prime 19 | if not nonprimes[i]: 20 | print(i, end=" ") 21 | # It is prime, so eliminate all of its 22 | # multiples that cannot be prime 23 | for j in range(2*i, MAX + 1, i) 24 | nonprimes[j] = True 25 | print() # Move cursor down to next line 26 | -------------------------------------------------------------------------------- /Chap10/generator2list.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | def is_prime(n): 4 | """ Returns True if nonnegative integer n is prime; 5 | otherwise, returns false """ 6 | if n == 2: # 2 is the only even prime number 7 | return True 8 | if n < 2 or n % 2 == 0: # Handle simple cases immediately 9 | return False # No evens and nothing less than 2 10 | trial_factor = 3 11 | root = sqrt(n) 12 | while trial_factor <= root: 13 | if n % trial_factor == 0: # Is trial factor a factor? 14 | return False # Yes, return right away 15 | trial_factor += 2 # Next potential factor, skip evens 16 | return True # Tried them all, must be prime 17 | 18 | 19 | def prime_sequence(begin, end): 20 | """ Generates the sequence of prime numbers between begin and end. """ 21 | for value in range(begin, end + 1): 22 | if is_prime(value): # See if value is prime 23 | yield value # Produce the prime number 24 | 25 | 26 | def main(): 27 | """ Make a list from a generator """ 28 | # Build the list of prime numbers in the range 20 to 50 29 | primes = list(prime_sequence(20, 50)) 30 | print(primes) 31 | 32 | 33 | if __name__ == '__main__': 34 | main() # Run the program 35 | -------------------------------------------------------------------------------- /Chap10/generatorexpression.py: -------------------------------------------------------------------------------- 1 | for val in (2**x for x in range(10)): 2 | print(val, end=' ') 3 | print() 4 | 5 | -------------------------------------------------------------------------------- /Chap10/heterolist.py: -------------------------------------------------------------------------------- 1 | collection = [24.2, 4, 'word', print, 19, -0.03, 'end'] 2 | print(collection[0]) 3 | print(collection[1]) 4 | print(collection[2]) 5 | print(collection[3]) 6 | print(collection[4]) 7 | print(collection[5]) 8 | print(collection[6]) 9 | print(collection) 10 | -------------------------------------------------------------------------------- /Chap10/heterolistfor.py: -------------------------------------------------------------------------------- 1 | collection = [24.2, 4, 'word', print, 19, -0.03, 'end'] 2 | for item in collection: 3 | print(item) # Print each element 4 | -------------------------------------------------------------------------------- /Chap10/heterolistforindex.py: -------------------------------------------------------------------------------- 1 | collection = [24.2, 4, 'word', print, 19, -0.03, 'end'] 2 | for i in range(len(collection)): # Not the preferred way to traverse a list 3 | print(collection[i]) # Print each element 4 | -------------------------------------------------------------------------------- /Chap10/listalias.py: -------------------------------------------------------------------------------- 1 | a = [10, 20, 30, 40] 2 | b = a 3 | print('a =', a) 4 | print('b =', b) 5 | b[2] = 35 6 | print('a =', a) 7 | print('b =', b) 8 | -------------------------------------------------------------------------------- /Chap10/listassignment.py: -------------------------------------------------------------------------------- 1 | a = [10, 20, 30, 40] 2 | b = [10, 20, 30, 40] 3 | print('a =', a) 4 | print('b =', b) 5 | b[2] = 35 6 | print('a =', a) 7 | print('b =', b) 8 | -------------------------------------------------------------------------------- /Chap10/listaverage.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | # Set up variables 3 | sum = 0.0 4 | NUMBER_OF_ENTRIES = 5 5 | numbers = [] 6 | 7 | # Get input from user 8 | print("Please enter", NUMBER_OF_ENTRIES, "numbers: ") 9 | for i in range(0, NUMBER_OF_ENTRIES): 10 | num = float(input("Enter number " + str(i) + ": ")) 11 | numbers += [num] 12 | sum += num 13 | 14 | # Print the numbers entered 15 | print(end="Numbers entered: ") 16 | for num in numbers: 17 | print(num, end=" ") 18 | print() # Print newline 19 | 20 | # Print average 21 | print("Average:", sum/NUMBER_OF_ENTRIES) 22 | 23 | 24 | main() # Execute main 25 | -------------------------------------------------------------------------------- /Chap10/listcopy.py: -------------------------------------------------------------------------------- 1 | def list_copy(lst): 2 | result = [] 3 | for item in lst: 4 | result += [item] 5 | return result 6 | 7 | 8 | def main(): 9 | # a and b are distinct lists that contain the same elements 10 | a = [10, 20, 30, 40] 11 | b = list_copy(a) # Make a copy of a 12 | print('a =', a, ' b =', b) 13 | 14 | print('Is ', a, ' equal to ', b, '?', sep='', end=' ') 15 | print(a == b) 16 | 17 | print('Are ', a, ' and ', b, ' aliases?', sep='', end=' ') 18 | print(a is b) 19 | 20 | b[2] = 35 # Change an element of b 21 | print('a =', a, ' b =', b) 22 | 23 | 24 | main() 25 | -------------------------------------------------------------------------------- /Chap10/listequivalence.py: -------------------------------------------------------------------------------- 1 | # a and b are distinct lists that contain the same elements 2 | a = [10, 20, 30, 40] 3 | b = [10, 20, 30, 40] 4 | print('Is ', a, ' equal to ', b, '?', sep='', end=' ') 5 | print(a == b) 6 | 7 | print('Are ', a, ' and ', b, ' aliases?', sep='', end=' ') 8 | print(a is b) 9 | 10 | # c and d alias are distinct lists that contain the same elements 11 | c = [100, 200, 300, 400] 12 | d = c # Makes d an alias of c 13 | print('Is ', c, ' equal to ', d, '?', sep='', end=' ') 14 | print(c == d) 15 | 16 | print('Are ', c, ' and ', d, ' aliases?', sep='', end=' ') 17 | print(c is d) 18 | -------------------------------------------------------------------------------- /Chap10/listfunc.py: -------------------------------------------------------------------------------- 1 | def sum(lst): 2 | """ 3 | Adds up the contents of a list of numeric values. 4 | lst is the list to sum. 5 | Returns the sum of all the elements or zero if the list is empty. 6 | """ 7 | result = 0 8 | for item in lst: 9 | result += item 10 | return result 11 | 12 | 13 | def make_zero(lst): 14 | """ 15 | Makes every element in list lst zero 16 | """ 17 | for i in range(len(lst)): 18 | lst[i] = 0 19 | 20 | 21 | def random_list(n): 22 | """ 23 | Builds a list of n integers, where each integer 24 | is a pseudorandom number in the range 0...99. 25 | Returns the random list. 26 | """ 27 | import random 28 | result = [] 29 | for i in range(n): 30 | rand = random.randrange(100) 31 | result += [rand] 32 | return result 33 | 34 | 35 | def main(): 36 | a = [2, 4, 6, 8] 37 | # Print the contents of the list 38 | print(a) 39 | # Compute and display sum 40 | print(sum(a)) 41 | # Zero out all the elements of list 42 | make_zero(a) 43 | # Reprint the contents of the list 44 | print(a) 45 | # Compute and display sum 46 | print(sum(a)) 47 | # Test empty list 48 | a = [] 49 | print(a) 50 | print(sum(a)) 51 | # Test pseudorandom list with 10 elements 52 | a = random_list(10) 53 | print(a) 54 | print(sum(a)) 55 | 56 | 57 | main() 58 | -------------------------------------------------------------------------------- /Chap10/listmembership.py: -------------------------------------------------------------------------------- 1 | lst = list(range(0, 21, 2)) 2 | for i in range(-2, 23): 3 | if i in lst: 4 | print(i, 'is a member of', lst) 5 | if i not in lst: 6 | print(i, 'is NOT a member of', lst) 7 | -------------------------------------------------------------------------------- /Chap10/listslice.py: -------------------------------------------------------------------------------- 1 | lst = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] 2 | print(lst) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] 3 | print(lst[0:3]) # [10, 20, 30] 4 | print(lst[4:8]) # [50, 60, 70, 80] 5 | print(lst[2:5]) # [30, 40, 50] 6 | print(lst[-5:-3]) # [80, 90] 7 | print(lst[:3]) # [10, 20, 30] 8 | print(lst[4:]) # [50, 60, 70, 80, 90, 100, 110, 120] 9 | print(lst[:]) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120] 10 | print(lst[-100:3]) # [10, 20, 30] 11 | print(lst[4:100]) # [50, 60, 70, 80, 90, 100, 110, 120] 12 | print(lst[2:-2:2]) # [30, 50, 70, 90] 13 | print(lst[::2]) # [10, 30, 50, 70, 90, 110] 14 | print(lst[::-1]) # [120, 110, 100, 90, 80, 70, 60, 50, 40, 30, 20, 10] 15 | -------------------------------------------------------------------------------- /Chap10/listslicemod.py: -------------------------------------------------------------------------------- 1 | lst = [10, 20, 30, 40, 50, 60, 70, 80] 2 | print(lst) # Print the list 3 | lst[2:5] = ['a', 'b', 'c'] # Replace [30, 40, 50] segment with ['a', 'b', 'c'] 4 | print(lst) 5 | print('==================') 6 | lst = [10, 20, 30, 40, 50, 60, 70, 80] 7 | print(lst) # Print the list 8 | lst[2:6] = ['a', 'b'] # Replace [30, 40, 50, 60] segment with ['a', 'b'] 9 | print(lst) 10 | print('==================') 11 | lst = [10, 20, 30, 40, 50, 60, 70, 80] 12 | print(lst) # Print the list 13 | lst[2:2] = ['a', 'b', 'c'] # Insert ['a', 'b', 'c'] segment at index 2 14 | print(lst) 15 | print('==================') 16 | lst = [10, 20, 30, 40, 50, 60, 70, 80] 17 | print(lst) # Print the list 18 | lst[2:5] = [] # Replace [30, 40, 50] segment with [] (delete the segment) 19 | print(lst) 20 | -------------------------------------------------------------------------------- /Chap10/makeintegerlists.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | a = list(range(0, 10)) 3 | print(a) 4 | a = list(range(10, -1, -1)) 5 | print(a) 6 | a = list(range(0, 100, 10)) 7 | print(a) 8 | a = list(range(-5, 6)) 9 | print(a) 10 | 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /Chap10/makeuniformlists.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | a = [0] * 10 3 | print(a) 4 | 5 | a = [3.4] * 5 6 | print(a) 7 | 8 | a = 3 * ['ABC'] 9 | print(a) 10 | 11 | a = 4 * [10, 20, 30] 12 | print(a) 13 | 14 | n = 3 # Use a variable multiplier 15 | a = n * ['abc', 22, 8.7] 16 | print(a) 17 | 18 | main() 19 | -------------------------------------------------------------------------------- /Chap10/negindex.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | data = [10, 20, 30, 40, 50, 60] 3 | 4 | # Print the individual elements with negative indices 5 | print(data[-1]) 6 | print(data[-2]) 7 | print(data[-3]) 8 | print(data[-4]) 9 | print(data[-5]) 10 | print(data[-6]) 11 | 12 | main() # Execute main 13 | -------------------------------------------------------------------------------- /Chap10/prefixsuffix.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3, 4, 5, 6, 7, 8] 2 | print('Prefixes of', a) 3 | for i in range(0, len(a) + 1): 4 | print('<', a[0:i], '>', sep='') 5 | print('----------------------------------') 6 | print('Suffixes of', a) 7 | for i in range(0, len(a) + 1): 8 | print('<', a[i:len(a) + 1], '>', sep='') 9 | -------------------------------------------------------------------------------- /Chap10/prettyprint2d.py: -------------------------------------------------------------------------------- 1 | matrix = [[100, 14, 8, 22, 71], 2 | [ 0, 243, 68, 1, 30], 3 | [ 90, 21, 7, 67, 112], 4 | [115, 200, 70, 150, 8]] 5 | 6 | for row in matrix: # Process each row 7 | for elem in row: # For each element in a given row 8 | print('{:>4}'.format(elem), end='') 9 | print() 10 | -------------------------------------------------------------------------------- /Chap10/rangetolist.py: -------------------------------------------------------------------------------- 1 | print(list(range(11))) 2 | print(list(range(10, 101, 10))) 3 | print(list(range(10, -1, -1))) 4 | -------------------------------------------------------------------------------- /Chap10/reversals.py: -------------------------------------------------------------------------------- 1 | lst = [1, 2, 3, 4, 5, 6, 7] 2 | print("---- Original list ----") 3 | print("lst =", lst) 4 | print("---- reversed function----") 5 | obj1 = reversed(lst) 6 | print("lst =", lst) 7 | print("obj1 =", obj1) 8 | print("---- Slice ----") 9 | obj2 = lst[::-1] 10 | print("lst =", lst) 11 | print("obj2 =", obj2) 12 | print("---- list.reverse method ----") 13 | obj3 = lst.reverse() 14 | print("lst =", lst) 15 | print("obj3 =", obj3) 16 | -------------------------------------------------------------------------------- /Chap10/sqrtcmdline.py: -------------------------------------------------------------------------------- 1 | from sys import argv 2 | from math import sqrt 3 | 4 | if len(argv) < 3: 5 | print('Supply range of values') 6 | else: 7 | for n in range(int(argv[1]), int(argv[2]) + 1): 8 | print(n, sqrt(n)) 9 | print() 10 | -------------------------------------------------------------------------------- /Chap10/threedlist.py: -------------------------------------------------------------------------------- 1 | 2 | # Make a 3D matrix representing the intermediate state 3 | # of a 3D Tic-Tac-Toe game in progress. 4 | 5 | matrix = [[['X', '.', '.', 'O'], 6 | ['.', '.', '.', '.'], 7 | ['.', '.', '.', '.'], 8 | ['.', '.', '.', '.']], 9 | [['.', '.', '.', 'O'], 10 | ['.', 'X', '.', '.'], 11 | ['.', '.', '.', '.'], 12 | ['.', '.', '.', '.']], 13 | [['.', '.', '.', '.'], 14 | ['.', '.', '.', '.'], 15 | ['.', '.', 'X', '.'], 16 | ['.', '.', '.', '.']], 17 | [['.', '.', '.', '.'], 18 | ['.', '.', '.', '.'], 19 | ['.', '.', '.', '.'], 20 | ['.', '.', '.', 'O']]] 21 | 22 | 23 | # Pretty print the matrix 24 | # Need the length of a row in order to adjust the indentation 25 | row_length = len(matrix[0][0]) 26 | for layer in matrix: # Process each layer 27 | for row in range(len(layer)): # For each row by its index 28 | print(' ' * (row_length - row), end='') # Print diminishing offset based on its index 29 | for column in range(len(layer[row])): # For each element in a given row 30 | print('{:>4}'.format(layer[row][column]), end='') 31 | print() 32 | print() 33 | -------------------------------------------------------------------------------- /Chap10/uniquefactorpairs.py: -------------------------------------------------------------------------------- 1 | import math 2 | n = int(input("Please enter a positive integer: ")) 3 | factors = [(x, n//x) for x in range(1, round(math.sqrt(n)) + 1) if n % x == 0] 4 | print("Factor pairs of", n, ":", factors) 5 | -------------------------------------------------------------------------------- /Chap11/add2or3.py: -------------------------------------------------------------------------------- 1 | def sum(a, b, c=0): 2 | return a + b + c # Adding zero will not affect a + b 3 | 4 | 5 | print(sum(3, 4)) 6 | print(sum(3, 4, 5)) 7 | -------------------------------------------------------------------------------- /Chap11/addmany.py: -------------------------------------------------------------------------------- 1 | def sum(*nums): 2 | s = 0 # Initialize sum to zero 3 | for num in nums: # Consider each argument passed to the function 4 | s += num # Accumulate their values 5 | return s # Return the sum 6 | 7 | 8 | print(sum(3, 4)) 9 | print(sum(3, 4, 5)) 10 | print(sum(3, 3, 3, 3, 4, 1, 9, 44, -2, 8, 8)) 11 | -------------------------------------------------------------------------------- /Chap11/addmanyaugmented.py: -------------------------------------------------------------------------------- 1 | def sum(*nums): 2 | print(nums) # See what nums really is 3 | s = 0 # Initialize sum to zero 4 | for num in nums: # Consider each argument passed to the function 5 | s += num # Accumulate their values 6 | return s # Return the sum 7 | 8 | 9 | print(sum(3, 4)) 10 | print(sum(3, 4, 5)) 11 | print(sum(3, 3, 3, 3, 4, 1, 9, 44, -2, 8, 8)) 12 | -------------------------------------------------------------------------------- /Chap11/callerkeyword.py: -------------------------------------------------------------------------------- 1 | def f(a, b, c): 2 | print('a =', a, ' b =', b, ' c =', c) 3 | 4 | 5 | f(1, 2, 3) # Pass three parameters 6 | dict = {} 7 | dict['b'] = 22 8 | dict['a'] = 11 9 | dict['c'] = 33 10 | f(**dict) 11 | f(**{'a':10, 'b':20, 'c':30}) # Pass a dictionary 12 | -------------------------------------------------------------------------------- /Chap11/enum.py: -------------------------------------------------------------------------------- 1 | lst = [10, 20, 30, 40, 50] 2 | t = 100, 200, 300, 400, 500 3 | d = {"A": 4, "B": 18, "C": 0, "D": 3} 4 | s = {1000, 2000, 3000, 4000, 5000} 5 | print(lst) 6 | print(t) 7 | print(d) 8 | print(s) 9 | for x in enumerate(lst): 10 | print(x, end=" ") 11 | print() 12 | for x in enumerate(t): 13 | print(x, end=" ") 14 | print() 15 | for x in enumerate(d): 16 | print(x, end=" ") 17 | print() 18 | for x in enumerate(s): 19 | print(x, end=" ") 20 | print() 21 | 22 | 23 | def gen(n): 24 | """ Generate n, n - 2, n - 3, ..., 0. """ 25 | for i in range(n, -1, -2): 26 | yield i 27 | 28 | 29 | for x in enumerate(gen(20)): 30 | print(x, end=" ") 31 | print() 32 | 33 | # Optionally specify beginning index 34 | for x in enumerate(t, 1): 35 | print(x, end=" ") 36 | print() 37 | -------------------------------------------------------------------------------- /Chap11/groupwords.py: -------------------------------------------------------------------------------- 1 | """ Uses a dictionary to group the words in a text file according to 2 | their length (number of letters). """ 3 | 4 | import sys # For argv global command line arguments list 5 | 6 | 7 | def main(): 8 | """ Group the words by length in a text file. """ 9 | if len(sys.argv) < 2: # Did the user not supply a file name? 10 | print('Usage: python groupwords.py ') 11 | print(' where is the name of a text file.') 12 | else: # User provided file name 13 | filename = sys.argv[1] 14 | groups = {} # Initialize grouping dictionary 15 | with open(filename, 'r') as f: # Open the file for reading 16 | content = f.read() # Read in content of the entire file 17 | words = content.split() # Make list of individual words 18 | for word in words: 19 | word = word.upper() # Make the word all caps 20 | # Compute the word's length 21 | size = len(word) 22 | if size in groups: 23 | if word not in groups[size]: # Avoid duplicates 24 | groups[size] += [word] # Add the word to its group 25 | else: 26 | groups[size] = [word] # Add the word to a new group 27 | # Show the groups 28 | for size, group in groups.items(): 29 | print(size, ':', group) 30 | 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /Chap11/groupwordslist.py: -------------------------------------------------------------------------------- 1 | """ Uses a list to group the words from a text file according to 2 | their length (number of letters). """ 3 | 4 | import sys # For argv global command line arguments list 5 | 6 | 7 | def main(): 8 | """ Group the words by length in a text file. """ 9 | if len(sys.argv) < 2: # Did the user not supply a file name? 10 | print('Usage: python groupwordslist.py ') 11 | print(' where is the name of a text file.') 12 | else: # User provided file name 13 | filename = sys.argv[1] 14 | groups = [] # Initialize grouping list 15 | for i in range(20): 16 | groups.append(set()) # Add new empty set to the list 17 | with open(filename, 'r') as f: # Open the file for reading 18 | content = f.read() # Read in content of the entire file 19 | words = content.split() # Make list of individual words 20 | for word in words: 21 | word = word.upper() # Make the word all caps 22 | # Compute the word's length 23 | size = len(word) 24 | groups[size].add(word) 25 | # Show the groups 26 | for size, group in enumerate(groups): 27 | print(size, ':', group) 28 | 29 | 30 | if __name__ == '__main__': 31 | main() 32 | -------------------------------------------------------------------------------- /Chap11/namedparams.py: -------------------------------------------------------------------------------- 1 | def process(a, b, c): 2 | print('a =', a, ' b =', b, ' c =', c) 3 | 4 | 5 | x = 14 6 | process(1, 2, 3) 7 | process(a=10, b=20, c=30) 8 | process(b=200, c=300, a=100) 9 | process(c=3000, a=1000, b=2000) 10 | process(10000, c=30000, b=20000) 11 | -------------------------------------------------------------------------------- /Chap11/phonelist.py: -------------------------------------------------------------------------------- 1 | contacts = {} # The global telephone contact list 2 | 3 | running = True 4 | 5 | while running: 6 | command = input('A)dd D)elete L)ook up Q)uit: ') 7 | if command == 'A' or command == 'a' : 8 | name = input('Enter new name:') 9 | print('Enter phone number for', name, end=':') 10 | number = input() 11 | contacts[name] = number 12 | elif command == 'D' or command == 'd': 13 | name = input('Enter name to delete :') 14 | del contacts[name] 15 | elif command == 'L' or command == 'l': 16 | name = input('Enter name :') 17 | print(name, contacts[name]) 18 | elif command == 'Q' or command == 'q': 19 | running = False 20 | elif command == 'dump': # Secret command 21 | print(contacts) 22 | else: 23 | print(command, 'is not a valid command') 24 | -------------------------------------------------------------------------------- /Chap11/readtextfile.py: -------------------------------------------------------------------------------- 1 | def readfile(filename): 2 | """ Read the comma-separated integer data from the text file 3 | named filename and return the data in a list. """ 4 | result = [] # List initially empty 5 | with open(filename, "r") as f: 6 | for line in f: 7 | # Remove any trailing spaces, comma, and newline 8 | result += [int(x.strip()) for x in line.rstrip(" ,\n").split(",")] 9 | return result 10 | 11 | 12 | def main(): 13 | lst = readfile("monitor.data") 14 | print(lst) 15 | 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /Chap11/setvslistaccess.py: -------------------------------------------------------------------------------- 1 | # Data structure size 2 | size = 1000 3 | 4 | # Make a big set 5 | S = {x**2 for x in range(size)} 6 | # Make a big list 7 | L = [x**2 for x in range(size)] 8 | 9 | # Verify the type of S and L 10 | print('Set:', type(S), ' List:', type(L)) 11 | 12 | from time import clock 13 | 14 | # Search size 15 | search_size = 1000000 16 | 17 | # Time list access 18 | start_time = clock() 19 | for i in range(search_size): 20 | if i in L: 21 | pass 22 | stop_time = clock() 23 | print('List elapsed:', stop_time - start_time) 24 | 25 | # Time set access 26 | start_time = clock() 27 | for i in range(search_size): 28 | if i in S: 29 | pass 30 | stop_time = clock() 31 | print('Set elapsed:', stop_time - start_time) 32 | -------------------------------------------------------------------------------- /Chap11/speciallistprinting.py: -------------------------------------------------------------------------------- 1 | lst = [2*i for i in range(6)] 2 | 3 | # Typical list printing 4 | print(lst) 5 | 6 | # Print just the list elements 7 | print(*lst) 8 | 9 | # Print the list in a special way 10 | print(*lst, sep=" and ", end="--that's all folks!\n") 11 | -------------------------------------------------------------------------------- /Chap11/translatedictionary.py: -------------------------------------------------------------------------------- 1 | translator = {'uno':'one', 2 | 'dos':'two', 3 | 'tres':'three', 4 | 'cuatro':'four', 5 | 'cinco':'five', 6 | 'seis':'six', 7 | 'siete':'seven', 8 | 'ocho':'eight'} 9 | word = '*' 10 | while word != '': # Loop until user presses return by itself 11 | # Obtain word from the user 12 | word = input('Enter Spanish word:') 13 | if word in translator: 14 | print(translator[word]) 15 | else: 16 | print('???') # Unknown word 17 | -------------------------------------------------------------------------------- /Chap11/translateif.py: -------------------------------------------------------------------------------- 1 | word = '*' # Initial word to ensure loop entry 2 | while word != '': # Loop until user presses return by itself 3 | # Obtain word from the user 4 | word = input('Enter Spanish word:') 5 | if word == 'uno': 6 | print('one') 7 | elif word == 'dos': 8 | print('two') 9 | elif word == 'tres': 10 | print('three') 11 | elif word == 'cuatro': 12 | print('four') 13 | elif word == 'cinco': 14 | print('five') 15 | elif word == 'seis': 16 | print('six') 17 | elif word == 'siete': 18 | print('seven') 19 | elif word == 'ocho': 20 | print('eight') 21 | else: # Unknown word 22 | print('???') 23 | -------------------------------------------------------------------------------- /Chap11/tupletest.py: -------------------------------------------------------------------------------- 1 | my_list = [1, 2, 3, 4, 5, 6, 7] # Make a list 2 | my_tuple = (1, 2, 3, 4, 5, 6, 7) # Make a tuple 3 | print('The list:', my_list) # Print the list 4 | print('The tuple:', my_tuple) # Print the tuple 5 | print('The first element in the list:', my_list[0]) # Access an element 6 | print('The first element in the tuple:', my_tuple[0]) # Access an element 7 | print('All the elements in the list:', end=' ') 8 | for elem in my_list: # Iterate over the elements of a list 9 | print(elem, end=' ') 10 | print() 11 | print('All the elements in the tuple:', end=' ') 12 | for elem in my_tuple: # Iterate over the elements of a tuple 13 | print(elem, end=' ') 14 | print() 15 | print('List slice:', my_list[2:5]) # Slice a list 16 | print('Tuple slice:', my_tuple[2:5]) # Slice a tuple 17 | print('Try to modify the first element in the list . . .') 18 | my_list[0] = 9 # Modify the list 19 | print('The list:', my_list) 20 | print('Try to modify the first element in the list . . .') 21 | my_tuple[0] = 9 # Is tuple modification possible? 22 | print('The tuple:', my_tuple) 23 | -------------------------------------------------------------------------------- /Chap11/wordcount.py: -------------------------------------------------------------------------------- 1 | """ Uses a dictionary to count the number of occurrences of each 2 | word in a text file. """ 3 | 4 | import sys # For sys.argv global command line arguments list 5 | 6 | 7 | def main(): 8 | """ Counts the words in a text file. """ 9 | if len(sys.argv) < 2: # Did the user not supply a file name? 10 | print('Usage: python wordcount ') 11 | print(' where is the name of a text file.') 12 | else: # User provided file name 13 | filename = sys.argv[1] 14 | counters = {} # Initialize counting dictionary 15 | with open(filename, 'r') as f: # Open the file for reading 16 | content = f.read() # Read in content of the entire file 17 | words = content.split() # Make list of individual words 18 | for word in words: 19 | word = word.upper() # Make the word all caps 20 | if word not in counters: 21 | counters[word] = 1 # First occurrence, add the counter 22 | else: 23 | counters[word] += 1 # Increment existing counter 24 | # Report the counts for each word 25 | for word, count in counters.items(): 26 | print(word, count) 27 | 28 | 29 | if __name__ == '__main__': 30 | main() 31 | -------------------------------------------------------------------------------- /Chap11/zipseq.py: -------------------------------------------------------------------------------- 1 | def gen(n): 2 | """ Generates the first n perfect squares, starting with zero: 3 | 0, 1, 4, 9, 16,..., (n - 1)^2. """ 4 | for i in range(n): 5 | yield i**2 6 | 7 | 8 | for p in zip([10, 20, 30, 40, 50, 60], gen(4)): 9 | print(p, end=' ') 10 | print() 11 | -------------------------------------------------------------------------------- /Chap12/betterfileread.py: -------------------------------------------------------------------------------- 1 | # Sum the values in a text file containing integers 2 | try: 3 | with open('mydata.dat') as f: 4 | sum = 0 5 | try: 6 | for line in f: 7 | sum += int(line) 8 | except Exception as er: 9 | print(er) # Show the problem 10 | print('sum =', sum) 11 | except OSError: 12 | print('Could not open file') 13 | -------------------------------------------------------------------------------- /Chap12/catchallexcept.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | for i in range(10): # Loop 10 times 4 | print('Beginning of loop iteration', i) 5 | try: 6 | r = random.randint(1, 4) # r is pseudorandomly 1, 2, 3, or 4 7 | if r == 1: 8 | print(int('Fred')) # Try to convert a non-integer 9 | elif r == 2: 10 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 11 | elif r == 3: 12 | print({}[1]) # Try to use a nonexistent key to get an item from a dictionary 13 | else: 14 | print(3/0) # Try to divide by zero 15 | except ValueError: 16 | print('Cannot convert integer') 17 | except IndexError: 18 | print('List index is out of range') 19 | except ZeroDivisionError: 20 | print('Division by zero not allowed') 21 | except Exception: # Catch any other type of exception 22 | print('This program has encountered a problem') 23 | 24 | print('End of loop iteration', i) 25 | -------------------------------------------------------------------------------- /Chap12/checkforzero.py: -------------------------------------------------------------------------------- 1 | # Get two integers from the user 2 | print('Please enter two numbers to divide.') 3 | num1 = int(input('Please enter the dividend: ')) 4 | num2 = int(input('Please enter the divisor: ')) 5 | if num2 != 0: 6 | print('{0} divided by {1} = {2}'.format(num1, num2, num1/num2)) 7 | else: 8 | print('Cannot divide by zero') 9 | -------------------------------------------------------------------------------- /Chap12/dividenumbers.py: -------------------------------------------------------------------------------- 1 | # Get two integers from the user 2 | print('Please enter two numbers to divide.') 3 | num1 = int(input('Please enter the dividend: ')) 4 | num2 = int(input('Please enter the divisor: ')) 5 | print('{0} divided by {1} = {2}'.format(num1, num2, num1/num2)) 6 | -------------------------------------------------------------------------------- /Chap12/enterinteger.py: -------------------------------------------------------------------------------- 1 | val = int(input("Please enter a small positive integer: ")) 2 | print('You entered', val) 3 | -------------------------------------------------------------------------------- /Chap12/enterintexcept.py: -------------------------------------------------------------------------------- 1 | try: 2 | val = int(input("Please enter a small positive integer: ")) 3 | print('You entered', val) 4 | except ValueError: 5 | print('Input not accepted') 6 | -------------------------------------------------------------------------------- /Chap12/exceptobject.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | for i in range(10): # Loop 10 times 4 | print('Beginning of loop iteration', i) 5 | try: 6 | r = random.randint(1, 4) # r is pseudorandomly 1, 2, 3, or 4 7 | if r == 1: 8 | print(int('Fred')) # Try to convert a non-integer 9 | elif r == 2: 10 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 11 | elif r == 3: 12 | print({}[1]) # Try to use a nonexistent key to get an item from a dictionary 13 | else: 14 | print(3/0) # Try to divide by zero 15 | except ValueError as e: 16 | print('Problem with value ==>', type(e), e) 17 | except IndexError as e: 18 | print('Problem with list ==>', type(e), e) 19 | except ZeroDivisionError as e: 20 | print('Problem with division ==>', type(e), e) 21 | except Exception as e: 22 | print('Problem with something ==>', type(e), e) 23 | 24 | print('End of loop iteration', i) 25 | -------------------------------------------------------------------------------- /Chap12/filereadfinally.py: -------------------------------------------------------------------------------- 1 | # Sum the values in a text file containing integers 2 | try: 3 | f = open('mydata.dat') 4 | except OSError: 5 | print('Could not open file') 6 | else: 7 | sum = 0 8 | try: 9 | for line in f: 10 | sum += int(line) 11 | except Exception as er: 12 | print(er) # Show the problem 13 | finally: 14 | f.close() # Close the file 15 | print('sum =', sum) 16 | -------------------------------------------------------------------------------- /Chap12/makeintegerlist.py: -------------------------------------------------------------------------------- 1 | def get_int_in_range(low, high): 2 | """ Obtains an integer value from the user. Acceptable values 3 | must fall within the specified range low...high. """ 4 | val = int(input()) # Can raise a ValueError 5 | while val < low or val > high: 6 | print('Value out of range, please try again:', end=' ') 7 | val = int(input()) # Can raise a ValueError 8 | return val 9 | 10 | 11 | def create_list(n, min, max): 12 | """ Allows the user to create a list of n elements consisting 13 | of integers in the range min...max """ 14 | result = [] 15 | while n > 0: # Count down to zero 16 | print('Enter integer in the range {}...{}:'.format(min, max), end=' ') 17 | result.append(get_int_in_range(min, max)) 18 | n -= 1 19 | return result 20 | 21 | 22 | def main(): 23 | """ Create a list of two elements supplied by the user, 24 | each element in the range 10...20 """ 25 | lst = create_list(2, 10, 20) 26 | print(lst) 27 | 28 | 29 | if __name__ == '__main__': 30 | main() # Invoke main 31 | -------------------------------------------------------------------------------- /Chap12/makeintegerlist2.py: -------------------------------------------------------------------------------- 1 | def get_int_in_range(low, high): 2 | """ Obtains an integer value from the user. Acceptable values 3 | must fall within the specified range low...high. """ 4 | val = int(input()) # Can raise a ValueError 5 | while val < low or val > high: 6 | print('Value out of range, please try again:', end=' ') 7 | val = int(input()) # Can raise a ValueError 8 | return val 9 | 10 | 11 | def create_list(n, min, max): 12 | """ Allows the user to create a list of n elements consisting 13 | of integers in the range min...max """ 14 | result = [] 15 | try: 16 | while n > 0: # Count down to zero 17 | print('Enter integer in the range {}...{}:'.format(min, max), end=' ') 18 | result.append(get_int_in_range(min, max)) 19 | n -= 1 20 | except ValueError: 21 | print('Disallowed user entry interrupted list creation') 22 | return result 23 | 24 | 25 | def main(): 26 | """ Create a list of two elements supplied by the user, 27 | each element in the range 10...20 """ 28 | lst = create_list(2, 10, 20) 29 | print(lst) 30 | 31 | 32 | if __name__ == '__main__': 33 | main() # Invoke main 34 | -------------------------------------------------------------------------------- /Chap12/missedexception.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | for i in range(10): # Loop 10 times 4 | print('Beginning of loop iteration', i) 5 | try: 6 | r = random.randint(1, 4) # r is pseudorandomly 1, 2, 3, or 4 7 | if r == 1: 8 | print(int('Fred')) # Try to convert a non-integer 9 | elif r == 2: 10 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 11 | elif r == 3: 12 | print({}[1]) # Try to use a nonexistent key to get an item from a dictionary 13 | else: 14 | print(3/0) # Try to divide by zero 15 | except ValueError: 16 | print('Cannot convert integer') 17 | except IndexError: 18 | print('List index is out of range') 19 | except ZeroDivisionError: 20 | print('Division by zero not allowed') 21 | 22 | print('End of loop iteration', i) 23 | -------------------------------------------------------------------------------- /Chap12/multiexcept.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | for i in range(10): # Loop 10 times 4 | print('Beginning of loop iteration', i) 5 | try: 6 | r = random.randint(1, 3) # r is pseudorandomly 1, 2, or 3 7 | if r == 1: 8 | print(int('Fred')) # Try to convert a non-integer 9 | elif r == 2: 10 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 11 | else: 12 | print(3/0) # Try to divide by zero 13 | except ValueError: 14 | print('Cannot convert integer') 15 | except IndexError: 16 | print('List index is out of range') 17 | except ZeroDivisionError: 18 | print('Division by zero not allowed') 19 | 20 | print('End of loop iteration', i) 21 | -------------------------------------------------------------------------------- /Chap12/multihandle.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | for i in range(10): # Loop 10 times 4 | print('Beginning of loop iteration', i) 5 | try: 6 | r = random.randint(1, 3) # r is pseudorandomly 1, 2, or 3 7 | if r == 1: 8 | print(int('Fred')) # Try to convert a non-integer 9 | elif r == 2: 10 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 11 | else: 12 | print(3/0) # Try to divide by zero 13 | except (ValueError, ZeroDivisionError): 14 | print('Problem with integer detected') 15 | except IndexError: 16 | print('List index is out of range') 17 | 18 | print('End of loop iteration', i) 19 | -------------------------------------------------------------------------------- /Chap12/nonnegconvert.py: -------------------------------------------------------------------------------- 1 | def non_neg_int(n): 2 | result = int(n) 3 | if result < 0: 4 | raise ValueError(result) 5 | return result 6 | 7 | 8 | while True: 9 | x = non_neg_int(input('Please enter a nonnegative integer:')) 10 | if x == 999: # Secret number exits loop 11 | break 12 | print('You entered', x) 13 | -------------------------------------------------------------------------------- /Chap12/nonnegexcept.py: -------------------------------------------------------------------------------- 1 | def non_neg_int(n): 2 | """ Converts argument n into a nonnegative integer, if possible. 3 | Raises a ValueError if the argument is not convertible 4 | to a nonnegative integer. """ 5 | result = int(n) 6 | if result < 0: 7 | raise ValueError(result) 8 | return result 9 | 10 | 11 | while True: 12 | try: 13 | x = non_neg_int(input('Please enter a nonnegative integer:')) 14 | if x == 999: # Secret number exits loop 15 | break 16 | print('You entered', x) 17 | except ValueError: 18 | print('The value you entered is not acceptable') 19 | -------------------------------------------------------------------------------- /Chap12/otherexcept.py: -------------------------------------------------------------------------------- 1 | try: 2 | val = int(input("Please enter a small positive integer: ")) 3 | print('You entered', val) 4 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 5 | except ValueError: 6 | print('Input not accepted') 7 | -------------------------------------------------------------------------------- /Chap12/reallycatchallexcept.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | for i in range(10): # Loop 10 times 4 | print('Beginning of loop iteration', i) 5 | try: 6 | r = random.randint(1, 4) # r is pseudorandomly 1, 2, 3, or 4 7 | if r == 1: 8 | print(int('Fred')) # Try to convert a non-integer 9 | elif r == 2: 10 | [][2] = 5 # Try to assign to a nonexistent index of the empty list 11 | elif r == 3: 12 | print({}[1]) # Try to use a nonexistent key to get an item from a dictionary 13 | else: 14 | print(3/0) # Try to divide by zero 15 | except ValueError: 16 | print('Cannot convert integer') 17 | except IndexError: 18 | print('List index is out of range') 19 | except ZeroDivisionError: 20 | print('Division by zero not allowed') 21 | except: # Catch absolutely any other type of exception 22 | print('This program has encountered a problem') 23 | 24 | print('End of loop iteration', i) 25 | -------------------------------------------------------------------------------- /Chap12/reraise.py: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | """ Returns True if nonnegative integer n is prime; 3 | otherwise, returns false. 4 | Raises a TypeError exception if n is not 5 | an integer. """ 6 | from math import sqrt 7 | if n == 2: # 2 is the only even prime number 8 | return True 9 | if n < 2 or n % 2 == 0: # Handle simple cases immediately 10 | return False # Raises a TypeError if n is not an integer 11 | trial_factor = 3 12 | root = sqrt(n) + 1 13 | while trial_factor <= root: 14 | if n % trial_factor == 0: # Is trial factor a factor? 15 | return False # Yes, return right away 16 | trial_factor += 2 # Next potential factor, skip evens 17 | return True # Tried them all, must be prime 18 | 19 | 20 | def non_neg(n): 21 | """ Determines if n is nonnegative. 22 | Raises a TypeError if n is not an integer. """ 23 | return n > 0 24 | 25 | 26 | 27 | def count_elements(lst, predicate): 28 | """ Counts the number of integers in list lst that are 29 | acceptable to a given predicate (Boolean function). 30 | Prints an error message and raises a type error if 31 | the list contains an element incompatible with 32 | the predicate. """ 33 | count = 0 34 | for x in lst: 35 | try: 36 | if predicate(x): 37 | count += 1 38 | except TypeError: 39 | print(x, 'is a not an acceptable element') 40 | raise # Re-raise the caught exception 41 | return count 42 | 43 | 44 | def main(): 45 | print(count_elements([3, -71, 22, -19, 2, 9], non_neg)) 46 | print(count_elements([2, 3, 4, 5, 6, 8, 9], is_prime)) 47 | print(count_elements([2, 4, '6', 8, 'x', 7], is_prime)) 48 | 49 | 50 | if __name__ == '__main__': 51 | main() 52 | -------------------------------------------------------------------------------- /Chap12/riskyread.py: -------------------------------------------------------------------------------- 1 | # Sum the values in a text file containing integer values 2 | sum = 0 3 | f = open('mydata.dat') 4 | for line in f: 5 | sum += int(line) 6 | f.close() # Close the file 7 | print(sum) 8 | -------------------------------------------------------------------------------- /Chap12/tryfileread.py: -------------------------------------------------------------------------------- 1 | # Sum the values in a text file containing integer values 2 | try: 3 | f = open('mydata.dat') 4 | except OSError: 5 | print('Could not open file') 6 | else: # File opened properly 7 | sum = 0 8 | try: 9 | for line in f: 10 | sum += int(line) 11 | f.close() # Close the file if no exception 12 | except Exception as er: 13 | print(er) # Show the problem 14 | f.close() # Close the file if exception 15 | print('sum =', sum) 16 | -------------------------------------------------------------------------------- /Chap12/trynoelse.py: -------------------------------------------------------------------------------- 1 | def fun1(): 2 | try: 3 | print('try code') 4 | except: 5 | print('exception handling code') 6 | else: 7 | print('no exception raised code') 8 | x = int('a') # Raises an exception 9 | 10 | 11 | def fun2(): 12 | try: 13 | print('try code') 14 | print('no exception raised code') 15 | x = int('a') # Raises an exception 16 | except: 17 | print('exception handling code') 18 | 19 | 20 | print('Calling fun2') 21 | fun2() 22 | print('-------------') 23 | print('Calling fun1') 24 | fun1() 25 | -------------------------------------------------------------------------------- /Chap13/circle.py: -------------------------------------------------------------------------------- 1 | class Circle: 2 | """ Represents a geometric circle object """ 3 | def __init__(self, center, radius): 4 | """ Initalize the center's center and radius """ 5 | # Disallow a negative radius 6 | if radius < 0: 7 | raise ValueError('Negative radius') 8 | self.center = center 9 | self.radius = radius 10 | 11 | def get_radius(self): 12 | """ Return the radius of the circle """ 13 | return self.radius 14 | 15 | def get_center(self): 16 | """ Return the coordinatess of the center """ 17 | return self.center 18 | 19 | def get_area(self): 20 | """ Compute and return the area of the circle """ 21 | from math import pi 22 | return pi*self.radius*self.radius 23 | 24 | def get_circumference(self): 25 | """ Compute and return the circumference of the circle """ 26 | from math import pi 27 | return 2*pi*self.radius 28 | 29 | def move(self, pt): 30 | """ Moves the enter of the circle to point pt """ 31 | self.center = pt 32 | 33 | def grow(self): 34 | """ Increases the radius of the circle """ 35 | self.radius += 1 36 | 37 | def shrink(self): 38 | """ Decreases the radius of the circle; 39 | does not affect a circle with radius zero """ 40 | if self.radius > 0: 41 | self.radius -= 1 42 | -------------------------------------------------------------------------------- /Chap13/dynamicfield.py: -------------------------------------------------------------------------------- 1 | class Widget: 2 | def __init__(self): 3 | self.a = 5 # Provide a preexisting attribute 4 | 5 | w = Widget() 6 | print(w.__dict__) 7 | print("w.a =", getattr(w, "a")) 8 | setattr(w, "a", 10) 9 | print("w.a =", getattr(w, "a")) 10 | field_name = input("Enter instance variable name: ") 11 | setattr(w, field_name, 15) 12 | print(getattr(w, field_name)) 13 | setattr(w, field_name, 20) 14 | print(getattr(w, field_name)) 15 | print(w.__dict__) 16 | -------------------------------------------------------------------------------- /Chap13/multisizelightwindow.py: -------------------------------------------------------------------------------- 1 | from tkinter import * #Tk, Canvas 2 | from tkinter.ttk import Button, Frame 3 | from random import choice, randrange 4 | 5 | from functools import partial 6 | 7 | from trafficlight import TrafficLight 8 | 9 | class MultisizeLightWindow: 10 | """ Graphical window that displays multiple traffic lights 11 | of different sizes. """ 12 | 13 | def do_button_press(self, idx): 14 | """ The window manager calls this function when the user 15 | presses the graphical button. """ 16 | self.lights[idx].change() 17 | 18 | def __init__(self): 19 | root = Tk() # Create the main window 20 | root.title("Multiple Traffic Lights") # Set title bar text 21 | self.lights = [] 22 | # The outer frame holds the nine inner frames that each contain 23 | # a canvas and a button. 24 | outer_frame = Frame(root) 25 | outer_frame.pack() 26 | # Create nine drawing surfaces within the window 27 | for i in range(1, 10): 28 | f = Frame(outer_frame, borderwidth=2, relief=GROOVE) 29 | f.grid(row=0, column=i) 30 | c = Canvas(f, width=20*i, height=250) 31 | c.grid(row=0, column=0) 32 | self.lights.append(TrafficLight(5*i, 10, 10*i, c)) 33 | #b = Button(f, text="Change", command=lambda x=i: lights[x - 1].change()) 34 | b = Button(f, text="Change", command=partial(self.do_button_press, i - 1)) 35 | b.grid(row=1, column=0) 36 | # Start the GUI event loop 37 | root.mainloop() 38 | 39 | 40 | # Main program --------------------------------------------------------------------- 41 | 42 | # Create and execute a traffic light window 43 | MultisizeLightWindow() 44 | -------------------------------------------------------------------------------- /Chap13/randomlights.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | from tkinter.ttk import Button, Frame 3 | from random import choice, randrange 4 | 5 | from trafficlight import TrafficLight 6 | 7 | class RandomLightsWindow: 8 | """ Graphical window that displays multiple traffic lights 9 | of different sizes. """ 10 | 11 | def __init__(self): 12 | root = Tk() # Create the main window 13 | root.title("Multiple Traffic Lights") # Set title bar text 14 | f = Frame(root) 15 | f.pack() 16 | # Create a drawing surface within the window 17 | canvas = Canvas(f, width=800, height=600) 18 | # Make a list of random traffic light objects 19 | color_list = ["red", "yellow", "green"] 20 | self.light_list = [] 21 | for i in range(50): 22 | self.light_list.append(TrafficLight(randrange(2, 700), 23 | randrange(2, 400), 24 | randrange(5, 120), 25 | canvas, 26 | choice(color_list))) 27 | # Create a graphical button and ensure it calls the do_button_press 28 | # function when the user presses it 29 | button = Button(f, text='Change', command=self.do_button_press) 30 | # Position button and canvas objects 31 | button.grid(row=0, column=0) 32 | canvas.grid(row=0, column=1) 33 | # Start the GUI event loop 34 | root.mainloop() 35 | 36 | def do_button_press(self): 37 | """ The window manager calls this function when the user 38 | presses the graphical button. """ 39 | for light in self.light_list: 40 | light.change() 41 | 42 | 43 | # Main program --------------------------------------------------------------------- 44 | 45 | # Create and execute a traffic light window 46 | RandomLightsWindow() 47 | -------------------------------------------------------------------------------- /Chap13/stopwatch.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | 3 | class Stopwatch: 4 | """ Provides stopwatch objects that that programmers 5 | can use to time the execution time of portions of 6 | a program. """ 7 | def __init__(self): 8 | """ Makes a new stopwatch ready for timing. """ 9 | self.reset() 10 | 11 | def start(self): 12 | """ Starts the stopwatch, unless it is already running. 13 | This method does not affect any time that may have 14 | already accumulated on the stopwatch. """ 15 | if not self._running: 16 | self._start_time = clock() - self._elapsed 17 | self._running = True # Clock now running 18 | 19 | def stop(self): 20 | """ Stops the stopwatch, unless it is not running. 21 | Updates the accumulated elapsed time. """ 22 | if self._running: 23 | self._elapsed = clock() - self._start_time 24 | self._running = False # Clock stopped 25 | 26 | def reset(self): 27 | """ Resets stopwatch to zero. """ 28 | self._start_time = self._elapsed = 0 29 | self._running = False 30 | 31 | def elapsed(self): 32 | """ Reveals the stopwatch running time since it 33 | was last reset. """ 34 | if not self._running: 35 | return self._elapsed 36 | else: 37 | return clock() - self._start_time 38 | -------------------------------------------------------------------------------- /Chap13/testplotter.py: -------------------------------------------------------------------------------- 1 | from plotobj import Plotter 2 | from math import sin 3 | 4 | 5 | def quad(x): 6 | """ Quadratic function (parabola) """ 7 | return 1/2 * x**2 + 3 8 | 9 | 10 | def arrow_wheel(plotter, x, y, len, angle, color): 11 | """ Draws a collection of arrows extending radially from 12 | an (x, y) center point. The arrows all are len long, the 13 | angle parameter specifes the angle between each adjacent 14 | arrow, and color specifies their color. """ 15 | from math import cos, sin, radians 16 | COS_theta = cos(radians(angle)) 17 | SIN_theta = sin(radians(angle)) 18 | plotter.setcolor(color) 19 | xe, ye = len, 0.0 20 | for i in range(360//angle): 21 | xe, ye = xe*COS_theta - ye*SIN_theta, xe*SIN_theta + ye*COS_theta 22 | plotter.draw_arrow(x, y, xe + x, ye + y) 23 | 24 | 25 | def main(): 26 | """ Provides a simple test of the plotting object. """ 27 | from math import sin 28 | 29 | def run_test(x, y): 30 | """ Generate an arrow wheel centered at (x, y) with 31 | random size and color. """ 32 | #test_arrow(plt) 33 | from random import randrange 34 | colors = ["red", "green", "blue", "black"] 35 | arrow_wheel(plt, x, y, randrange(10) + 1, 10, colors[randrange(4)]) 36 | 37 | # Create a plotter object 38 | plt = Plotter(600, 600, -10, 10, -10, 10) 39 | # Plot f(x) = 1/2*x + 3, for -10 <= x < 100 40 | plt.plot_function(quad, 'red') 41 | # Plot f(x) = x, for -10 <= x < 100 42 | plt.plot_function(lambda x: x, 'blue') 43 | # Plot f(x) = 3 sin x, for -10 <= x < 100 44 | plt.plot_function(lambda x: 3*sin(x), 'green') 45 | 46 | # Execute the run_test function when the user clicks the mouse 47 | plt.onclick(run_test) 48 | #test_arrow(plt) 49 | 50 | plt.interact() 51 | 52 | 53 | if __name__ == '__main__': 54 | main() 55 | -------------------------------------------------------------------------------- /Chap13/trafficlightobject.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Canvas 2 | from tkinter.ttk import Button, Frame 3 | 4 | from trafficlight import TrafficLight 5 | 6 | 7 | class TrafficLightWindow: 8 | """ Graphical window that displays a traffic light and change button. """ 9 | 10 | def __init__(self): 11 | root = Tk() # Create the main window 12 | root.title("Traffic Light") # Set title bar text 13 | # Create widget container 14 | frame = Frame(root) 15 | frame.pack() 16 | # Create a graphical button and ensure it calls the do_button_press 17 | # method when the user presses it 18 | button = Button(frame, text='Change', command=self.do_button_press) 19 | # Create and add a drawing surface within the window 20 | canvas = Canvas(frame, width=200, height=300) 21 | # Make a traffic light object instance variable 22 | self.light = TrafficLight(50, 20, 100, canvas) 23 | # Position button and canvas objects 24 | button.grid(row=0, column=0) 25 | canvas.grid(row=0, column=1) 26 | # Start the GUI event loop 27 | root.mainloop() 28 | 29 | def do_button_press(self): 30 | """ The window manager calls this function when the user 31 | presses the graphical button. """ 32 | self.light.change() 33 | 34 | 35 | # Main program --------------------------------------------------------------------- 36 | 37 | # Create and execute a traffic light window 38 | TrafficLightWindow() 39 | -------------------------------------------------------------------------------- /Chap13/widgetfactory.py: -------------------------------------------------------------------------------- 1 | class Widget: 2 | """ Models a manufactured item. """ 3 | serial_number_source = 0 # Class variable 4 | def __init__(self): 5 | """ Make a widget with a unique serial number. """ 6 | self.serial_number = Widget.serial_number_source 7 | Widget.serial_number_source += 1 8 | def get_serial_number(self): 9 | """ Return the widget's serial number. """ 10 | return self.serial_number 11 | 12 | if __name__ == '__main__': 13 | widget_list = [] 14 | for i in range(10): 15 | widget_list.append(Widget()) 16 | for w in widget_list: 17 | print(w.serial_number, end=' ') 18 | print() 19 | -------------------------------------------------------------------------------- /Chap14/box.py: -------------------------------------------------------------------------------- 1 | class Box: 2 | """ A square box object """ 3 | def __init__(self, screen, pen, x, y, width): 4 | """ Initializes a box object with a given Turtle screen, pen, 5 | (x, y) position, and width """ 6 | self._screen = screen 7 | self._pen = pen 8 | self._x_val = x 9 | self._y_val = y 10 | self._width = width 11 | 12 | def position(self, x, y): 13 | """ Positions the box at (x,y) """ 14 | self._x_val = x 15 | self._y_val = y 16 | 17 | def render(self): 18 | """ Renders the box in the Turtle graphics window """ 19 | self._pen.penup() # Move pen 20 | self._pen.setpos(self._x_val - self._width/2, 21 | self._y_val - self._width/2) 22 | self._pen.setheading(0) 23 | self._pen.pendown() 24 | self._pen.fillcolor("blue") 25 | self._pen.begin_fill() 26 | self._pen.forward(self._width) 27 | self._pen.left(90) 28 | self._pen.forward(self._width) 29 | self._pen.left(90) 30 | self._pen.forward(self._width) 31 | self._pen.left(90) 32 | self._pen.forward(self._width) 33 | self._pen.left(90) 34 | self._pen.end_fill() 35 | -------------------------------------------------------------------------------- /Chap14/boxadapter.py: -------------------------------------------------------------------------------- 1 | from graphicalobject import GraphicalObject 2 | from box import Box 3 | 4 | class BoxAdapter(GraphicalObject): 5 | """ A simple, square box graphical object. 6 | BoxAdapter is a GraphicalObject. 7 | BoxAdapter has a Box. """ 8 | def __init__(self, **kwargs): 9 | """ Initializes an adapted box object with a given Turtle 10 | screen, pen, and (x, y) position """ 11 | self.box = Box(kwargs['screen'], kwargs['turtle'], 12 | kwargs['x'], kwargs['y'], kwargs['width']) 13 | super().__init__(**kwargs) 14 | 15 | def move_to(self, x, y): 16 | """ Repositions the box to (x,y) """ 17 | self.box.position(x, y) 18 | 19 | def draw(self): 20 | """ Renders the box in the Turtle graphics window """ 21 | #self.box.position(self.x, self.y) 22 | self.box.render() 23 | -------------------------------------------------------------------------------- /Chap14/comptrafficlightapp.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import tkinter.ttk as ttk 3 | 4 | from comptrafficlight import CompTrafficLight 5 | 6 | 7 | class CompTrafficLightApp: 8 | """ Graphical window that displays a traffic light and change button. """ 9 | 10 | def __init__(self): 11 | root = tk.Tk() # Create the main window 12 | root.title("Traffic Light") # Set title bar text 13 | # Create widget container 14 | frame = ttk.Frame(root) 15 | frame.pack() 16 | # Create a graphical button and ensure it calls the do_button_press 17 | # method when the user presses it 18 | button = ttk.Button(frame, text='Change', command=self.do_button_press) 19 | # Make a traffic light object instance variable 20 | self.light = CompTrafficLight(frame, 100, padding=25) 21 | # Position button and canvas objects 22 | button.grid(row=0, column=0) 23 | self.light.frame.grid(row=0, column=1) 24 | # Start the GUI event loop 25 | root.mainloop() 26 | 27 | def do_button_press(self): 28 | """ The window manager calls this function when the user 29 | presses the graphical button. """ 30 | self.light.change() 31 | 32 | 33 | # Main program --------------------------------------------------------------------- 34 | 35 | # Create and execute a traffic light window 36 | CompTrafficLightApp() 37 | -------------------------------------------------------------------------------- /Chap14/countingstopwatch.py: -------------------------------------------------------------------------------- 1 | from stopwatch import Stopwatch 2 | 3 | class CountingStopwatch(Stopwatch): 4 | def __init__(self): 5 | # Allow base class to do its initialization of the 6 | # inherited instance variables 7 | super().__init__() 8 | # Set number of starts to zero 9 | self._count = 0 10 | 11 | def start(self): 12 | # Count this start message unless the watch already is running 13 | if not self._running: 14 | self._count += 1 15 | # Let base class do its start code 16 | super().start() 17 | 18 | def reset(self): 19 | # Let base class reset the inherited instance variables 20 | super().reset() 21 | # Reset new instance variable that the base class method does not know about 22 | self._count = 0 23 | 24 | def count(self): 25 | return self._count 26 | -------------------------------------------------------------------------------- /Chap14/countingstopwatch2.py: -------------------------------------------------------------------------------- 1 | from stopwatch import Stopwatch 2 | 3 | class CountingStopwatch2: 4 | """ This counting stopwatch uses composition instead of 5 | inheritance. """ 6 | def __init__(self): 7 | # Create a stopwatch object to keep the time 8 | self.watch = Stopwatch() 9 | # Set number of starts to zero 10 | self._count = 0 11 | 12 | def start(self): 13 | # Count this start message unless the watch already is running 14 | if not self.watch._running: 15 | self._count += 1 16 | # Delegate other work to the stopwatch object 17 | self.watch.start() 18 | 19 | def stop(self): 20 | # Delegate to stopwatch object 21 | self.watch.stop() 22 | 23 | def reset(self): 24 | # Let the stopwatch object reset the time 25 | watch.reset() 26 | # Reset the count 27 | self._count = 0 28 | 29 | def elapsed(self): 30 | # Delegate to stopwatch object 31 | return self.watch.elapsed() 32 | 33 | def count(self): 34 | return self._count 35 | -------------------------------------------------------------------------------- /Chap14/digitalstopwatch.py: -------------------------------------------------------------------------------- 1 | from stopwatch import Stopwatch 2 | 3 | class DigitalStopwatch(Stopwatch): 4 | def digital_time(self): 5 | """ Returns a string representation of the elapsed time 6 | in hours : minutes : seconds. """ 7 | # Compute time in hours, minutes, and seconds 8 | seconds = round(self.elapsed()) 9 | hours = seconds // 3600 # Compute total hours 10 | seconds %= 3600 # Update seconds remaining 11 | minutes = seconds // 60 # Compute minutes 12 | seconds %= 60 # Update seconds remaining 13 | # Each digit occupies two spaces; pad with leading zeros, if necessary 14 | return "{0:0>2}:{1:0>2}:{2:0>2}".format(hours, minutes, seconds) 15 | -------------------------------------------------------------------------------- /Chap14/digitaltimer.py: -------------------------------------------------------------------------------- 1 | from timer import Timer 2 | 3 | class DigitalTimer(Timer): 4 | def __init__(self, **kwargs): # New code here 5 | super().__init__(**kwargs) # New code here 6 | print("Initializing digital stopwatch") # New code here 7 | 8 | def digital_time(self): 9 | """ Returns a string representation of the elapsed time 10 | in hours : minutes : seconds. """ 11 | # Compute time in hours, minutes, and seconds 12 | seconds = round(self.elapsed()) 13 | hours = seconds // 3600 # Compute total hours 14 | seconds %= 3600 # Update seconds remaining 15 | minutes = seconds // 60 # Compute minutes 16 | seconds %= 60 # Update seconds remaining 17 | # Each digit occupies two spaces; pad with leading zeros, if necessary 18 | return "{0:0>2}:{1:0>2}:{2:0>2}".format(hours, minutes, seconds) 19 | -------------------------------------------------------------------------------- /Chap14/dot.py: -------------------------------------------------------------------------------- 1 | from graphicalobject import GraphicalObject 2 | 3 | class Dot(GraphicalObject): 4 | """ A simple, round circle graphical object """ 5 | def __init__(self, **kwargs): 6 | """ Initializes a dot object with a given Turtle screen, pen, 7 | and (x, y) position """ 8 | super().__init__(**kwargs) 9 | 10 | def draw(self): 11 | """ Renders the dot in the Turtle graphics window """ 12 | self.turtle.penup() # Move pen 13 | self.turtle.setpos(self.x, self.y) 14 | self.turtle.pendown() 15 | self.turtle.fillcolor("red") 16 | self.turtle.begin_fill() 17 | self.turtle.circle(20) 18 | self.turtle.end_fill() 19 | -------------------------------------------------------------------------------- /Chap14/graphicalobject.py: -------------------------------------------------------------------------------- 1 | from top import Top 2 | 3 | class GraphicalObject(Top): 4 | """ A graphical object that allows the user to reposition 5 | it anywhere within the window using the mouse. 6 | Contains all the code to manage the Turtle graphics 7 | environment. """ 8 | def __init__(self, **kwargs): 9 | """ Initializes a GraphicalObject object 10 | Keyword args include: 11 | screen is the Turtle graphics screen. 12 | turtle is the Turtle graphics pen. 13 | initially appear at location (x, y). """ 14 | super().__init__(**kwargs) # See discussion about super constructor 15 | print("Initializing graphical object") 16 | self.screen = kwargs['screen'] 17 | self.turtle = kwargs['turtle'] 18 | self.x = kwargs['x'] 19 | self.y = kwargs['y'] 20 | self.screen.delay(0) # Do not slowly trace drawing 21 | self.turtle.speed(0) # Make turtle's actions as fast as possible 22 | self.turtle.hideturtle() # Make the turtle invisible 23 | self.screen.onclick(self.do_click) # Set mouse press handler 24 | self.move_to(x=kwargs['x'], y=kwargs['y']) 25 | 26 | def run(self): 27 | """ Run the graphical program. """ 28 | self.screen.mainloop() 29 | 30 | def draw(self): 31 | """ Renders the object within the window. 32 | Derived classes override this method to meet their specific 33 | needs. """ 34 | pass 35 | 36 | def do_click(self, x, y): 37 | """ Called when the user presses the mouse button. 38 | (x, y) is the new location of the display. """ 39 | self.move_to(x, y) # Move to a new location 40 | self.draw() # Redraw at new location 41 | 42 | def move_to(self, x, y): 43 | """ Relocates a Movable object to position (x, y). """ 44 | self.x, self.y = x, y 45 | -------------------------------------------------------------------------------- /Chap14/movablelight.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import tkinter.ttk as ttk 3 | 4 | from trafficsignal import TrafficSignal 5 | 6 | 7 | class MovableLight(TrafficSignal): 8 | """ Models a graphical traffic light that the user can reposition """ 9 | 10 | def __init__(self, parent, width, initial_color="red"): 11 | """ Makes a new movable traffic light object. The light's 12 | parent is the parent widget 13 | The width of the light is width pixels. 14 | The light's initial color is initial_color. """ 15 | # Call base class constructor 16 | super().__init__(parent, width, initial_color) 17 | self.place(x=0, y=0) 18 | 19 | def move_to(self, x, y): 20 | """ Positions the light's center at point (x, y) """ 21 | center_x_offset = self.winfo_width() // 2 22 | center_y_offset = self.winfo_height() // 2 23 | self.x = x - center_x_offset 24 | self.y = y - center_y_offset 25 | self.place(x=self.x, y=self.y) 26 | -------------------------------------------------------------------------------- /Chap14/newtrafficlightapp.py: -------------------------------------------------------------------------------- 1 | import tkinter as tk 2 | import tkinter.ttk as ttk 3 | 4 | from trafficsignal import TrafficSignal 5 | 6 | 7 | class NewTrafficLightApp: 8 | """ Graphical window that displays a traffic light and change button. """ 9 | 10 | def __init__(self): 11 | root = tk.Tk() # Create the main window 12 | root.title("Traffic Light") # Set title bar text 13 | # Create widget container 14 | frame = ttk.Frame(root) 15 | frame.pack() 16 | # Create a graphical button and ensure it calls the do_button_press 17 | # method when the user presses it 18 | button = ttk.Button(frame, text='Change', command=self.do_button_press) 19 | # Create and add a drawing surface within the window 20 | # Make a traffic light object instance variable 21 | self.light = TrafficSignal(frame, 100, padding=25) 22 | #self.light.config(padding=25) 23 | # Position button and canvas objects 24 | button.grid(row=0, column=0) 25 | self.light.grid(row=0, column=1) 26 | # Start the GUI event loop 27 | root.mainloop() 28 | 29 | def do_button_press(self): 30 | """ The window manager calls this function when the user 31 | presses the graphical button. """ 32 | self.light.change() 33 | 34 | 35 | # Main program --------------------------------------------------------------------- 36 | 37 | # Create and execute a traffic light window 38 | NewTrafficLightApp() 39 | -------------------------------------------------------------------------------- /Chap14/restrictedstopwatch.py: -------------------------------------------------------------------------------- 1 | from countingstopwatch import CountingStopwatch 2 | 3 | class RestrictedStopwatch(CountingStopwatch): 4 | def __init__(self, n): 5 | """ Restrict the number stopwatch starts to n times. """ 6 | # Allow superclass to do its initialization of the 7 | # inherited instance variables 8 | super().__init__() 9 | self._limit = n 10 | 11 | def start(self): 12 | """ If the count exceeds the limit, terminate the program's 13 | execution. """ 14 | if self._count < self._limit: 15 | super().start() # Let superclass do its start code 16 | else: 17 | import sys 18 | print("Limit exceeded") 19 | sys.exit(1) # Limit exceeded, terminate the program 20 | -------------------------------------------------------------------------------- /Chap14/simplemultinherit.py: -------------------------------------------------------------------------------- 1 | class Top(object): 2 | def __init__(self, **kwargs): 3 | pass # Terminate the constructor call chain 4 | 5 | class A(Top): 6 | def __init__(self, **kwargs): 7 | print("Making an A object") 8 | super().__init__(**kwargs) 9 | self.value_A = 0 10 | 11 | class B(Top): 12 | def __init__(self, **kwargs): 13 | print("Making a B object") 14 | self.value_B = kwargs['val'] 15 | kwargs.pop('val') # Remove the parameter from the kwargs 16 | super().__init__(**kwargs) 17 | 18 | class C(A, B): 19 | def __init__(self, **kwargs): 20 | print("Making a C object") 21 | super().__init__(**kwargs) 22 | self.value_C = 2 23 | 24 | c_obj = C(val=5) # Need to supply keyword argument here 25 | print("===========") 26 | print(c_obj.__dict__) 27 | -------------------------------------------------------------------------------- /Chap14/stopwatch.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | 3 | class Stopwatch: 4 | """ Provides stopwatch objects that that programmers 5 | can use to time the execution time of portions of 6 | a program. """ 7 | def __init__(self): 8 | """ Makes a new stopwatch ready for timing. """ 9 | self.reset() 10 | 11 | def start(self): 12 | """ Starts the stopwatch, unless it is already running. 13 | This method does not affect any time that may have 14 | already accumulated on the stopwatch. """ 15 | if not self._running: 16 | self._start_time = clock() - self._elapsed 17 | self._running = True # Clock now running 18 | 19 | def stop(self): 20 | """ Stops the stopwatch, unless it is not running. 21 | Updates the accumulated elapsed time. """ 22 | if self._running: 23 | self._elapsed = clock() - self._start_time 24 | self._running = False # Clock stopped 25 | 26 | def reset(self): 27 | """ Resets stopwatch to zero. """ 28 | self._start_time = self._elapsed = 0 29 | self._running = False 30 | 31 | def elapsed(self): 32 | """ Reveals the stopwatch running time since it 33 | was last reset. """ 34 | if not self._running: 35 | return self._elapsed 36 | else: 37 | return clock() - self._start_time 38 | -------------------------------------------------------------------------------- /Chap14/testbox.py: -------------------------------------------------------------------------------- 1 | from boxadapter import BoxAdapter 2 | from turtle import Screen, Turtle 3 | 4 | 5 | def main(): 6 | # Make a Box object via the adapter 7 | b = BoxAdapter(screen=Screen(), turtle=Turtle(), 8 | x=20, y=20, width=30) 9 | # Run the graphical program 10 | b.run() 11 | 12 | 13 | if __name__ == "__main__": 14 | main() 15 | -------------------------------------------------------------------------------- /Chap14/testdigitalsw.py: -------------------------------------------------------------------------------- 1 | from digitalstopwatch import DigitalStopwatch 2 | from time import sleep 3 | 4 | dsw = DigitalStopwatch() 5 | dsw.start() # Start the timer 6 | sleep(140) # Do noting for 2:20 7 | dsw.stop() # Stop the timer 8 | print(dsw.digital_time()) # Print elapsed time in digital format 9 | -------------------------------------------------------------------------------- /Chap14/testdot.py: -------------------------------------------------------------------------------- 1 | from dot import Dot 2 | from turtle import Screen, Turtle 3 | 4 | 5 | def main(): 6 | # Make a Dot object 7 | d = Dot(screen=Screen(), turtle=Turtle(), x=10, y=20) 8 | # Run the graphical program 9 | d.run() 10 | 11 | 12 | if __name__ == "__main__": 13 | main() 14 | -------------------------------------------------------------------------------- /Chap14/testrestrictedsw.py: -------------------------------------------------------------------------------- 1 | from restrictedstopwatch import RestrictedStopwatch 2 | 3 | sw = RestrictedStopwatch(3) 4 | print("Starting 1") 5 | sw.start() 6 | print("Stopping 1") 7 | sw.stop() 8 | print("Starting 2") 9 | sw.start() 10 | print("Stopping 2") 11 | sw.stop() 12 | print("Starting 3") 13 | sw.start() 14 | print("Stopping 3") 15 | sw.stop() 16 | print("Starting 4") 17 | sw.start() 18 | print("Stopping 4") 19 | sw.stop() 20 | print("Done") 21 | -------------------------------------------------------------------------------- /Chap14/timer.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | from top import Top 3 | 4 | class Timer(Top): 5 | """ Provides stopwatch objects that that programmers 6 | can use to time the execution time of portions of 7 | a program. """ 8 | def __init__(self, **kwargs): 9 | """ Makes a new stopwatch ready for timing. """ 10 | super().__init__(**kwargs) # New code here 11 | print("Initializing stopwatch") # New code here 12 | self.reset() 13 | 14 | def start(self): 15 | """ Starts the stopwatch, unless it is already running. 16 | This method does not affect any time that may have 17 | already accumulated on the stopwatch. """ 18 | if not self._running: 19 | self._start_time = clock() - self._elapsed 20 | self._running = True # Clock now running 21 | 22 | def stop(self): 23 | """ Stops the stopwatch, unless it is not running. 24 | Updates the accumulated elapsed time. """ 25 | if self._running: 26 | self._elapsed = clock() - self._start_time 27 | self._running = False # Clock stopped 28 | 29 | def reset(self): 30 | """ Resets stopwatch to zero. """ 31 | self._start_time = self._elapsed = 0 32 | self._running = False 33 | 34 | def elapsed(self): 35 | """ Reveals the stopwatch running time since it 36 | was last reset. """ 37 | if not self._running: 38 | return self._elapsed 39 | else: 40 | return clock() - self._start_time 41 | -------------------------------------------------------------------------------- /Chap14/top.py: -------------------------------------------------------------------------------- 1 | class Top(object): 2 | def __init__(self, **kwargs): 3 | pass # Terminate the constructor call chain 4 | -------------------------------------------------------------------------------- /Chap14/usecountingsw.py: -------------------------------------------------------------------------------- 1 | from countingstopwatch import CountingStopwatch 2 | from time import sleep 3 | 4 | timer = CountingStopwatch() 5 | timer.start() 6 | sleep(10) # Pause program for 10 seconds 7 | timer.stop() 8 | print("Time:", timer.elapsed(), " Number:", timer.count()) 9 | 10 | timer.start() 11 | sleep(5) # Pause program for 5 seconds 12 | timer.stop() 13 | print("Time:", timer.elapsed(), " Number:", timer.count()) 14 | 15 | timer.start() 16 | sleep(20) # Pause program for 20 seconds 17 | timer.stop() 18 | print("Time:", timer.elapsed(), " Number:", timer.count()) 19 | -------------------------------------------------------------------------------- /Chap15/ascendingtheory.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | from math import sqrt 3 | from plotobj import Plotter 4 | 5 | 6 | def main(): 7 | """ Compares the theoretical performance of the is_ascending and 8 | is_ascending2 functions on lists of various sizes. """ 9 | data1, data2 = [], [] 10 | 11 | # Compute results for sizes in the range 0...40,000 12 | max_size = 40000 13 | # Sizes used are 0**2 = 0, 20**2 = 400, 40**2 = 1600, 60**2 = 3600, 14 | # etc. up to 200**2 = 40,000 15 | 16 | # Create a plotter object 17 | plt = Plotter(600, 600, 0, max_size, 0, 750000000) 18 | 19 | # Plot the curves 20 | plt.pen.width(4) 21 | data1 = [(x, (x**2 - x)/2) for x in 22 | (x**2 for x in range(0, round(sqrt(max_size)) + 1, 20))] 23 | data2 = [(x, x - 1) for x in 24 | (x**2 for x in range(0, round(sqrt(max_size)) + 1, 20))] 25 | 26 | plt.plot_data(data1, "green") 27 | plt.plot_data(data2, "brown") 28 | 29 | plt.interact() 30 | 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /Chap15/fibonacci.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | from random import randrange 3 | 4 | 5 | def fibonacci(n): 6 | """ Returns the nth Fibonacci number recursively. """ 7 | if n <= 0: 8 | return 0 9 | elif n == 1: 10 | return 1 11 | else: 12 | return fibonacci(n - 2) + fibonacci(n - 1) 13 | 14 | 15 | # Dictionary for caching the results of the fibonacci2 function 16 | ans = {0:0, 1:1} # Precompute the results for 0 and 1 17 | 18 | def fibonacci2(n): 19 | """ Returns the nth Fibonacci number. Caches a 20 | recursively computed result to be used when needed 21 | in the future. Provides a huge performance improvement 22 | over the recursive version. """ 23 | if n not in ans.keys(): 24 | result = fibonacci2(n - 2) + fibonacci2(n - 1) 25 | ans[n] = result 26 | return ans[n] 27 | 28 | 29 | def time_it(f, ns): 30 | """ f is a function that accepts a single parameter. 31 | ns is a list. 32 | Measures the time for function f to process each element in ns. 33 | Returns the cumulative elapsed time. """ 34 | start_time = clock() 35 | for i in ns: 36 | #print("{:>4}: {:>8}".format(i, f(i))) 37 | print(f(i), end=" ") 38 | end_time = clock() 39 | return end_time - start_time # Return elapsed time 40 | 41 | 42 | def main(): 43 | """ Tests the performance of the fibonacci and fibonacci2 functions. """ 44 | 45 | # Make a list of pseudorandom integers in the range 1...50 46 | numbers = [] 47 | for i in range(10): 48 | numbers.append(randrange(40) + 1) 49 | 50 | # Print the numbers 51 | print(numbers) 52 | 53 | # Compare the two Fibonacci functions 54 | print("Time:", time_it(fibonacci, numbers)) 55 | print("------------------") 56 | print("Time:", time_it(fibonacci2, numbers)) 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /Chap15/fibonacciinstrumented.py: -------------------------------------------------------------------------------- 1 | # This dictionary will keep track of the number of calls to the 2 | # fibonacci function. 3 | call_counter = {} 4 | 5 | def fibonacci(n): 6 | """ Returns the nth Fibonacci number. """ 7 | # Count the call 8 | if n not in call_counter: 9 | call_counter[n] = 1 10 | else: 11 | call_counter[n] += 1 12 | 13 | if n <= 0: 14 | return 0 15 | elif n == 1: 16 | return 1 17 | else: 18 | return fibonacci(n - 2) + fibonacci(n - 1) 19 | 20 | 21 | # Call fibonacci(5) 22 | print("fibonacci(5) = ", fibonacci(5)) 23 | print() 24 | 25 | # Report the total number of calls to the fibonacci function 26 | print("Argument Calls") 27 | print("-----------------") 28 | for args, calls in sorted(call_counter.items()): 29 | print(" ", args, " ", calls); 30 | -------------------------------------------------------------------------------- /Chap15/generatepermutations.py: -------------------------------------------------------------------------------- 1 | def perm(lst, begin): 2 | """ Generates the sequence of all the permutations of the 3 | elements of a given list (lst), beginning with a 4 | specified index (begin). 5 | This is a helper function for the permutations function. """ 6 | end = len(lst) - 1 # Index of the last element 7 | if begin == end: 8 | yield lst[:] # Yield a copy of lst 9 | else: 10 | for i in range(begin, end + 1): # Consider all indices 11 | # Interchange the element at the first position 12 | # with the element at position i 13 | lst[begin], lst[i] = lst[i], lst[begin] 14 | # Recursively permute the rest of the list 15 | yield from perm(lst, begin + 1) 16 | # Undo the earlier interchange 17 | lst[begin], lst[i] = lst[i], lst[begin] 18 | 19 | 20 | def permutations(lst): 21 | """ Generates the sequence of all the permutations of the 22 | elements of list lst. 23 | Delegates the hard work to the perm function. """ 24 | yield from perm(lst, 0) 25 | 26 | 27 | def main(): 28 | """ Tests the permutations function. """ 29 | a = list(range(3)) # Make list [0, 1, 2] 30 | print('List:', a) # Print the list 31 | # Generate and print all permutations of the list 32 | for p in permutations(a): 33 | print(p, end=' ') 34 | print() 35 | 36 | 37 | if __name__ == '__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /Chap15/inplacecount.py: -------------------------------------------------------------------------------- 1 | def count_helper(lst, pos, item): 2 | """ Counts the number of occurrences of item within the list 3 | lst. pos represents the current position under 4 | examination within the list. """ 5 | if pos == len(lst): # Are we past the end of the list? 6 | return 0 # Nothing can appear past the end 7 | else: 8 | # Count the occurrences in the rest of the list 9 | # (all but the first element) 10 | count_rest = count_helper(lst, pos + 1, item) 11 | if lst[pos] == item: 12 | return 1 + count_rest 13 | else: 14 | return count_rest 15 | 16 | 17 | def count(lst, item): 18 | """ Counts the number of occurrences of item within the list 19 | lst. Delegates the work to the recursive count_helper 20 | function, passing zero as the initial position (which is 21 | the index of the first element in the list). """ 22 | return count_helper(lst, 0, item) 23 | 24 | 25 | def main(): 26 | lst1 = [21, 19, 31, 22, 14, 31, 22, 6, 31] 27 | print(count(lst1, 31)) 28 | lst2 = ['FRED', [2, 3], 44, 'WILMA', 'FRED', 8, 'BARNEY'] 29 | print(count(lst2, 'FRED')) 30 | print(count(lst2, 'BETTY')) 31 | print(count([], 16)) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /Chap15/inplacecountlocal.py: -------------------------------------------------------------------------------- 1 | 2 | def count(lst, item): 3 | """ Counts the number of occurrences of item within the list 4 | lst. Delegates the work to the recursive count_helper 5 | function, passing zero as the initial position (which is 6 | the index of the first element in the list). """ 7 | 8 | def count_helper(pos): 9 | """ Local function counts the number of occurrences of an 10 | item within a list. 11 | pos represents the current position under examination 12 | within the list. 13 | lst and item are nonlocal variables from the outer context. """ 14 | if pos == len(lst): # Are we past the end of the list? 15 | return 0 # Nothing can appear past the end 16 | else: 17 | # Count the occurrences in the rest of the list 18 | # (all but the first element) 19 | count_rest = count_helper(pos + 1) 20 | if lst[pos] == item: 21 | return 1 + count_rest 22 | else: 23 | return count_rest 24 | 25 | # Body of count function 26 | return count_helper(0) 27 | 28 | 29 | def main(): 30 | lst1 = [21, 19, 31, 22, 14, 31, 22, 6, 31] 31 | print(count(lst1, 31)) 32 | lst2 = ['FRED', [2, 3], 44, 'WILMA', 'FRED', 8, 'BARNEY'] 33 | print(count(lst2, 'FRED')) 34 | print(count(lst2, 'BETTY')) 35 | print(count([], 16)) 36 | 37 | 38 | if __name__ == '__main__': 39 | main() 40 | -------------------------------------------------------------------------------- /Chap15/listpermutations.py: -------------------------------------------------------------------------------- 1 | def perm(lst, begin, result): 2 | """ Creates a list (result) containing all the permutations of the 3 | elements of a given list (lst), beginning with a 4 | specified index (begin). 5 | This is a helper function for the permutations function. """ 6 | end = len(lst) - 1 # Index of the last element 7 | if begin == end: 8 | result += [lst[:]] # Copy lst into result 9 | else: 10 | for i in range(begin, end + 1): # Consider all indices 11 | # Interchange the element at the first position 12 | # with the element at position i 13 | lst[begin], lst[i] = lst[i], lst[begin] 14 | # Recursively permute the rest of the list 15 | perm(lst, begin + 1, result) 16 | # Undo the earlier interchange 17 | lst[begin], lst[i] = lst[i], lst[begin] 18 | 19 | 20 | def permutations(lst): 21 | """ Returns a list containing all the permutations of the 22 | orderings of the elements of a given list (lst). 23 | Delegates the hard work to the perm function. """ 24 | result = [] 25 | perm(lst, 0, result) 26 | return result 27 | 28 | 29 | def main(): 30 | """ Tests the permutations function. """ 31 | a = list(range(3)) # Make list [0, 1, 2] 32 | print('List:', a) # Print the list 33 | # Generate and print all permutations of the list 34 | print('Permutations:', permutations(a)) 35 | 36 | 37 | if __name__ == '__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /Chap15/listreverse.py: -------------------------------------------------------------------------------- 1 | def rev(lst): 2 | return [] if len(lst) == 0 else rev(lst[1:]) + lst[0:1] 3 | 4 | print(rev([1, 2, 3, 4, 5, 6, 7])) 5 | -------------------------------------------------------------------------------- /Chap15/nonrecursivememory.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | def nonrec(n, depth): 4 | """ Prints the value of the parameter n and local variable 5 | rand before and after the recursive call. 6 | n is the parameter of interest. 7 | depth represents the depth of the recursion. """ 8 | history = [] 9 | while n != 0: 10 | rand = randint(0, 1000) # Make a random number 11 | history += [(n, depth, rand)] # Remember original values of n and depth 12 | print(' ' * depth, 'Entering: n =', n, ' rand =', rand) 13 | n -= 1 14 | depth += 1 15 | print(' ' * depth, ' *** Recursion over ***') 16 | while len(history) > 0: 17 | n, depth, rand = history[-1] 18 | del history[-1] 19 | print(' ' * depth, 'Exiting: n =', n, ' rand =', rand) 20 | 21 | 22 | nonrec(10, 0) 23 | -------------------------------------------------------------------------------- /Chap15/perminstrumented.py: -------------------------------------------------------------------------------- 1 | def perm(lst, begin, result, depth): 2 | """ Creates a list (result) containing all the permutations of the 3 | elements of a given list (lst), beginning with a 4 | specified index (begin). 5 | Printing statements report the progression of the 6 | function's recursion. The depth parameter indicates the 7 | depth of the recursion. 8 | This is a helper function for the permutations function. """ 9 | print(' ' * depth, 'begin =', begin) 10 | end = len(lst) - 1 # Index of the last element 11 | if begin == end: 12 | result += [lst[:]] # Copy lst into result 13 | print(' ' * depth, ' *') 14 | else: 15 | for i in range(begin, end + 1): 16 | # Interchange the element at the first position 17 | # with the element at position i 18 | lst[begin], lst[i] = lst[i], lst[begin] 19 | print(' ' * depth, ' ', lst[begin], '<-->', lst[i], ' ', lst) 20 | # Recursively permute the rest of the list 21 | perm(lst, begin + 1, result, depth + 1) 22 | # Undo the earlier interchange 23 | lst[begin], lst[i] = lst[i], lst[begin] 24 | 25 | 26 | def permutations(lst): 27 | """ Returns a list containing all the permutations of the 28 | orderings of the elements of a given list (lst). 29 | Delegates the hard work to the perm function. """ 30 | result = [] 31 | perm(lst, 0, result, 0) # Initial call with depth = 0 32 | return result 33 | 34 | 35 | def main(): 36 | a = list(range(3)) 37 | print(permutations(a)) 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Chap15/randompermute.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | 4 | def permute(lst): 5 | """ 6 | Randomly permutes the contents of list lst 7 | """ 8 | n = len(lst) 9 | for i in range(n - 1): 10 | pos = randrange(i, n) # i <= pos < n 11 | lst[i], lst[pos] = lst[pos], lst[i] 12 | 13 | 14 | def main(): 15 | """ 16 | Tests the permute function that randomly permutes the 17 | contents of a list 18 | """ 19 | a = [1, 2, 3, 4, 5, 6, 7, 8] 20 | print('Before:', a) 21 | permute(a) 22 | print('After :', a) 23 | 24 | 25 | main() 26 | -------------------------------------------------------------------------------- /Chap15/recursivecount.py: -------------------------------------------------------------------------------- 1 | def count(lst, item): 2 | """ Counts the number of occurrences of item within the list lst """ 3 | if len(lst) == 0: # Is the list empty? 4 | return 0 # Nothing can appear in an empty list 5 | else: 6 | # Count the occurrences in the rest of the list 7 | # (all but the first element) 8 | count_rest = count(lst[1:], item) 9 | if lst[0] == item: 10 | return 1 + count_rest 11 | else: 12 | return count_rest 13 | 14 | 15 | def main(): 16 | lst1 = [21, 19, 31, 22, 14, 31, 22, 6, 31] 17 | print(count(lst1, 31)) 18 | lst2 = ['FRED', [2, 3], 44, 'WILMA', 'FRED', 8, 'BARNEY'] 19 | print(count(lst2, 'FRED')) 20 | print(count(lst2, 'BETTY')) 21 | print(count([], 16)) 22 | 23 | 24 | if __name__ == '__main__': 25 | main() 26 | -------------------------------------------------------------------------------- /Chap15/recursivememory.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | def rec(n, depth): 4 | """ Prints the value of the parameter n and local variable 5 | rand before and after the recursive call. 6 | n is the parameter of interest. 7 | depth represents the depth of the recursion. """ 8 | rand = randint(0, 1000) # Make a random number 9 | print(' ' * depth, 'Entering: n =', n, ' rand =', rand) 10 | if n == 0: 11 | print(' ' * depth, ' *** Recursion over ***') 12 | else: 13 | rec(n - 1, depth + 1) 14 | print(' ' * depth, 'Exiting: n =', n, ' rand =', rand) 15 | 16 | 17 | rec(10, 0) 18 | -------------------------------------------------------------------------------- /Chap15/reversedexample.py: -------------------------------------------------------------------------------- 1 | for item in reversed([1, 2, 3, 4, 5, 6, 7]): 2 | print(item, end=" ") 3 | print() 4 | -------------------------------------------------------------------------------- /Chap15/sortintegers.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | def random_list(): 4 | """ 5 | Produce a list of pseudorandom integers. 6 | The list's length is chosen pseudorandomly in the 7 | range 3-20. 8 | The integers in the list range from -50 to 50. 9 | """ 10 | result = [] 11 | count = randint(3, 20) 12 | for i in range(count): 13 | result.append(randint(-50, 50)) 14 | return result 15 | 16 | 17 | def selection_sort(lst): 18 | """ 19 | Arranges the elements of list lst in ascending order. 20 | Physically rearranges the elements of lst. 21 | """ 22 | n = len(lst) 23 | for i in range(n - 1): 24 | # Note: i, small, and j represent positions within lst 25 | # lst[i], lst[small], and lst[j] represent the elements at 26 | # those positions. 27 | # small is the position of the smallest value we've seen 28 | # so far; we use it to find the smallest value less 29 | # than lst[i] 30 | small = i 31 | # See if a smaller value can be found later in the list 32 | # Consider all the elements at position j, where i < j < n 33 | for j in range(i + 1, n): 34 | if lst[j] < lst[small]: 35 | small = j # Found a smaller value 36 | # Swap lst[i] and lst[small], if a smaller value was found 37 | if i != small: 38 | lst[i], lst[small] = lst[small], lst[i] 39 | 40 | 41 | def main(): 42 | """ 43 | Tests the selection_sort function 44 | """ 45 | for n in range(10): 46 | col = random_list() 47 | print(col) 48 | selection_sort(col) 49 | print(col) 50 | print('==============================') 51 | 52 | 53 | main() 54 | -------------------------------------------------------------------------------- /Chap15/stdpermutations.py: -------------------------------------------------------------------------------- 1 | # Use the standard permutations function to list 2 | # the possible arrangements of elements in a list. 3 | 4 | from itertools import permutations 5 | 6 | 7 | def main(): 8 | a = [0, 1, 2] 9 | for p in permutations(a): 10 | print(p, end=' ') 11 | print() 12 | 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /Chap15/stdpermutations2list.py: -------------------------------------------------------------------------------- 1 | # Use the standard permutations function to list 2 | # the possible arrangements of elements in a list. 3 | 4 | from itertools import permutations 5 | 6 | 7 | def main(): 8 | a = [0, 1, 2] 9 | for p in permutations(a): 10 | print(list(p), end=' ') 11 | print() 12 | 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /Chap2/addintegers.py: -------------------------------------------------------------------------------- 1 | print('Please enter an integer value:') 2 | x = input() 3 | print('Please enter another integer value:') 4 | y = input() 5 | num1 = int(x) 6 | num2 = int(y) 7 | print(num1, '+', num2, '=', num1 + num2) 8 | -------------------------------------------------------------------------------- /Chap2/addintegers2.py: -------------------------------------------------------------------------------- 1 | x = input('Please enter an integer value: ') 2 | y = input('Please enter another integer value: ') 3 | num1 = int(x) 4 | num2 = int(y) 5 | print(num1, '+', num2, '=', num1 + num2) 6 | -------------------------------------------------------------------------------- /Chap2/addintegers3.py: -------------------------------------------------------------------------------- 1 | num1 = int(input('Please enter an integer value: ')) 2 | num2 = int(input('Please enter another integer value: ')) 3 | print(num1, '+', num2, '=', num1 + num2) 4 | -------------------------------------------------------------------------------- /Chap2/changeabletype.py: -------------------------------------------------------------------------------- 1 | a = 10 2 | print('First, variable a has value', a, 'and type', type(a)) 3 | a = 'ABC' 4 | print('Now, variable a has value', a, 'and type', type(a)) 5 | -------------------------------------------------------------------------------- /Chap2/charactercube.py: -------------------------------------------------------------------------------- 1 | x = ''' 2 | A cube has 8 corners: 3 | 4 | 7------8 5 | /| /| 6 | 3------4 | 7 | | | | | 8 | | 5----|-6 9 | |/ |/ 10 | 1------2 11 | ''' 12 | print(x) 13 | -------------------------------------------------------------------------------- /Chap2/escapequotes.py: -------------------------------------------------------------------------------- 1 | print("Did you know that 'word' is a word?") 2 | print('Did you know that "word" is a word?') 3 | print('Did you know that \'word\' is a word?') 4 | print("Did you know that \"word\" is a word?") 5 | -------------------------------------------------------------------------------- /Chap2/multilinestring.py: -------------------------------------------------------------------------------- 1 | x = ''' 2 | This is a multi-line 3 | string that goes on 4 | for three lines! 5 | ''' 6 | print(x) 7 | -------------------------------------------------------------------------------- /Chap2/multipleassignment.py: -------------------------------------------------------------------------------- 1 | x = 10 2 | print(x) 3 | x = 20 4 | print(x) 5 | x = 30 6 | print(x) 7 | -------------------------------------------------------------------------------- /Chap2/multipleassignment2.py: -------------------------------------------------------------------------------- 1 | x = 10 2 | print('x = ' + str(x)) 3 | x = 20 4 | print('x = ' + str(x)) 5 | x = 30 6 | print('x = ' + str(x)) 7 | -------------------------------------------------------------------------------- /Chap2/multipleassignment3.py: -------------------------------------------------------------------------------- 1 | variable, version~2} 2 | x = 10 3 | print('x =', x) 4 | x = 20 5 | print('x =', x) 6 | x = 30 7 | print('x =', x) 8 | -------------------------------------------------------------------------------- /Chap2/pi-print.py: -------------------------------------------------------------------------------- 1 | pi = 3.14159 2 | print("Pi =", pi) 3 | print("or", 3.14, "for short") 4 | -------------------------------------------------------------------------------- /Chap2/powers10left.py: -------------------------------------------------------------------------------- 1 | print(0, 10**0) 2 | print(1, 10**1) 3 | print(2, 10**2) 4 | print(3, 10**3) 5 | print(4, 10**4) 6 | print(5, 10**5) 7 | print(6, 10**6) 8 | print(7, 10**7) 9 | print(8, 10**8) 10 | print(9, 10**9) 11 | print(10, 10**10) 12 | print(11, 10**11) 13 | print(12, 10**12) 14 | print(13, 10**13) 15 | print(14, 10**14) 16 | print(15, 10**15) 17 | -------------------------------------------------------------------------------- /Chap2/powers10left2.py: -------------------------------------------------------------------------------- 1 | print('{0} {1}'.format(0, 10**0)) 2 | print('{0} {1}'.format(1, 10**1)) 3 | print('{0} {1}'.format(2, 10**2)) 4 | print('{0} {1}'.format(3, 10**3)) 5 | print('{0} {1}'.format(4, 10**4)) 6 | print('{0} {1}'.format(5, 10**5)) 7 | print('{0} {1}'.format(6, 10**6)) 8 | print('{0} {1}'.format(7, 10**7)) 9 | print('{0} {1}'.format(8, 10**8)) 10 | print('{0} {1}'.format(9, 10**9)) 11 | print('{0} {1}'.format(10, 10**10)) 12 | print('{0} {1}'.format(11, 10**11)) 13 | print('{0} {1}'.format(12, 10**12)) 14 | print('{0} {1}'.format(13, 10**13)) 15 | print('{0} {1}'.format(14, 10**14)) 16 | print('{0} {1}'.format(15, 10**15)) 17 | -------------------------------------------------------------------------------- /Chap2/powers10right.py: -------------------------------------------------------------------------------- 1 | print('{0:>3} {1:>16}'.format(0, 10**0)) 2 | print('{0:>3} {1:>16}'.format(1, 10**1)) 3 | print('{0:>3} {1:>16}'.format(2, 10**2)) 4 | print('{0:>3} {1:>16}'.format(3, 10**3)) 5 | print('{0:>3} {1:>16}'.format(4, 10**4)) 6 | print('{0:>3} {1:>16}'.format(5, 10**5)) 7 | print('{0:>3} {1:>16}'.format(6, 10**6)) 8 | print('{0:>3} {1:>16}'.format(7, 10**7)) 9 | print('{0:>3} {1:>16}'.format(8, 10**8)) 10 | print('{0:>3} {1:>16}'.format(9, 10**9)) 11 | print('{0:>3} {1:>16}'.format(10, 10**10)) 12 | print('{0:>3} {1:>16}'.format(11, 10**11)) 13 | print('{0:>3} {1:>16}'.format(12, 10**12)) 14 | print('{0:>3} {1:>16}'.format(13, 10**13)) 15 | print('{0:>3} {1:>16}'.format(14, 10**14)) 16 | print('{0:>3} {1:>16}'.format(15, 10**15)) 17 | -------------------------------------------------------------------------------- /Chap2/printingexample.py: -------------------------------------------------------------------------------- 1 | print('A', end='') 2 | print('B', end='') 3 | print('C', end='') 4 | print() 5 | print('X') 6 | print('Y') 7 | print('Z') 8 | -------------------------------------------------------------------------------- /Chap2/printpath.py: -------------------------------------------------------------------------------- 1 | filename = 'C:\\Users\\rick' 2 | print(filename) 3 | -------------------------------------------------------------------------------- /Chap2/printsep.py: -------------------------------------------------------------------------------- 1 | w, x, y, z = 10, 15, 20, 25 2 | print(w, x, y, z) 3 | print(w, x, y, z, sep=',') 4 | print(w, x, y, z, sep='') 5 | print(w, x, y, z, sep=':') 6 | print(w, x, y, z, sep='-----') 7 | -------------------------------------------------------------------------------- /Chap2/scientificnotation.py: -------------------------------------------------------------------------------- 1 | avogadros_number = 6.022e23 2 | c = 2.998e8 3 | print("Avogadro's number =", avogadros_number) 4 | print("Speed of light =", c) 5 | -------------------------------------------------------------------------------- /Chap2/specialchars.py: -------------------------------------------------------------------------------- 1 | print('A\nB\nC') 2 | print('D\tE\tF') 3 | print('WX\bYZ') 4 | print('1\a2\a3\a4\a5\a6') 5 | -------------------------------------------------------------------------------- /Chap2/tupleassign.py: -------------------------------------------------------------------------------- 1 | x, y, z = 100, -45, 0 2 | print('x =', x, ' y =', y, ' z =', z) 3 | -------------------------------------------------------------------------------- /Chap2/usinginput.py: -------------------------------------------------------------------------------- 1 | print('Please enter some text:') 2 | x = input() 3 | print('Text entered:', x) 4 | print('Type:', type(x)) 5 | -------------------------------------------------------------------------------- /Chap2/variable.py: -------------------------------------------------------------------------------- 1 | x = 10 2 | print(x) 3 | -------------------------------------------------------------------------------- /Chap3/adder.py: -------------------------------------------------------------------------------- 1 | value1 = int(input('Please enter a number: ')) 2 | value2 = int(input('Please enter another number: ')) 3 | sum = value1 + value2 4 | print(value1, '+', value2, '=', sum) 5 | -------------------------------------------------------------------------------- /Chap3/dividedanger.py: -------------------------------------------------------------------------------- 1 | # File dividedanger.py 2 | 3 | # Get two integers from the user 4 | print('Please enter two numbers to divide.') 5 | dividend = int(input('Please enter the dividend: ')) 6 | divisor = int(input('Please enter the divisor: ')) 7 | # Divide them and report the result 8 | print(dividend, '/', divisor, "=", dividend/divisor) 9 | -------------------------------------------------------------------------------- /Chap3/enhancedtimeconv.py: -------------------------------------------------------------------------------- 1 | # File enhancedtimeconv.py 2 | 3 | # Get the number of seconds 4 | seconds = int(input("Please enter the number of seconds:")) 5 | # First, compute the number of hours in the given number of seconds 6 | # Note: integer division with possible truncation 7 | hours = seconds // 3600 # 3600 seconds = 1 hours 8 | # Compute the remaining seconds after the hours are accounted for 9 | seconds = seconds % 3600 10 | # Next, compute the number of minutes in the remaining number of seconds 11 | minutes = seconds // 60 # 60 seconds = 1 minute 12 | # Compute the remaining seconds after the minutes are accounted for 13 | seconds = seconds % 60 14 | # Report the results 15 | print(hours, ":", sep="", end="") 16 | # Compute tens digit of minutes 17 | tens = minutes // 10 18 | # Compute ones digit of minutes 19 | ones = minutes % 10 20 | print(tens, ones, ":", sep="", end="") 21 | # Compute tens digit of seconds 22 | tens = seconds // 10 23 | # Compute ones digit of seconds 24 | ones = seconds % 10 25 | print(tens, ones, sep ="") 26 | -------------------------------------------------------------------------------- /Chap3/error.py: -------------------------------------------------------------------------------- 1 | y = 5 2 | x = y + 2 3 | y + 2 = x 4 | -------------------------------------------------------------------------------- /Chap3/faultytempconv.py: -------------------------------------------------------------------------------- 1 | # File faultytempconv.py 2 | 3 | # Establish some variables 4 | degreesF, degreesC = 0, 0 5 | # Define the relationship between F and C 6 | degreesC = 5/9*(degreesF - 32) 7 | # Prompt user for degrees F 8 | degreesF = float(input('Enter the temperature in degrees F: ')) 9 | # Report the result 10 | print(degreesF, "degrees F =', degreesC, 'degrees C') 11 | -------------------------------------------------------------------------------- /Chap3/halve.py: -------------------------------------------------------------------------------- 1 | # Get a number from the user 2 | value = int(input('Please enter a number to cut in half: ')) 3 | # Report the result 4 | print(value/2) 5 | -------------------------------------------------------------------------------- /Chap3/imprecise.py: -------------------------------------------------------------------------------- 1 | one = 1.0 2 | one_third = 1.0/3.0 3 | zero = one - one_third - one_third - one_third 4 | 5 | print('one =', one, ' one_third =', one_third, ' zero =', zero) 6 | -------------------------------------------------------------------------------- /Chap3/imprecise10.py: -------------------------------------------------------------------------------- 1 | one = 1.0 2 | one_tenth = 1.0/10.0 3 | zero = one - one_tenth - one_tenth - one_tenth \ 4 | - one_tenth - one_tenth - one_tenth \ 5 | - one_tenth - one_tenth - one_tenth \ 6 | - one_tenth 7 | 8 | print('one =', one, ' one_tenth =', one_tenth, ' zero =', zero) 9 | -------------------------------------------------------------------------------- /Chap3/precise4.py: -------------------------------------------------------------------------------- 1 | binary fraction} 2 | one = 1.0 3 | one_fourth = 1.0/4.0 4 | zero = one - one_fourth - one_fourth - one_fourth - one_fourth 5 | print('one =', one, ' one-fourth =', one_fourth, ' zero =', zero) 6 | -------------------------------------------------------------------------------- /Chap3/tempconv.py: -------------------------------------------------------------------------------- 1 | # File tempconv.py 2 | # Author: Rick Halterman 3 | # Last modified: August 22, 2014 4 | # Converts degrees Fahrenheit to degrees Celsius 5 | # Based on the formula found at 6 | # http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature 7 | 8 | # Prompt user for temperature to convert and read the supplied value 9 | degreesF = float(input('Enter the temperature in degrees F: ')) 10 | # Perform the conversion 11 | degreesC = 5/9*(degreesF - 32) 12 | # Report the result 13 | print(degreesF, 'degrees F =', degreesC, 'degrees C') 14 | -------------------------------------------------------------------------------- /Chap3/timeconv.py: -------------------------------------------------------------------------------- 1 | # File timeconv.py 2 | 3 | # Get the number of seconds 4 | seconds = int(input("Please enter the number of seconds:")) 5 | # First, compute the number of hours in the given number of seconds 6 | # Note: integer division with possible truncation 7 | hours = seconds // 3600 # 3600 seconds = 1 hours 8 | # Compute the remaining seconds after the hours are accounted for 9 | seconds = seconds % 3600 10 | # Next, compute the number of minutes in the remaining number of seconds 11 | minutes = seconds // 60 # 60 seconds = 1 minute 12 | # Compute the remaining seconds after the minutes are accounted for 13 | seconds = seconds % 60 14 | # Report the results 15 | print(hours, "hr,", minutes, "min,", seconds, "sec") 16 | -------------------------------------------------------------------------------- /Chap4/absvalueconditional.py: -------------------------------------------------------------------------------- 1 | # Acquire a number from the user and print its absolute value. 2 | n = int(input("Enter a number: ")) 3 | print('|', n, '| = ', (-n if n < 0 else n), sep='') 4 | -------------------------------------------------------------------------------- /Chap4/alternatedivision.py: -------------------------------------------------------------------------------- 1 | # Get two integers from the user 2 | dividend = int(input('Please enter the number to divide: ')) 3 | divisor = int(input('Please enter dividend: ')) 4 | # If possible, divide them and report the result 5 | if divisor != 0: 6 | quotient = dividend/divisor 7 | print(dividend, '/', divisor, "=", quotient) 8 | print('Program finished') 9 | -------------------------------------------------------------------------------- /Chap4/betterdivision.py: -------------------------------------------------------------------------------- 1 | # File betterdivision.py 2 | 3 | # Get two integers from the user 4 | print('Please enter two numbers to divide.') 5 | dividend = int(input('Please enter the first number to divide: ')) 6 | divisor = int(input('Please enter the second number to divide: ')) 7 | # If possible, divide them and report the result 8 | if divisor != 0: 9 | print(dividend, '/', divisor, "=", dividend/divisor) 10 | -------------------------------------------------------------------------------- /Chap4/betterfeedback.py: -------------------------------------------------------------------------------- 1 | # Get two integers from the user 2 | dividend = int(input('Please enter the number to divide: ')) 3 | divisor = int(input('Please enter dividend: ')) 4 | # If possible, divide them and report the result 5 | if divisor != 0: 6 | print(dividend, '/', divisor, "=", dividend/divisor) 7 | else: 8 | print('Division by zero is not allowed') 9 | -------------------------------------------------------------------------------- /Chap4/binaryconversion.py: -------------------------------------------------------------------------------- 1 | # Get number from the user 2 | value = int(input("Please enter an integer value in the range 0...1023: ")) 3 | # Create an empty binary string to build upon 4 | binary_string = '' 5 | # Integer must be less than 1024 6 | if 0 <= value < 1024: 7 | if value >= 512: 8 | binary_string += '1' 9 | value %= 512 10 | else: 11 | binary_string += '0' 12 | if value >= 256: 13 | binary_string += '1' 14 | value %= 256 15 | else: 16 | binary_string += '0' 17 | if value >= 128: 18 | binary_string += '1' 19 | value %= 128 20 | else: 21 | binary_string += '0' 22 | if value >= 64: 23 | binary_string += '1' 24 | value %= 64 25 | else: 26 | binary_string += '0' 27 | if value >= 32: 28 | binary_string += '1' 29 | value %= 32 30 | else: 31 | binary_string += '0' 32 | if value >= 16: 33 | binary_string += '1' 34 | value %= 16 35 | else: 36 | binary_string += '0' 37 | if value >= 8: 38 | binary_string += '1' 39 | value %= 8 40 | else: 41 | binary_string += '0' 42 | if value >= 4: 43 | binary_string += '1' 44 | value %= 4 45 | else: 46 | binary_string += '0' 47 | if value >= 2: 48 | binary_string += '1' 49 | value %= 2 50 | else: 51 | binary_string += '0' 52 | binary_string += str(value) 53 | 54 | # Display the results 55 | if binary_string != '': 56 | print(binary_string) 57 | else: 58 | print('Cannot convert') 59 | -------------------------------------------------------------------------------- /Chap4/boolvars.py: -------------------------------------------------------------------------------- 1 | # Assign some Boolean variables 2 | a = True 3 | b = False 4 | print('a =', a, ' b =', b) 5 | # Reassign a 6 | a = False 7 | print('a =', a, ' b =', b) 8 | -------------------------------------------------------------------------------- /Chap4/checkrange.py: -------------------------------------------------------------------------------- 1 | value = int(input("Please enter an integer value in the range 0...10: ") 2 | if value >= 0: # First check 3 | if value <= 10: # Second check 4 | print("In range") 5 | print("Done") 6 | -------------------------------------------------------------------------------- /Chap4/datetransformer.py: -------------------------------------------------------------------------------- 1 | month = int(input("Please enter the month as a number (1-12): ")) 2 | day = int(input("Please enter the day of the month: ")) 3 | # Translate month into English 4 | if month == 1: 5 | print("January ", end='') 6 | elif month == 2: 7 | print("February ", end='') 8 | elif month == 3: 9 | print("March ", end='') 10 | elif month == 4: 11 | print("April ", end='') 12 | elif month == 5: 13 | print("May ", end='') 14 | elif month == 6: 15 | print("June ", end='') 16 | elif month == 7: 17 | print("July ", end='') 18 | elif month == 8: 19 | print("August ", end='') 20 | elif month == 9: 21 | print("September ", end='') 22 | elif month == 10: 23 | print("October ", end='') 24 | elif month == 11: 25 | print("November ", end='') 26 | else: 27 | print("December ", end='') 28 | # Add the day 29 | print(day, 'or', day, end='') 30 | # Translate month into Spanish 31 | if month == 1: 32 | print(" de enero") 33 | elif month == 2: 34 | print(" de febrero") 35 | elif month == 3: 36 | print(" de marzo") 37 | elif month == 4: 38 | print(" de abril") 39 | elif month == 5: 40 | print(" de mayo") 41 | elif month == 6: 42 | print(" de junio") 43 | elif month == 7: 44 | print(" de julio") 45 | elif month == 8: 46 | print(" de agosto") 47 | elif month == 9: 48 | print(" de septiembre") 49 | elif month == 10: 50 | print(" de octubre") 51 | elif month == 11: 52 | print(" de noviembre") 53 | else: 54 | print(" de diciembre") 55 | -------------------------------------------------------------------------------- /Chap4/digittoword.py: -------------------------------------------------------------------------------- 1 | value = int(input("Please enter an integer in the range 0...5: ")) 2 | if value < 0: 3 | print("Too small") 4 | else: 5 | if value == 0: 6 | print("zero") 7 | else: 8 | if value == 1: 9 | print("one") 10 | else: 11 | if value == 2: 12 | print("two") 13 | else: 14 | if value == 3: 15 | print("three") 16 | else: 17 | if value == 4: 18 | print("four") 19 | else: 20 | if value == 5: 21 | print("five") 22 | else: 23 | print("Too large") 24 | print("Done") 25 | -------------------------------------------------------------------------------- /Chap4/digittoworderror.py: -------------------------------------------------------------------------------- 1 | value = int(input("Please enter an integer in the range 0...5: ")) 2 | answer = "not in range" # Default answer 3 | if value == 0: 4 | answer = "zero" 5 | elif value == 1: 6 | answer = "one" 7 | elif value == 2: 8 | answer = "two" 9 | elif value == 3: 10 | amswer = "three" 11 | elif value == 4: 12 | answer = "four" 13 | elif value == 5: 14 | answer = "five" 15 | print("The number you entered was", answer) 16 | -------------------------------------------------------------------------------- /Chap4/enhancedcheckrange.py: -------------------------------------------------------------------------------- 1 | value = int(input("Please enter an integer value in the range 0...10: ") 2 | if value >= 0: # First check 3 | if value <= 10: # Second check 4 | print(value, "is in range") 5 | else: 6 | print(value, "is too large") 7 | else: 8 | print(value, "is too small") 9 | print("Done") 10 | -------------------------------------------------------------------------------- /Chap4/floatequals.py: -------------------------------------------------------------------------------- 1 | d1 = 1.11 - 1.10 2 | d2 = 2.11 - 2.10 3 | print('d1 =', d1, ' d2 =', d2) 4 | diff = d1 - d2 # Compute difference 5 | if diff < 0: # Compute absolute value 6 | diff = -diff 7 | if diff < 0.0000001: # Are the values close enough? 8 | print('Same') 9 | else: 10 | print('Different') 11 | -------------------------------------------------------------------------------- /Chap4/floatequals2.py: -------------------------------------------------------------------------------- 1 | d1 = 1.11 - 1.10 2 | d2 = 2.11 - 2.10 3 | print('d1 =', d1, ' d2 =', d2) 4 | if -0.0000001 < d1 - d2 < 0.0000001: 5 | print('Same') 6 | else: 7 | print('Different') 8 | -------------------------------------------------------------------------------- /Chap4/leadingzeros.py: -------------------------------------------------------------------------------- 1 | # Request input from the user 2 | num = int(input("Please enter an integer in the range 0...9999: ")) 3 | 4 | # Attenuate the number if necessary 5 | if num < 0: # Make sure number is not too small 6 | num = 0 7 | if num > 9999: # Make sure number is not too big 8 | num = 9999 9 | 10 | print(end="[") # Print left brace 11 | 12 | # Extract and print thousands-place digit 13 | digit = num//1000 # Determine the thousands-place digit 14 | print(digit, end="") # Print the thousands-place digit 15 | num %= 1000 # Discard thousands-place digit 16 | 17 | # Extract and print hundreds-place digit 18 | digit = num//100 # Determine the hundreds-place digit 19 | print(digit, end="") # Print the hundreds-place digit 20 | num %= 100 # Discard hundreds-place digit 21 | 22 | # Extract and print tens-place digit 23 | digit = num//10 # Determine the tens-place digit 24 | print(digit, end="") # Print the tens-place digit 25 | num %= 10 # Discard tens-place digit 26 | 27 | # Remainder is the one-place digit 28 | print(num, end="") # Print the ones-place digit 29 | 30 | print("]") # Print right brace 31 | -------------------------------------------------------------------------------- /Chap4/max4a.py: -------------------------------------------------------------------------------- 1 | # Get input values from user 2 | print("Please enter four integer values.") 3 | num1 = int(input("Enter number 1: ")) 4 | num2 = int(input("Enter number 2: ")) 5 | num3 = int(input("Enter number 3: ")) 6 | num4 = int(input("Enter number 4: ")) 7 | 8 | # Compute the maximum value 9 | if num1 >= num2 and num1 >= num3 and num1 >= num4: 10 | max = num1 11 | elif num2 >= num1 and num2 >= num3 and num2 >= num4: 12 | max = num2 13 | elif num3 >= num1 and num3 >= num2 and num3 >= num4: 14 | max = num3 15 | else: # The maximum must be num4 at this point 16 | max = num4 17 | 18 | # Report result 19 | print("The maximum number entered was:", max) 20 | -------------------------------------------------------------------------------- /Chap4/max4b.py: -------------------------------------------------------------------------------- 1 | # Get input values from user 2 | print("Please enter four integer values.") 3 | num1 = int(input("Enter number 1: ")) 4 | num2 = int(input("Enter number 2: ")) 5 | num3 = int(input("Enter number 3: ")) 6 | num4 = int(input("Enter number 4: ")) 7 | 8 | # Compute the maximum value 9 | max = num1 10 | if num2 > max: 11 | max = num2 12 | if num3 > max: 13 | max = num3 14 | if num4 > max: 15 | max = num4 16 | 17 | # Report result 18 | print("The maximum number entered was:", max) 19 | -------------------------------------------------------------------------------- /Chap4/multivsseq1.py: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | if num == 1: 3 | print("You entered one") 4 | elif num == 2: 5 | print("You entered two") 6 | elif num > 5: 7 | print("You entered a number greater than five") 8 | elif num == 7: 9 | print("You entered seven") 10 | else: 11 | print("You entered some other number") 12 | -------------------------------------------------------------------------------- /Chap4/multivsseq2.py: -------------------------------------------------------------------------------- 1 | num = int(input("Enter a number: ")) 2 | if num == 1: 3 | print("You entered one") 4 | if num == 2: 5 | print("You entered two") 6 | if num > 5: 7 | print("You entered a number greater than five") 8 | if num == 7: 9 | print("You entered seven") 10 | else: 11 | print("You entered some other number") 12 | -------------------------------------------------------------------------------- /Chap4/newcheckrange.py: -------------------------------------------------------------------------------- 1 | value = int(input("Please enter an integer value in the range 0...10: ") 2 | if value >= 0 and value <= 10: # Only one, slightly more complicated check 3 | print("In range") 4 | print("Done") 5 | -------------------------------------------------------------------------------- /Chap4/restyleddigittoword.py: -------------------------------------------------------------------------------- 1 | value = int(input("Please enter an integer in the range 0...5: ")) 2 | if value < 0: 3 | print("Too small") 4 | elif value == 0: 5 | print("zero") 6 | elif value == 1: 7 | print("one") 8 | elif value == 2: 9 | print("two") 10 | elif value == 3: 11 | print("three") 12 | elif value == 4: 13 | print("four") 14 | elif value == 5: 15 | print("five") 16 | else: 17 | print("Too large") 18 | print("Done") 19 | -------------------------------------------------------------------------------- /Chap4/safedivide.py: -------------------------------------------------------------------------------- 1 | # Get the dividend and divisor from the user 2 | dividend = int(input('Enter dividend: ')) 3 | divisor = int(input('Enter divisor: ')) 4 | # We want to divide only if divisor is not zero; otherwise, 5 | # we will print an error message 6 | if divisor != 0: 7 | print(dividend/divisor) 8 | else: 9 | print('Error, cannot divide by zero') 10 | -------------------------------------------------------------------------------- /Chap4/safedivideconditional.py: -------------------------------------------------------------------------------- 1 | # Get the dividend and divisor from the user 2 | dividend = int(input('Enter dividend: ')) 3 | divisor = int(input('Enter divisor: ')) 4 | # We want to divide only if divisor is not zero; otherwise, 5 | # we will print an error message 6 | msg = dividend/divisor if divisor != 0 else 'Error, cannot divide by zero' 7 | print(msg) 8 | -------------------------------------------------------------------------------- /Chap4/samedifferent.py: -------------------------------------------------------------------------------- 1 | d1 = 1.11 - 1.10 2 | d2 = 2.11 - 2.10 3 | print('d1 =', d1, ' d2 =', d2) 4 | if d1 == d2: 5 | print('Same') 6 | else: 7 | print('Different') 8 | -------------------------------------------------------------------------------- /Chap4/simplerbinaryconversion.py: -------------------------------------------------------------------------------- 1 | # Get number from the user 2 | value = int(input("Please enter an integer value in the range 0...1023: ")) 3 | # Initial binary string is empty 4 | binary_string = '' 5 | # Integer must be less than 1024 6 | if 0 <= value < 1024: 7 | binary_string += str(value//512) 8 | value %= 512 9 | binary_string += str(value//256) 10 | value %= 256 11 | binary_string += str(value//128) 12 | value %= 128 13 | binary_string += str(value//64) 14 | value %= 64 15 | binary_string += str(value//32) 16 | value %= 32 17 | binary_string += str(value//16) 18 | value %= 16 19 | binary_string += str(value//8) 20 | value %= 8 21 | binary_string += str(value//4) 22 | value %= 4 23 | binary_string += str(value//2) 24 | value %= 2 25 | binary_string += str(value) 26 | # Report results 27 | if binary_string != '': 28 | print(binary_string) 29 | else: 30 | print('Unable to convert') 31 | -------------------------------------------------------------------------------- /Chap4/simplerdigittoword.py: -------------------------------------------------------------------------------- 1 | # Use a mult-way conditional statement 2 | value = int(input()) 3 | if value == 0: 4 | print("zero") 5 | elif value == 1: 6 | print("one") 7 | elif value == 2: 8 | print("two") 9 | elif value == 3: 10 | print("three") 11 | elif value == 4: 12 | print("four") 13 | elif value == 5: 14 | print("five") 15 | print("Done") 16 | -------------------------------------------------------------------------------- /Chap4/simplerdigittoword2.py: -------------------------------------------------------------------------------- 1 | # Use sequential conditional statements 2 | value = int(input()) 3 | if value == 0: 4 | print("zero") 5 | if value == 1: 6 | print("one") 7 | if value == 2: 8 | print("two") 9 | if value == 3: 10 | print("three") 11 | if value == 4: 12 | print("four") 13 | if value == 5: 14 | print("five") 15 | print("Done") 16 | -------------------------------------------------------------------------------- /Chap4/timeconvcond1.py: -------------------------------------------------------------------------------- 1 | # File timeconvcond1.py 2 | 3 | # Some useful conversion factors 4 | seconds_per_minute = 60 5 | seconds_per_hour = 60*seconds_per_minute # 3600 6 | 7 | # Get user input in seconds 8 | seconds = int(input("Please enter the number of seconds:")) 9 | 10 | # First, compute the number of hours in the given number of seconds 11 | hours = seconds // seconds_per_hour # 3600 seconds = 1 hour 12 | # Compute the remaining seconds after the hours are accounted for 13 | seconds = seconds % seconds_per_hour 14 | # Next, compute the number of minutes in the remaining number of seconds 15 | minutes = seconds // seconds_per_minute # 60 seconds = 1 minute 16 | # Compute the remaining seconds after the minutes are accounted for 17 | seconds = seconds % seconds_per_minute 18 | # Report the results 19 | print(hours, end='') 20 | # Decide between singular and plural form of hours 21 | if hours == 1: 22 | print(" hour ", end='') 23 | else: 24 | print(" hours ", end='') 25 | print(minutes, end='') 26 | # Decide between singular and plural form of minutes 27 | if minutes == 1: 28 | print(" minute ", end='') 29 | else: 30 | print(" minutes ", end='') 31 | print(seconds, end='') 32 | # Decide between singular and plural form of seconds 33 | if seconds == 1: 34 | print(" second") 35 | else: 36 | print(" seconds") 37 | -------------------------------------------------------------------------------- /Chap4/timeconvcond2.py: -------------------------------------------------------------------------------- 1 | # File timeconvcond2.py 2 | 3 | # Some useful conversion constants 4 | seconds_per_minute = 60 5 | seconds_per_hour = 60*seconds_per_minute # 3600 6 | seconds = int(input("Please enter the number of seconds:")) 7 | # First, compute the number of hours in the given number of seconds 8 | hours = seconds // seconds_per_hour # 3600 seconds = 1 hour 9 | # Compute the remaining seconds after the hours are accounted for 10 | seconds = seconds % seconds_per_hour 11 | # Next, compute the number of minutes in the remaining number of seconds 12 | minutes = seconds // seconds_per_minute # 60 seconds = 1 minute 13 | # Compute the remaining seconds after the minutes are accounted for 14 | seconds = seconds % seconds_per_minute 15 | # Report the results 16 | if hours > 0: # Print hours at all? 17 | print(hours, end='') 18 | # Decide between singular and plural form of hours 19 | if hours == 1: 20 | print(" hour ", end='') 21 | else: 22 | print(" hours ", end='') 23 | if minutes > 0: # Print minutes at all? 24 | print(minutes, end='') 25 | # Decide between singular and plural form of minutes 26 | if minutes == 1: 27 | print(" minute ", end='') 28 | else: 29 | print(" minutes ", end='') 30 | # Print seconds at all? 31 | if seconds > 0 or (hours == 0 and minutes == 0 and seconds == 0): 32 | print(seconds, end='') 33 | # Decide between singular and plural form of seconds 34 | if seconds == 1: 35 | print(" second", end='') 36 | else: 37 | print(" seconds", end='') 38 | print() # Finally print the newline 39 | -------------------------------------------------------------------------------- /Chap4/troubleshoot.py: -------------------------------------------------------------------------------- 1 | print("Help! My computer doesn't work!") 2 | print("Does the computer make any sounds (fans, etc.)") 3 | choice = input("or show any lights? (y/n):") 4 | # The troubleshooting control logic 5 | if choice == 'n': # The computer does not have power 6 | choice = input("Is it plugged in? (y/n):") 7 | if choice == 'n': # It is not plugged in, plug it in 8 | print("Plug it in. If the problem persists, ") 9 | print("please run this program again.") 10 | else: # It is plugged in 11 | choice = input("Is the switch in the \"on\" position? (y/n):") 12 | if choice == 'n': # The switch is off, turn it on! 13 | print("Turn it on. If the problem persists, ") 14 | print("please run this program again.") 15 | else: # The switch is on 16 | choice = input("Does the computer have a fuse? (y/n):") 17 | if choice == 'n': # No fuse 18 | choice = input("Is the outlet OK? (y/n):") 19 | if choice == 'n': # Fix outlet 20 | print("Check the outlet's circuit ") 21 | print("breaker or fuse. Move to a") 22 | print("new outlet, if necessary. ") 23 | print("If the problem persists, ") 24 | print("please run this program again.") 25 | else: # Beats me! 26 | print("Please consult a service technician.") 27 | else: # Check fuse 28 | print("Check the fuse. Replace if ") 29 | print("necessary. If the problem ") 30 | print("persists, then ") 31 | print("please run this program again.") 32 | else: # The computer has power 33 | print("Please consult a service technician.") 34 | -------------------------------------------------------------------------------- /Chap5/abusefor.py: -------------------------------------------------------------------------------- 1 | # Abuse the for statement 2 | 3 | for i in range(10): 4 | print(i, end=' ') # Print i as served by the range object 5 | if i == 5: 6 | i = 20 # Change i inside the loop? 7 | print('({})'.format(i), end=' ') 8 | print() 9 | -------------------------------------------------------------------------------- /Chap5/addmiddleexit.py: -------------------------------------------------------------------------------- 1 | # Allow the user to enter a sequence of nonnegative 2 | # numbers. The user ends the list with a negative 3 | # number. At the end the sum of the nonnegative 4 | # numbers entered is displayed. The program prints 5 | # zero if the user provides no nonnegative numbers. 6 | 7 | entry = 0 # Ensure the loop is entered 8 | sum = 0 # Initialize sum 9 | 10 | # Request input from the user 11 | print("Enter numbers to sum, negative number ends list:") 12 | 13 | while True: # Loop forever? Not really 14 | entry = int(input()) # Get the value 15 | if entry < 0: # Is number negative number? 16 | break # If so, exit the loop 17 | sum += entry # Add entry to running sum 18 | print("Sum =", sum) # Display the sum 19 | -------------------------------------------------------------------------------- /Chap5/addnonnegatives.py: -------------------------------------------------------------------------------- 1 | # Allow the user to enter a sequence of nonnegative 2 | # integers. The user ends the list with a negative 3 | # integer. At the end the sum of the nonnegative 4 | # umbers entered is displayed. The program prints 5 | # zero if the user provides no nonnegative numbers. 6 | 7 | entry = 0 # Ensure the loop is entered 8 | sum = 0 # Initialize sum 9 | 10 | # Request input from the user 11 | print("Enter numbers to sum, negative number ends list:") 12 | 13 | while entry >= 0: # A negative number exits the loop 14 | entry = int(input()) # Get the value 15 | if entry >= 0: # Is number nonnegative? 16 | sum += entry # Only add it if it is nonnegative 17 | print("Sum =", sum) # Display the sum 18 | -------------------------------------------------------------------------------- /Chap5/betterinputonly.py: -------------------------------------------------------------------------------- 1 | # Require the user to enter an integer in the range 1-10 2 | in_value = 0 # Ensure loop entry 3 | attempts = 0 # Count the number of tries 4 | 5 | # Loop until the user supplies a valid number 6 | while in_value < 1 or in_value > 10: 7 | in_value = int(input("Please enter an integer in the range 0-10: ")) 8 | attempts += 1 9 | 10 | # Make singular or plural word as necessary 11 | tries = "try" if attempts == 1 else "tries" 12 | # in_value at this point is guaranteed to be within range 13 | print("It took you", attempts, tries, "to enter a valid number") 14 | -------------------------------------------------------------------------------- /Chap5/computesquareroot.py: -------------------------------------------------------------------------------- 1 | # File computesquareroot.py 2 | 3 | # Get value from the user 4 | val = float(input('Enter number: ')) 5 | # Compute a provisional square root 6 | root = 1.0 7 | 8 | # How far off is our provisional root? 9 | diff = root*root - val 10 | 11 | # Loop until the provisional root 12 | # is close enough to the actual root 13 | while diff > 0.00000001 or diff < -0.00000001: 14 | print(root, 'squared is', root*root) # Report how we are doing 15 | root = (root + val/root) / 2 # Compute new provisional root 16 | # How bad is our current approximation? 17 | diff = root*root - val 18 | 19 | # Report approximate square root 20 | print('Square root of', val, '=', root) 21 | -------------------------------------------------------------------------------- /Chap5/continueexample.py: -------------------------------------------------------------------------------- 1 | sum = 0 2 | done = False 3 | while not done: 4 | val = int(input("Enter positive integer (999 quits):")) 5 | if val < 0: 6 | print("Negative value", val, "ignored") 7 | continue # Skip rest of body for this iteration 8 | if val != 999: 9 | print("Tallying", val) 10 | sum += val 11 | else: 12 | done = (val == 999) # 999 entry exits loop 13 | print("sum =", sum) 14 | -------------------------------------------------------------------------------- /Chap5/counttofive.py: -------------------------------------------------------------------------------- 1 | print(1) 2 | print(2) 3 | print(3) 4 | print(4) 5 | print(5) 6 | -------------------------------------------------------------------------------- /Chap5/countup.py: -------------------------------------------------------------------------------- 1 | # Counts up from zero. The user continues the count by entering 2 | # 'Y'. The user discontinues the count by entering 'N'. 3 | 4 | count = 0 # The current count 5 | entry = 'Y' # Count to begin with 6 | 7 | while entry != 'N' and entry != 'n': 8 | # Print the current value of count 9 | print(count) 10 | entry = input('Please enter "Y" to continue or "N" to quit: ') 11 | if entry == 'Y' or entry == 'y': 12 | count += 1 # Keep counting 13 | # Check for "bad" entry 14 | elif entry != 'N' and entry != 'n': 15 | print('"' + entry + '" is not a valid choice') 16 | # else must be 'N' or 'n' 17 | -------------------------------------------------------------------------------- /Chap5/countvowels.py: -------------------------------------------------------------------------------- 1 | word = input('Enter text: ') 2 | vowel_count = 0 3 | for c in word: 4 | if c == 'A' or c == 'a' or c == 'E' or c == 'e' \ 5 | or c == 'I' or c == 'i' or c == 'O' or c == 'o': 6 | print(c, ', ', sep='', end='') # Print the vowel 7 | vowel_count += 1 # Count the vowel 8 | print(' (', vowel_count, ' vowels)', sep='') 9 | -------------------------------------------------------------------------------- /Chap5/countvowelselse.py: -------------------------------------------------------------------------------- 1 | word = input('Enter text (no X\'s, please): ') 2 | vowel_count = 0 3 | for c in word: 4 | if c == 'A' or c == 'a' or c == 'E' or c == 'e' \ 5 | or c == 'I' or c == 'i' or c == 'O' or c == 'o': 6 | print(c, ', ', sep='', end='') # Print the vowel 7 | vowel_count += 1 # Count the vowel 8 | elif c == 'X' or c =='x': 9 | print('X not allowed') 10 | break 11 | else: 12 | print(' (', vowel_count, ' vowels)', sep='') 13 | -------------------------------------------------------------------------------- /Chap5/countvowelsnox.py: -------------------------------------------------------------------------------- 1 | word = input('Enter text (no X\'s, please): ') 2 | vowel_count = 0 3 | for c in word: 4 | if c == 'A' or c == 'a' or c == 'E' or c == 'e' \ 5 | or c == 'I' or c == 'i' or c == 'O' or c == 'o': 6 | print(c, ', ', sep='', end='') # Print the vowel 7 | vowel_count += 1 # Count the vowel 8 | elif c == 'X' or c =='x': 9 | break 10 | print(' (', vowel_count, ' vowels)', sep='') 11 | -------------------------------------------------------------------------------- /Chap5/definite1.py: -------------------------------------------------------------------------------- 1 | n = 1 2 | while n <= 10: 3 | print(n) 4 | n += 1 5 | -------------------------------------------------------------------------------- /Chap5/definite2.py: -------------------------------------------------------------------------------- 1 | n = 1 2 | stop = int(input()) 3 | while n <= stop: 4 | print(n) 5 | n += 1 6 | -------------------------------------------------------------------------------- /Chap5/findfactors.py: -------------------------------------------------------------------------------- 1 | # List the factors of the integers 1...MAX 2 | MAX = 20 # MAX is 20 3 | n = 1 # Start with 1 4 | while n <= MAX: # Do not go past MAX 5 | factor = 1 # 1 is a factor of any integer 6 | print(end=str(n) + ': ') # Which integer are we examining? 7 | while factor <= n: # Factors are <= the number 8 | if n % factor == 0: # Test to see if factor is a factor of n 9 | print(factor, end=' ') # If so, display it 10 | factor += 1 # Try the next number 11 | print() # Move to next line for next n 12 | n += 1 13 | -------------------------------------------------------------------------------- /Chap5/findfactorsfor.py: -------------------------------------------------------------------------------- 1 | # List the factors of the integers 1...MAX 2 | MAX = 20 # MAX is 20 3 | for n in range(1, MAX + 1): # Consider numbers 1...MAX 4 | print(end=str(n) + ': ') # Which integer are we examining? 5 | for factor in range(1, n + 1): # Try factors 1...n 6 | if n % factor == 0: # Test to see if factor is a factor of n 7 | print(factor, end=' ') # If so, display it 8 | print() # Move to next line for next n 9 | -------------------------------------------------------------------------------- /Chap5/indefinite.py: -------------------------------------------------------------------------------- 1 | done = False # Enter the loop at least once 2 | while not done: 3 | entry = int(input()) # Get value from user 4 | if entry == 999: # Did user provide the magic number? 5 | done = True # If so, get out 6 | else: 7 | print(entry) # If not, print it and continue 8 | -------------------------------------------------------------------------------- /Chap5/iterativecounttofive.py: -------------------------------------------------------------------------------- 1 | count = 1 # Initialize counter 2 | while count <= 5: # Should we continue? 3 | print(count) # Display counter, then 4 | count += 1 # Increment counter 5 | -------------------------------------------------------------------------------- /Chap5/nocontinueexample.py: -------------------------------------------------------------------------------- 1 | sum = 0 2 | done = False 3 | while not done: 4 | val = int(input("Enter positive integer (999 quits):")) 5 | if val < 0: 6 | print("Negative value", val, "ignored") 7 | else: 8 | if val != 999: 9 | print("Tallying", val) 10 | sum += val 11 | else: 12 | done = (val == 999) # 999 entry exits loop 13 | print("sum =", sum) 14 | -------------------------------------------------------------------------------- /Chap5/permuteabc.py: -------------------------------------------------------------------------------- 1 | # File permuteabc.py 2 | 3 | # The first letter varies from A to C 4 | for first in 'ABC': 5 | for second in 'ABC': # The second varies from A to C 6 | if second != first: # No duplicate letters allowed 7 | for third in 'ABC': # The third varies from A to C 8 | # Don't duplicate first or second letter 9 | if third != first and third != second: 10 | print(first + second + third) 11 | -------------------------------------------------------------------------------- /Chap5/permuteabcd.py: -------------------------------------------------------------------------------- 1 | # File permuteabcd.py 2 | 3 | # The first letter varies from A to D 4 | for first in 'ABCD': 5 | for second in 'ABCD': # The second varies from A to D 6 | if second != first: # No duplicate letters allowed 7 | for third in 'ABCD': # The third varies from A to D 8 | # Don't duplicate first or second letter 9 | if third != first and third != second: 10 | for fourth in 'ABCD': # The fourth varies from A to D 11 | if fourth != first and fourth != second and fourth != third: 12 | print(first + second + third + fourth) 13 | -------------------------------------------------------------------------------- /Chap5/powers10loop.py: -------------------------------------------------------------------------------- 1 | for i in range(16): 2 | print('{0:3} {1:16}'.format(i, 10**i)) 3 | -------------------------------------------------------------------------------- /Chap5/printprimes.py: -------------------------------------------------------------------------------- 1 | max_value = int(input('Display primes up to what value? ')) 2 | value = 2 # Smallest prime number 3 | while value <= max_value: 4 | # See if value is prime 5 | is_prime = True # Provisionally, value is prime 6 | # Try all possible factors from 2 to value - 1 7 | trial_factor = 2 8 | while trial_factor < value: 9 | if value % trial_factor == 0: 10 | is_prime = False # Found a factor 11 | break # No need to continue; it is NOT prime 12 | trial_factor += 1 # Try the next potential factor 13 | if is_prime: 14 | print(value, end= ' ') # Display the prime number 15 | value += 1 # Try the next potential prime number 16 | print() # Move cursor down to next line 17 | -------------------------------------------------------------------------------- /Chap5/printprimesfor.py: -------------------------------------------------------------------------------- 1 | max_value = int(input('Display primes up to what value? ')) 2 | # Try values from 2 (smallest prime number) to max_value 3 | for value in range(2, max_value + 1): 4 | # See if value is prime 5 | is_prime = True # Provisionally, value is prime 6 | # Try all possible factors from 2 to value - 1 7 | for trial_factor in range(2, value): 8 | if value % trial_factor == 0: 9 | is_prime = False # Found a factor 10 | break # No need to continue; it is NOT prime 11 | if is_prime: 12 | print(value, end= ' ') # Display the prime number 13 | print() # Move cursor down to next line 14 | -------------------------------------------------------------------------------- /Chap5/printprimesforelse.py: -------------------------------------------------------------------------------- 1 | max_value = int(input('Display primes up to what value? ')) 2 | # Try values from 2 (smallest prime number) to max_value 3 | for value in range(2, max_value + 1): 4 | # See if value is prime: try all possible factors from 2 to value - 1 5 | for trial_factor in range(2, value): 6 | if value % trial_factor == 0: 7 | break # Found a factor, no need to continue; it is NOT prime 8 | else: 9 | print(value, end= ' ') # Display the prime number 10 | print() # Move cursor down to next line 11 | -------------------------------------------------------------------------------- /Chap5/startree.py: -------------------------------------------------------------------------------- 1 | # Get tree height from user 2 | height = int(input('Enter height of tree: ')) 3 | 4 | # Draw one row for every unit of height 5 | row = 0 6 | while row < height: 7 | # Print leading spaces; as row gets bigger, the number of 8 | # leading spaces gets smaller 9 | count = 0 10 | while count < height - row: 11 | print(end=' ') 12 | count += 1 13 | 14 | # Print out stars, twice the current row plus one: 15 | # 1. number of stars on left side of tree 16 | # = current row value 17 | # 2. exactly one star in the center of tree 18 | # 3. number of stars on right side of tree 19 | # = current row value 20 | count = 0 21 | while count < 2*row + 1: 22 | print(end='*') 23 | count += 1 24 | # Move cursor down to next line 25 | print() 26 | row += 1 # Consider next row 27 | -------------------------------------------------------------------------------- /Chap5/startreefor.py: -------------------------------------------------------------------------------- 1 | # Get tree height from user 2 | height = int(input('Enter height of tree: ')) 3 | 4 | # Draw one row for every unit of height 5 | for row in range(height): 6 | # Print leading spaces; as row gets bigger, the number of 7 | # leading spaces gets smaller 8 | for count in range(height - row): 9 | print(end=' ') 10 | 11 | # Print out stars, twice the current row plus one: 12 | # 1. number of stars on left side of tree 13 | # = current row value 14 | # 2. exactly one star in the center of tree 15 | # 3. number of stars on right side of tree 16 | # = current row value 17 | for count in range(2*row + 1): 18 | print(end='*') 19 | # Move cursor down to next line 20 | print() 21 | -------------------------------------------------------------------------------- /Chap5/stopatone.py: -------------------------------------------------------------------------------- 1 | x = 0.0 2 | while x != 1.0: 3 | print(x) 4 | x += 0.1 5 | print("Done") 6 | -------------------------------------------------------------------------------- /Chap5/stopatonefixed.py: -------------------------------------------------------------------------------- 1 | x = 0.0 2 | while x != 1.0: 3 | print(x) 4 | x += 0.1 5 | print("Done") 6 | -------------------------------------------------------------------------------- /Chap5/stringletters.py: -------------------------------------------------------------------------------- 1 | word = input('Enter a word: ') 2 | for letter in word: 3 | print(letter) 4 | -------------------------------------------------------------------------------- /Chap5/stringliteralletters.py: -------------------------------------------------------------------------------- 1 | for c in 'ABCDEF': 2 | print('[', c, ']', end='', sep='') 3 | print() 4 | -------------------------------------------------------------------------------- /Chap5/timestable1.py: -------------------------------------------------------------------------------- 1 | # Get the number of rows and columns in the table 2 | size = int(input("Please enter the table size: ")) 3 | # Print a size x size multiplication table 4 | for row in range(1, size + 1): 5 | print("Row #", row) 6 | -------------------------------------------------------------------------------- /Chap5/timestable2.py: -------------------------------------------------------------------------------- 1 | # Get the number of rows and columns in the table 2 | size = int(input("Please enter the table size: ")) 3 | # Print a size x size multiplication table 4 | for row in range(1, size + 1): 5 | for column in range(1, size + 1): 6 | product = row*column # Compute product 7 | print(product, end=' ') # Display product 8 | print() # Move cursor to next row 9 | -------------------------------------------------------------------------------- /Chap5/timestable3.py: -------------------------------------------------------------------------------- 1 | # Get the number of rows and columns in the table 2 | size = int(input("Please enter the table size: ")) 3 | # Print a size x size multiplication table 4 | for row in range(1, size + 1): 5 | for column in range(1, size + 1): 6 | product = row*column # Compute product 7 | print('{0:4}'.format(product), end='') # Display product 8 | print() # Move cursor to next row 9 | -------------------------------------------------------------------------------- /Chap5/timestable4.py: -------------------------------------------------------------------------------- 1 | # Get the number of rows and columns in the table 2 | size = int(input("Please enter the table size: ")) 3 | # Print a size x size multiplication table 4 | # First, print heading: 1 2 3 4 5 etc. 5 | print(" ", end='') 6 | # Print column heading 7 | for column in range(1, size + 1): 8 | print('{0:4}'.format(column), end='') # Display column number 9 | print() # Go down to the next line 10 | # Print line separator: +------------------ 11 | print(" +", end='') 12 | for column in range(1, size + 1): 13 | print('----', end='') # Display line 14 | print() # Drop down to next line 15 | 16 | # Print table contents 17 | for row in range(1, size + 1): 18 | print('{0:3} |'.format(row), end='') # Print heading for this row 19 | for column in range(1, size + 1): 20 | product = row*column # Compute product 21 | print('{0:4}'.format(product), end='') # Display product 22 | print() # Move cursor to next row 23 | -------------------------------------------------------------------------------- /Chap5/troubleshootloop.py: -------------------------------------------------------------------------------- 1 | print("Help! My computer doesn't work!") 2 | done = False # Not done initially 3 | while not done: 4 | print("Does the computer make any sounds (fans, etc.) ") 5 | choice = input("or show any lights? (y/n):") 6 | # The troubleshooting control logic 7 | if choice == 'n': # The computer does not have power 8 | choice = input("Is it plugged in? (y/n):") 9 | if choice == 'n': # It is not plugged in, plug it in 10 | print("Plug it in.") 11 | else: # It is plugged in 12 | choice = input("Is the switch in the \"on\" position? (y/n):") 13 | if choice == 'n': # The switch is off, turn it on! 14 | print("Turn it on.") 15 | else: # The switch is on 16 | choice = input("Does the computer have a fuse? (y/n):") 17 | if choice == 'n': # No fuse 18 | choice = input("Is the outlet OK? (y/n):") 19 | if choice == 'n': # Fix outlet 20 | print("Check the outlet's circuit ") 21 | print("breaker or fuse. Move to a") 22 | print("new outlet, if necessary. ") 23 | else: # Beats me! 24 | print("Please consult a service technician.") 25 | done = True # Nothing else I can do 26 | else: # Check fuse 27 | print("Check the fuse. Replace if ") 28 | print("necessary.") 29 | else: # The computer has power 30 | print("Please consult a service technician.") 31 | done = True # Nothing else I can do 32 | -------------------------------------------------------------------------------- /Chap5/troubleshootloop2.py: -------------------------------------------------------------------------------- 1 | print("Help! My computer doesn't work!") 2 | while True: 3 | print("Does the computer make any sounds (fans, etc.)") 4 | choice = input(" or show any lights? (y/n):") 5 | # The troubleshooting control logic 6 | if choice == 'n': # The computer does not have power 7 | choice = input("Is it plugged in? (y/n):") 8 | if choice == 'n': # It is not plugged in, plug it in 9 | print("Plug it in.") 10 | else: # It is plugged in 11 | choice = input("Is the switch in the \"on\" position? (y/n):") 12 | if choice == 'n': # The switch is off, turn it on! 13 | print("Turn it on.") 14 | else: # The switch is on 15 | choice = input("Does the computer have a fuse? (y/n):") 16 | if choice == 'n': # No fuse 17 | choice = input("Is the outlet OK? (y/n):") 18 | if choice == 'n': # Fix outlet 19 | print("Check the outlet's circuit ") 20 | print("breaker or fuse. Move to a") 21 | print("new outlet, if necessary. ") 22 | else: # Beats me! 23 | print("Please consult a service technician.") 24 | break # Nothing else I can do, exit loop 25 | else: # Check fuse 26 | print("Check the fuse. Replace if ") 27 | print("necessary.") 28 | else: # The computer has power 29 | print("Please consult a service technician.") 30 | break # Nothing else I can do, exit loop 31 | -------------------------------------------------------------------------------- /Chap5/whileelse.py: -------------------------------------------------------------------------------- 1 | # Add five nonnegative numbers supplied by the user 2 | count = sum = 0 3 | print('Please provide five nonnegative numbers when prompted') 4 | while count < 5: 5 | # Get value from the user 6 | val = float(input('Enter number: ')) 7 | if val < 0: 8 | print('Negative numbers not acceptable! Terminating') 9 | break 10 | count += 1 11 | sum += val 12 | else: 13 | print('Average =', sum/count) 14 | -------------------------------------------------------------------------------- /Chap5/whileexitattop.py: -------------------------------------------------------------------------------- 1 | x = 10 2 | while x == 10: 3 | print('First print statement in the while loop') 4 | x = 5 # Condition no longer true; do we exit immediately? 5 | print('Second print statement in the while loop') 6 | -------------------------------------------------------------------------------- /Chap5/whilenoelse.py: -------------------------------------------------------------------------------- 1 | # Add five nonnegative numbers supplied by the user 2 | count = sum = 0 3 | print('Please provide five nonnegative numbers when prompted') 4 | while count < 5: 5 | # Get value from the user 6 | val = float(input('Enter number: ')) 7 | if val < 0: 8 | break 9 | count += 1 10 | sum += val 11 | if count < 5: 12 | print('Negative numbers not acceptable! Terminating') 13 | else: 14 | print('Average =', sum/count) 15 | -------------------------------------------------------------------------------- /Chap6/addintegers4.py: -------------------------------------------------------------------------------- 1 | num1, num2 = eval(input('Please enter number 1, number 2: ')) 2 | print(num1, '+', num2, '=', num1 + num2) 3 | -------------------------------------------------------------------------------- /Chap6/boxturtle.py: -------------------------------------------------------------------------------- 1 | # Draws a rectangular box in the window 2 | 3 | import turtle 4 | 5 | turtle.pencolor('red') # Set pen color to red 6 | turtle.forward(200) # Move pen forward 200 units (create bottom of rectangle) 7 | turtle.left(90) # Turn pen by 90 degrees 8 | turtle.pencolor('blue') # Change pen color to blue 9 | turtle.forward(150) # Move pen forward 150 units (create right wall) 10 | turtle.left(90) # Turn pen by 90 degrees 11 | turtle.pencolor('green') # Change pen color to green 12 | turtle.forward(200) # Move pen forward 200 units (create top) 13 | turtle.left(90) # Turn pen by 90 degrees 14 | turtle.pencolor('black') # Change pen color to black 15 | turtle.forward(150) # Move pen forward 150 units (create left wall) 16 | turtle.hideturtle() # Make pen invisible 17 | turtle.exitonclick() # Wait for user input 18 | -------------------------------------------------------------------------------- /Chap6/countdown.py: -------------------------------------------------------------------------------- 1 | from time import sleep 2 | 3 | for count in range(10, -1, -1): # Range 10, 9, 8, ..., 0 4 | print(count) # Display the count 5 | sleep(1) # Suspend execution for 1 second 6 | -------------------------------------------------------------------------------- /Chap6/die.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | # Roll the die three times 4 | for i in range(0, 3): 5 | # Generate random number in the range 1...7 6 | value = randrange(1, 7) 7 | 8 | # Show the die 9 | print("+-------+") 10 | if value == 1: 11 | print("| |") 12 | print("| * |") 13 | print("| |") 14 | elif value == 2: 15 | print("| * |") 16 | print("| |") 17 | print("| * |") 18 | elif value == 3: 19 | print("| * |") 20 | print("| * |") 21 | print("| * |") 22 | elif value == 4: 23 | print("| * * |") 24 | print("| |") 25 | print("| * * |") 26 | elif value == 5: 27 | print("| * * |") 28 | print("| * |") 29 | print("| * * |") 30 | elif value == 6: 31 | print("| * * * |") 32 | print("| |") 33 | print("| * * * |") 34 | else: 35 | print(" *** Error: illegal die value ***") 36 | print("+-------+") 37 | -------------------------------------------------------------------------------- /Chap6/enterarith.py: -------------------------------------------------------------------------------- 1 | print(eval(input())) 2 | -------------------------------------------------------------------------------- /Chap6/evalfunc.py: -------------------------------------------------------------------------------- 1 | x1 = eval(input('Entry x1? ')) 2 | print('x1 =', x1, ' type:', type(x1)) 3 | 4 | x2 = eval(input('Entry x2? ')) 5 | print('x2 =', x2, ' type:', type(x2)) 6 | 7 | x3 = eval(input('Entry x3? ')) 8 | print('x3 =', x3, ' type:', type(x3)) 9 | 10 | x4 = eval(input('Entry x4? ')) 11 | print('x4 =', x4, ' type:', type(x4)) 12 | 13 | x5 = eval(input('Entry x5? ')) 14 | print('x5 =', x5, ' type:', type(x5)) 15 | -------------------------------------------------------------------------------- /Chap6/exitprogram.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | sum = 0 4 | while True: 5 | x = int(input('Enter a number (999 ends):')) 6 | if x == 999: 7 | sys.exit(0) 8 | sum += x 9 | print('Sum is', sum) 10 | -------------------------------------------------------------------------------- /Chap6/measureprimespeed.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | 3 | max_value = 10000 4 | count = 0 5 | start_time = clock() # Start timer 6 | # Try values from 2 (smallest prime number) to max_value 7 | for value in range(2, max_value + 1): 8 | # See if value is prime 9 | is_prime = True # Provisionally, value is prime 10 | # Try all possible factors from 2 to value - 1 11 | for trial_factor in range(2, value): 12 | if value % trial_factor == 0: 13 | is_prime = False # Found a factor 14 | break # No need to continue; it is NOT prime 15 | if is_prime: 16 | count += 1 # Count the prime number 17 | print() # Move cursor down to next line 18 | elapsed = clock() - start_time # Stop the timer 19 | print("Count:", count, " Elapsed time:", elapsed, "sec") 20 | -------------------------------------------------------------------------------- /Chap6/moreefficientprimes.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | max_value = int(input('Display primes up to what value? ')) 4 | value = 2 # Smallest prime number 5 | 6 | while value <= max_value: 7 | # See if value is prime 8 | is_prime = True # Provisionally, value is prime 9 | # Try all possible factors from 2 to value - 1 10 | trial_factor = 2 11 | root = sqrt(value) # Compute the square root of value 12 | while trial_factor <= root: 13 | if value % trial_factor == 0: 14 | is_prime = False # Found a factor 15 | break # No need to continue; it is NOT prime 16 | trial_factor += 1 # Try the next potential factor 17 | if is_prime: 18 | print(value, end= ' ') # Display the prime number 19 | value += 1 # Try the next potential prime number 20 | 21 | print() # Move cursor down to next line 22 | -------------------------------------------------------------------------------- /Chap6/myinterpreter.py: -------------------------------------------------------------------------------- 1 | while True: 2 | exec(input(">>>")) 3 | -------------------------------------------------------------------------------- /Chap6/noanimation.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | y = -200 # Initial y value 4 | 5 | # Turn off animation 6 | turtle.tracer(0) 7 | turtle.color("red") 8 | for x in range(10): 9 | turtle.penup() 10 | turtle.setposition(-200, y) 11 | turtle.pendown() 12 | turtle.forward(400) 13 | y += 10 14 | 15 | turtle.color("blue") 16 | for x in range(10): 17 | turtle.penup() 18 | turtle.setposition(-200, y) 19 | turtle.pendown() 20 | turtle.forward(400) 21 | y += 10 22 | 23 | turtle.color("green") 24 | for x in range(10): 25 | turtle.penup() 26 | turtle.setposition(-200, y) 27 | turtle.pendown() 28 | turtle.forward(400) 29 | y += 10 30 | 31 | turtle.color("black") 32 | for x in range(10): 33 | turtle.penup() 34 | turtle.setposition(-200, y) 35 | turtle.pendown() 36 | turtle.forward(400) 37 | y += 10 38 | 39 | turtle.update() # Ensure all of image is drawn 40 | turtle.done() 41 | -------------------------------------------------------------------------------- /Chap6/octogon.py: -------------------------------------------------------------------------------- 1 | # Draws in the window a spiral surrounded with an octagon 2 | 3 | import turtle 4 | 5 | # Draw a red octogon centered at (-45, 100) 6 | turtle.pencolor('red') # Set pen color 7 | turtle.penup() # Lift pen to move it 8 | turtle.setposition(-45, 100) # Move the pen to coordinates (-45, 100) 9 | turtle.pendown() # Place pen to begin drawing 10 | for i in range(8): # Draw the eight sides 11 | turtle.forward(80) # Each side is 80 units long 12 | turtle.right(45) # Each vertex is 45 degrees 13 | 14 | 15 | # Draw a blue spiral centered at (0, 0) 16 | distance = 0.2 17 | angle = 40 18 | turtle.pencolor('blue') # Set pen color 19 | turtle.penup() # Left pen to move it 20 | turtle.setposition(0, 0) # Position the pen at coordinates (0, 0) 21 | turtle.pendown() # Set pen down to begin drawing 22 | for i in range(100): 23 | turtle.forward(distance) 24 | turtle.left(angle) 25 | distance += 0.5 26 | 27 | turtle.hideturtle() # Make pen invisible 28 | turtle.exitonclick() # Quit program when user clicks mouse button 29 | -------------------------------------------------------------------------------- /Chap6/octogon2.py: -------------------------------------------------------------------------------- 1 | # Draws in the window a spiral surrounded with an octagon 2 | 3 | import turtle as t # Use a shorter name for turtle module 4 | 5 | t.delay(0) # Draw as quickly as possible 6 | t.speed(0) # Turtle's action as fast as possible 7 | t.hideturtle() # Do not show the pen 8 | # Draw a red octogon centered at (-45, 100) 9 | t.pencolor('red') # Set pen color 10 | t.penup() # Lift pen to move it 11 | t.setposition(-45, 100) # Move the pen to coordinates (-45, 100) 12 | t.pendown() # Place pen to begin drawing 13 | for i in range(8): # Draw the eight sides 14 | t.forward(80) # Each side is 80 units long 15 | t.right(45) # Each vertex is 45 degrees 16 | 17 | 18 | # Draw a blue spiral centered at (0, 0) 19 | distance = 0.2 20 | angle = 40 21 | t.pencolor('blue') # Set pen color 22 | t.penup() # Left pen to move it 23 | t.setposition(0, 0) # Position the pen at coordinates (0, 0) 24 | t.pendown() # Set pen down to begin drawing 25 | for i in range(100): 26 | t.forward(distance) 27 | t.left(angle) 28 | distance += 0.5 29 | 30 | t.exitonclick() # Quit program when user clicks the mouse button 31 | -------------------------------------------------------------------------------- /Chap6/orbitdist.py: -------------------------------------------------------------------------------- 1 | # Use some functions and values from the math module 2 | from math import sqrt, sin, cos, pi, radians 3 | 4 | # Get coordinates of the stationary spacecraft, (px, py) 5 | px = float(input("Enter x coordinate of spacecraft: ")) 6 | py = float(input("Enter y coordinate of spacecraft: ")) 7 | 8 | # Get starting coordinates of satellite, (x1, y1) 9 | x = float(input("Enter initial satellite x coordinate: ")) 10 | y = float(input("Enter initial satellite y coordinate: ")) 11 | 12 | # Convert 60 degrees to radians to be able to use the trigonometric functions 13 | rads = radians(60) 14 | 15 | # Precompute the cosine and sine of the angle 16 | COS_theta = cos(rads) 17 | SIN_theta = sin(rads) 18 | 19 | # Make a complete revolution (6*60 = 360 degrees) 20 | for increment in range(0, 7): 21 | # Compute the distance to the satellite 22 | dist = sqrt((px - x)*(px - x) + (py - y)*(py - y)) 23 | print('Distance to satellite {0:10.2f} km'.format(dist)) 24 | # Compute the satellite's new (x, y) location after rotating by 60 degrees 25 | x, y = x*COS_theta - y*SIN_theta, x*SIN_theta + y*COS_theta 26 | -------------------------------------------------------------------------------- /Chap6/randomstring.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | for i in range(10): 4 | print(choice(("one", "two", "three", "four", "five", "six", 5 | "seven", "eight", "nine", "ten"))) 6 | -------------------------------------------------------------------------------- /Chap6/simplerandom.py: -------------------------------------------------------------------------------- 1 | from random import randrange, seed 2 | 3 | seed(23) # Set random number seed 4 | for i in range(0, 100): # Print 100 random numbers 5 | print(randrange(1, 1001), end=' ') # Range 1...1,000, inclusive 6 | print() # Print newine 7 | -------------------------------------------------------------------------------- /Chap6/speedvsdelay.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | y = -200 # Initial y value 4 | 5 | # Default speed and default delay 6 | turtle.color("red") 7 | for x in range(10): 8 | turtle.penup() 9 | turtle.setposition(-200, y) 10 | turtle.pendown() 11 | turtle.forward(400) 12 | y += 10 13 | 14 | # Slowest speed, but no delay 15 | turtle.speed("slowest") 16 | turtle.delay(0) 17 | turtle.update() 18 | turtle.color("blue") 19 | for x in range(10): 20 | turtle.penup() 21 | turtle.setposition(-200, y) 22 | turtle.pendown() 23 | turtle.forward(400) 24 | y += 10 25 | 26 | 27 | # Fastest speed with a 500 millisecond delay 28 | turtle.speed("fastest") 29 | turtle.delay(500) 30 | turtle.update() 31 | turtle.color("green") 32 | for x in range(10): 33 | turtle.penup() 34 | turtle.setposition(-200, y) 35 | turtle.pendown() 36 | turtle.forward(400) 37 | y += 10 38 | 39 | # Fastest speed with no delay 40 | turtle.speed("fastest") 41 | turtle.delay(0) 42 | turtle.update() 43 | turtle.color("black") 44 | for x in range(10): 45 | turtle.penup() 46 | turtle.setposition(-200, y) 47 | turtle.pendown() 48 | turtle.forward(400) 49 | y += 10 50 | 51 | turtle.done() 52 | -------------------------------------------------------------------------------- /Chap6/standardsquareroot.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | # Get value from the user 4 | num = float(input("Enter number: ")) 5 | 6 | # Compute the square root 7 | root = sqrt(num) 8 | 9 | # Report result 10 | print("Square root of", num, "=", root) 11 | -------------------------------------------------------------------------------- /Chap6/timeaddition.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | 3 | sum = 0 # Initialize sum accumulator 4 | start = clock() # Start the stopwatch 5 | for n in range(1, 100000001): # Sum the numbers 6 | sum += n 7 | elapsed = clock() - start # Stop the stopwatch 8 | print("sum:", sum, "time:", elapsed) # Report results 9 | -------------------------------------------------------------------------------- /Chap6/timeit.py: -------------------------------------------------------------------------------- 1 | from time import clock 2 | 3 | print("Enter your name: ", end="") 4 | start_time = clock() 5 | name = input() 6 | elapsed = clock() - start_time 7 | print(name, "it took you", elapsed, "seconds to respond") 8 | -------------------------------------------------------------------------------- /Chap6/timemoreefficientprimes.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | from time import clock 3 | 4 | max_value = 10000 5 | count = 0 6 | value = 2 # Smallest prime number 7 | start = clock() # Start the stopwatch 8 | while value <= max_value: 9 | # See if value is prime 10 | is_prime = True # Provisionally, value is prime 11 | # Try all possible factors from 2 to value - 1 12 | trial_factor = 2 13 | root = sqrt(value) 14 | while trial_factor <= root: 15 | if value % trial_factor == 0: 16 | is_prime = False # Found a factor 17 | break # No need to continue; it is NOT prime 18 | trial_factor += 1 # Try the next potential factor 19 | if is_prime: 20 | count += 1 # Count the prime number 21 | value += 1 # Try the next potential prime number 22 | elapsed = clock() - start # Stop the stopwatch 23 | print("Count:", count, " Elapsed time:", elapsed, "sec") 24 | -------------------------------------------------------------------------------- /Chap6/usingsqrt.py: -------------------------------------------------------------------------------- 1 | # This program shows the various ways the 2 | # sqrt function can be used. 3 | 4 | from math import sqrt 5 | 6 | x = 16 7 | # Pass a literal value and display the result 8 | print(sqrt(16.0)) 9 | # Pass a variable and display the result 10 | print(sqrt(x)) 11 | # Pass an expression 12 | print(sqrt(2 * x - 5)) 13 | # Assign result to variable 14 | y = sqrt(x) 15 | print(y) 16 | # Use result in an expression 17 | y = 2 * sqrt(x + 16) - 4 18 | print(y) 19 | # Use result as argument to a function call 20 | y = sqrt(sqrt(256.0)) 21 | print(y) 22 | print(sqrt(int('45'))) 23 | -------------------------------------------------------------------------------- /Chap7/badfloatcheck.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | # Count to ten by tenths 3 | i = 0.0 4 | while i != 1.0: 5 | print("i =", i) 6 | i += 0.1 7 | 8 | 9 | main() 10 | -------------------------------------------------------------------------------- /Chap7/betterdie.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | def show_die(spots): 4 | """ 5 | Draws a picture of a die with number of spots indicated. 6 | spots is the number of spots on the top face. 7 | """ 8 | print("+-------+") 9 | if spots == 1: 10 | print("| |") 11 | print("| * |") 12 | print("| |") 13 | elif spots == 2: 14 | print("| * |") 15 | print("| |") 16 | print("| * |") 17 | elif spots == 3: 18 | print("| * |") 19 | print("| * |") 20 | print("| * |") 21 | elif spots == 4: 22 | print("| * * |") 23 | print("| |") 24 | print("| * * |") 25 | elif spots == 5: 26 | print("| * * |") 27 | print("| * |") 28 | print("| * * |") 29 | elif spots == 6: 30 | print("| * * * |") 31 | print("| |") 32 | print("| * * * |") 33 | else: 34 | print(" *** Error: illegal die value ***") 35 | print("+-------+") 36 | 37 | 38 | def roll(): 39 | """ Returns a pseudorandom number in the range 1...6, inclusive """ 40 | return randrange(1, 7) 41 | 42 | 43 | def main(): 44 | """ Simulates the roll of a die three times """ 45 | # Roll the die three times 46 | for i in range(0, 3): 47 | show_die(roll()) 48 | 49 | 50 | main() # Run the program 51 | -------------------------------------------------------------------------------- /Chap7/betterinputfunc.py: -------------------------------------------------------------------------------- 1 | def get_int_in_range(first, last): 2 | """ 3 | Forces the user to enter an integer within a specified range. 4 | first is either a minimum or maximum acceptable value. 5 | last is the corresponding other end of the range, either a maximum or minimum value. 6 | Returns an acceptable value from the user. 7 | """ 8 | # If the larger number is provided first, 9 | # switch the parameters 10 | if first > last: 11 | first, last = last, first 12 | # Insist on values in the range first...last 13 | in_value = int(input("Please enter values in the range " \ 14 | + str(first) + "..." + str(last) + ": ")) 15 | while in_value < first or in_value > last: 16 | print(in_value, "is not in the range", first, "...", last) 17 | in_value = int(input("Please try again: ")) 18 | # in_value at this point is guaranteed to be within range 19 | return in_value 20 | 21 | 22 | def main(): 23 | """ Tests the get_int_in_range function """ 24 | print(get_int_in_range(10, 20)) 25 | print(get_int_in_range(20, 10)) 26 | print(get_int_in_range(5, 5)) 27 | print(get_int_in_range(-100, 100)) 28 | 29 | 30 | main() # Run the program 31 | -------------------------------------------------------------------------------- /Chap7/calculator.py: -------------------------------------------------------------------------------- 1 | def help_screen(): 2 | """ 3 | Displays information about how the program works. 4 | Accepts no parameters. 5 | Returns nothing. 6 | """ 7 | print("Add: Adds two numbers") 8 | print("Subtract: Subtracts two numbers") 9 | print("Print: Displays the result of the latest operation") 10 | print("Help: Displays this help screen") 11 | print("Quit: Exits the program") 12 | 13 | 14 | def menu(): 15 | """ 16 | Displays a menu 17 | Accepts no parameters 18 | Returns the string entered by the user. 19 | """ 20 | return input("=== A)dd S)ubtract P)rint H)elp Q)uit ===") 21 | 22 | 23 | def main(): 24 | """ Runs a command loop that allows users to perform simple arithmetic. """ 25 | result = 0.0 26 | done = False # Initially not done 27 | while not done: 28 | choice = menu() # Get user's choice 29 | 30 | if choice == "A" or choice == "a": # Addition 31 | arg1 = float(input("Enter arg 1: ")) 32 | arg2 = float(input("Enter arg 2: ")) 33 | result = arg1 + arg2 34 | print(result) 35 | elif choice == "S" or choice == "s": # Subtraction 36 | arg1 = float(input("Enter arg 1: ")) 37 | arg2 = float(input("Enter arg 2: ")) 38 | result = arg1 - arg2 39 | print(result) 40 | elif choice == "P" or choice == "p": # Print 41 | print(result) 42 | elif choice == "H" or choice == "h": # Help 43 | help_screen() 44 | elif choice == "Q" or choice == "q": # Quit 45 | done = True 46 | 47 | 48 | main() 49 | -------------------------------------------------------------------------------- /Chap7/countto10.py: -------------------------------------------------------------------------------- 1 | # Counts to ten 2 | for i in range(1, 11): 3 | print(i, end=' ') 4 | print() 5 | -------------------------------------------------------------------------------- /Chap7/countto10func.py: -------------------------------------------------------------------------------- 1 | # Count to ten and print each number on its own line 2 | def count_to_10(): 3 | for i in range(1, 11): 4 | print(i, end=' ') 5 | print() 6 | 7 | 8 | print("Going to count to ten . . .") 9 | count_to_10() 10 | print("Going to count to ten again. . .") 11 | count_to_10() 12 | -------------------------------------------------------------------------------- /Chap7/countton.py: -------------------------------------------------------------------------------- 1 | # Count to n and print each number 2 | def count_to_n(n): 3 | for i in range(1, n + 1): 4 | print(i, end=' ') 5 | print() 6 | 7 | 8 | print("Going to count to ten . . .") 9 | count_to_n(10) 10 | print("Going to count to five . . .") 11 | count_to_n(5) 12 | -------------------------------------------------------------------------------- /Chap7/countwithvariable.py: -------------------------------------------------------------------------------- 1 | def count_to_n(n): 2 | for i in range(1, n + 1): 3 | print(i, end=' ') 4 | print() 5 | 6 | 7 | for i in range(1, 10): 8 | count_to_n(i) 9 | -------------------------------------------------------------------------------- /Chap7/customsquareroot.py: -------------------------------------------------------------------------------- 1 | # File customsquareroot.py 2 | 3 | def square_root(val): 4 | """ Compute an approximation of the square root of x """ 5 | # Compute a provisional square root 6 | root = 1.0 7 | 8 | # How far off is our provisional root? 9 | diff = root*root - val 10 | 11 | # Loop until the provisional root 12 | # is close enough to the actual root 13 | while diff > 0.00000001 or diff < -0.00000001: 14 | root = (root + val/root) / 2 # Compute new provisional root 15 | # How bad is our current approximation? 16 | diff = root*root - val 17 | 18 | return root 19 | 20 | 21 | # Use the standard square root function to compare with our custom function 22 | from math import sqrt 23 | 24 | d = 1.0 25 | while d <= 10.0: 26 | print('{0:6.1f}: {1:16.8f} {2:16.8f}' \ 27 | .format(d, square_root(d), sqrt(d))) 28 | d += 0.5 # Next d 29 | -------------------------------------------------------------------------------- /Chap7/docgcd.py: -------------------------------------------------------------------------------- 1 | def gcd(n1, n2): 2 | """ Computes the greatest common divisor of integers n1 and n2. """ 3 | # Determine the smaller of n1 and n2 4 | min = n1 if n1 < n2 else n2 5 | # 1 definitely is a common factor to all ints 6 | largest_factor = 1 7 | for i in range(1, min + 1): 8 | if n1 % i == 0 and n2 % i == 0: 9 | largest_factor = i # Found larger factor 10 | return largest_factor 11 | -------------------------------------------------------------------------------- /Chap7/doublenumber.py: -------------------------------------------------------------------------------- 1 | def double(n): 2 | return 2 * n # Return twice the given number 3 | 4 | # Call the function with the value 3 and print its result 5 | x = double(3) 6 | print(x) 7 | -------------------------------------------------------------------------------- /Chap7/floatequalsfunction.py: -------------------------------------------------------------------------------- 1 | from math import fabs 2 | 3 | def equals(a, b, tolerance): 4 | """ 5 | Returns true if a = b or |a - b| < tolerance. 6 | If a and b differ by only a small amount (specified by tolerance), a and b are considered 7 | "equal." Useful to account for floating-point round-off error. 8 | The == operator is checked first since some special floating-point values such as 9 | floating-point infinity require an exact equality check. 10 | """ 11 | return a == b or fabs(a - b) < tolerance 12 | 13 | 14 | def main(): 15 | """ Try out the equals function """ 16 | i = 0.0 17 | while not equals(i, 1.0, 0.0001): 18 | print("i =", i) 19 | i += 0.1 20 | 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /Chap7/gcdfunc.py: -------------------------------------------------------------------------------- 1 | # Compute the greatest common factor of two integers 2 | # provided by the user 3 | 4 | 5 | def gcd(n1, n2): 6 | # Determine the smaller of n1 and n2 7 | min = n1 if n1 < n2 else n2 8 | # 1 definitely is a common factor to all ints 9 | largest_factor = 1 10 | for i in range(1, min + 1): 11 | if n1 % i == 0 and n2 % i == 0: 12 | largest_factor = i # Found larger factor 13 | return largest_factor 14 | 15 | 16 | # Exercise the gcd function 17 | 18 | # Prompt user for input 19 | num1 = int(input('Please enter an integer: ')) 20 | num2 = int(input('Please enter another integer: ')) 21 | 22 | # Determine the smaller of num1 and num2 23 | min = num1 if num1 < num2 else num2 24 | 25 | # Print the GCD 26 | print(gcd(num1, num2)) 27 | -------------------------------------------------------------------------------- /Chap7/gcdfuncbad.py: -------------------------------------------------------------------------------- 1 | # NOTE: This program will not run to completion because it 2 | # calls the gcd function before defining it! 3 | 4 | # [Attempt to] Compute the greatest common factor of two integers 5 | # provided by the user 6 | 7 | # Exercise the gcd function 8 | 9 | # Prompt user for input 10 | num1 = int(input('Please enter an integer: ')) 11 | num2 = int(input('Please enter another integer: ')) 12 | 13 | # Print the GCD 14 | print(gcd(num1, num2)) 15 | 16 | 17 | def gcd(n1, n2): 18 | # Determine the smaller of n1 and n2 19 | min = n1 if n1 < n2 else n2 20 | # 1 definitely is a common factor to all ints 21 | largest_factor = 1 22 | for i in range(1, min + 1): 23 | if n1 % i == 0 and n2 % i == 0: 24 | largest_factor = i # Found larger factor 25 | return largest_factor 26 | 27 | 28 | -------------------------------------------------------------------------------- /Chap7/gcdprog.py: -------------------------------------------------------------------------------- 1 | # Compute the greastest common factor of two integers 2 | # provided by the user 3 | 4 | # Prompt user for input 5 | num1 = int(input('Please enter an integer: ')) 6 | num2 = int(input('Please enter another integer: ')) 7 | 8 | # Determine the smaller of num1 and num2 9 | min = num1 if num1 < num2 else num2 10 | 11 | # 1 definitely is a common factor to all ints 12 | largest_factor = 1 13 | for i in range(1, min + 1): 14 | if num1 % i == 0 and num2 % i == 0: 15 | largest_factor = i # Found larger factor 16 | # Print the GCD 17 | print(largest_factor) 18 | -------------------------------------------------------------------------------- /Chap7/gcdwithmain.py: -------------------------------------------------------------------------------- 1 | # Computes the greatest common divisor of m and n 2 | def gcd(m, n): 3 | # Determine the smaller of m and n 4 | min = m if m < n else n 5 | # 1 is definitely a common factor to all ints 6 | largest_factor = 1 7 | for i in range(1, min + 1): 8 | if m % i == 0 and n % i == 0: 9 | largest_factor = i # Found larger factor 10 | return largest_factor 11 | 12 | 13 | # Get an integer from the user 14 | def get_int(): 15 | return int(input("Please enter an integer: ")) 16 | 17 | 18 | # Main code to execute 19 | def main(): 20 | n1 = get_int() 21 | n2 = get_int() 22 | print("gcd(", n1, ",", n2, ") = ", gcd(n1, n2), sep="") 23 | 24 | 25 | # Run the program 26 | main() 27 | -------------------------------------------------------------------------------- /Chap7/localplay.py: -------------------------------------------------------------------------------- 1 | x = 2 2 | print("1. x =", x) # Print variable x's current value 3 | 4 | def fun1(): 5 | x = 10 6 | print("2. x =", x) # Print this variable x's current value 7 | 8 | print("3. x =", x) # Print variable x's current value 9 | 10 | def fun2(): 11 | x = 20 12 | print("4. x =", x) # Print this variable x's current value 13 | 14 | print("5. x =", x) # Print variable x's current value 15 | 16 | fun1() # Invoke function fun1 17 | fun2() # Invoke function fun2 18 | 19 | print("6. x =", x) # Print variable x's current value 20 | -------------------------------------------------------------------------------- /Chap7/midpoint.py: -------------------------------------------------------------------------------- 1 | def midpoint(pt1, pt2): 2 | x1, y1 = pt1 # Extract x and y components from the first point 3 | x2, y2 = pt2 # Extract x and y components from the second point 4 | return (x1 + x2)/2, (y1 + y2)/2 5 | 6 | 7 | # Get two points from the user 8 | point1 = float(input("Enter first point's x: ")), \ 9 | float(input("Enter first point's y: ")) 10 | point2 = float(input("Enter second point's x: ")), \ 11 | float(input("Enter second point's y: ")) 12 | # Compute the midpoint 13 | mid = midpoint(point1, point2) 14 | # Report result to user 15 | print('Midpoint of', point1, 'and', point2, 'is', mid) 16 | -------------------------------------------------------------------------------- /Chap7/noduplication.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | 4 | def draw_lines(color, y): 5 | """ Draws 10 horizontal lines of a given color stacked 6 | on top of each other with the lowest line appearing 7 | at position y on the y axis. """ 8 | turtle.color(color) 9 | for x in range(10): 10 | turtle.penup() 11 | turtle.setposition(-200, y) 12 | turtle.pendown() 13 | turtle.forward(400) 14 | y += 10 15 | 16 | 17 | # Turn off animation 18 | turtle.tracer(0) 19 | draw_lines("red", -200) 20 | draw_lines("blue", -100) 21 | draw_lines("green",0) 22 | draw_lines("black", 100) 23 | 24 | turtle.update() # Ensure all of image is drawn 25 | turtle.done() 26 | -------------------------------------------------------------------------------- /Chap7/parampassing.py: -------------------------------------------------------------------------------- 1 | def increment(x): 2 | print("Beginning execution of increment, x =", x) 3 | x += 1 # Increment x 4 | print("Ending execution of increment, x =", x) 5 | 6 | 7 | def main(): 8 | x = 5 9 | print("Before increment, x =", x) 10 | increment(x) 11 | print("After increment, x =", x) 12 | 13 | 14 | main() 15 | -------------------------------------------------------------------------------- /Chap7/primefunc.py: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | 3 | def is_prime(n): 4 | """ 5 | Determines the primality of a given value. 6 | n an integer to test for primality. 7 | Returns true if n is prime; otherwise, returns false. 8 | """ 9 | root = round(sqrt(n)) + 1 10 | # Try all potential factors from 2 to the square root of n 11 | for trial_factor in range(2, root): 12 | if n % trial_factor == 0: # Is it a factor? 13 | return False # Found a factor 14 | return True # No factors found 15 | 16 | 17 | def main(): 18 | """ 19 | Tests for primality each integer from 2 up to a value provided by the user. 20 | If an integer is prime, it prints it; otherwise, the number is not printed. 21 | """ 22 | max_value = int(input("Display primes up to what value? ")) 23 | for value in range(2, max_value + 1): 24 | if is_prime(value): # See if value is prime 25 | print(value, end=" ") # Display the prime number 26 | print() # Move cursor down to next line 27 | 28 | 29 | main() # Run the program 30 | -------------------------------------------------------------------------------- /Chap7/regularpolygon.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | import random 3 | 4 | 5 | # Draws a regular polygon with the given number of sides. 6 | # The length of each side is length. 7 | # The pen begins at point(x, y). 8 | # The color of the polygon is color. 9 | def polygon(sides, length, x, y, color): 10 | turtle.penup() 11 | turtle.setposition(x, y) 12 | turtle.pendown() 13 | turtle.color(color) 14 | turtle.begin_fill() 15 | for i in range(sides): 16 | turtle.forward(length) 17 | turtle.left(360//sides) 18 | turtle.end_fill() 19 | 20 | 21 | # Disable rendering to speed up drawing 22 | turtle.hideturtle() 23 | turtle.tracer(0) 24 | 25 | # Draw 20 random polygons with 3-11 sides, each side ranging 26 | # in length from 10-50, located at random position (x, y). 27 | # Select a color at random from red, green, blue, black, or yellow. 28 | for i in range(20): 29 | polygon(random.randrange(3, 11), random.randrange(10, 51), 30 | random.randrange(-250, 251), random.randrange(-250, 251), 31 | random.choice(("red", "green", "blue", "black", "yellow"))) 32 | 33 | turtle.update() # Render image 34 | turtle.exitonclick() # Wait for user's mouse click 35 | -------------------------------------------------------------------------------- /Chap7/simplefloataddition.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | x = 0.9 3 | x += 0.1 4 | if x == 1.0: 5 | print("OK") 6 | else: 7 | print("NOT OK") 8 | 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /Chap7/squarerootcomparison.py: -------------------------------------------------------------------------------- 1 | from math import fabs, sqrt 2 | 3 | def equals(a, b, tolerance): 4 | """ 5 | Consider two floating-point numbers equal when the difference between them is very small. 6 | Returns true if a = b or |a - b| < tolerance. 7 | If a and b differ by only a small amount (specified by tolerance), a and b are considered 8 | "equal." Useful to account for floating-point round-off error. 9 | The == operator is checked first since some special floating-point values such as 10 | floating-point infinity require an exact equality check. 11 | """ 12 | return a == b or fabs(a - b) < tolerance 13 | 14 | 15 | def square_root(val): 16 | """ 17 | Computes the approximate square root of val. 18 | val is a number 19 | """ 20 | # Compute a provisional square root 21 | root = 1.0 22 | 23 | # How far off is our provisional root? 24 | diff = root*root - val 25 | 26 | # Loop until the provisional root 27 | # is close enough to the actual root 28 | while diff > 0.00000001 or diff < -0.00000001: 29 | root = (root + val/root) / 2 # Compute new provisional root 30 | # How bad is our current approximation? 31 | diff = root*root - val 32 | return root 33 | 34 | 35 | def main(): 36 | d = 0.0 37 | while d < 100000.0: 38 | if not equals(square_root(d), sqrt(d), 0.001): 39 | print('*** Difference detected for', d) 40 | print(' Expected', sqrt(d)) 41 | print(' Computed', square_root(d)) 42 | d += 0.0001 # Consider next value 43 | 44 | 45 | main() # Run the program 46 | -------------------------------------------------------------------------------- /Chap7/treefunc.py: -------------------------------------------------------------------------------- 1 | def tree(height): 2 | """ 3 | Draws a tree of a given height. 4 | """ 5 | row = 0 # First row, from the top, to draw 6 | while row < height: # Draw one row for every unit of height 7 | # Print leading spaces 8 | count = 0 9 | while count < height - row: 10 | print(end=" ") 11 | count += 1 12 | # Print out stars, twice the current row plus one: 13 | # 1. number of stars on left side of tree 14 | # = current row value 15 | # 2. exactly one star in the center of tree 16 | # 3. number of stars on right side of tree 17 | # = current row value 18 | count = 0 19 | while count < 2*row + 1: 20 | print(end="*") 21 | count += 1 22 | # Move cursor down to next line 23 | print() 24 | # Change to the next row 25 | row += 1 26 | 27 | 28 | def main(): 29 | """ Allows users to draw trees of various heights """ 30 | height = int(input("Enter height of tree: ")) 31 | tree(height) 32 | 33 | 34 | main() 35 | -------------------------------------------------------------------------------- /Chap8/arithmeticeval.py: -------------------------------------------------------------------------------- 1 | def add(x, y): 2 | """ 3 | Adds the parameters x and y and returns the result 4 | """ 5 | return x + y 6 | 7 | 8 | def multiply(x, y): 9 | """ 10 | Multiplies the parameters x and y and returns the result 11 | """ 12 | return x * y 13 | 14 | 15 | def evaluate(f, x, y): 16 | """ 17 | Calls the function f with parameters x and y: 18 | f(x, y) 19 | """ 20 | return f(x, y) 21 | 22 | 23 | def main(): 24 | """ 25 | Tests the add, multiply, and evaluate functions 26 | """ 27 | print(add(2, 3)) 28 | print(multiply(2, 3)) 29 | print(evaluate(add, 2, 3)) 30 | print(evaluate(multiply, 2, 3)) 31 | 32 | 33 | main() # Call main 34 | -------------------------------------------------------------------------------- /Chap8/closurein.py: -------------------------------------------------------------------------------- 1 | def evaluate(f, x, y): 2 | return f(x, y) 3 | 4 | 5 | def main(): 6 | a = int(input('Enter an integer:')) 7 | print(evaluate(lambda x, y: False if x == a else True, 2, 3)) 8 | 9 | 10 | main() 11 | -------------------------------------------------------------------------------- /Chap8/comparerolls.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | from functools import partial 3 | 4 | 5 | def read_file(filename, n, val): 6 | """ Reads n integers from the text file named filename. 7 | Returns the number of times val appears in the file. """ 8 | count, read = 0, 0 9 | with open(filename, 'r') as f: 10 | for value in f.readlines(): 11 | read += 1 12 | # Have we read enough values in yet? 13 | if read > n: 14 | break 15 | # Convert text integer into an actual integer 16 | if int(value) == val: 17 | count += 1 18 | return count 19 | 20 | 21 | def roll(n, val): 22 | """ Simulates the roll of a pair of dice n times. 23 | Returns the number of times a roll resulted in val. """ 24 | count = 0 25 | for i in range(n): 26 | roll = randint(1, 6) + randint(1, 6) 27 | if roll == val: 28 | count += 1 29 | return count 30 | 31 | 32 | def run_trials(f, n): 33 | """ Performs n experiments using function f as the source of 34 | outcomes. Counts the number of occurrences of each possible 35 | outcome. """ 36 | for value in range(2, 13): 37 | print("{:>3}:{:>5}".format(value, f(n, value))) 38 | 39 | 40 | # Compare the actual experiments to the simulation 41 | number_of_trials = 100 42 | print('--- Pseudorandom number rolls ---') 43 | run_trials(roll, number_of_trials) 44 | print('--- Actual experimental data ---') 45 | run_trials(partial(read_file, 'dicedata.data'), number_of_trials) 46 | -------------------------------------------------------------------------------- /Chap8/derivative.py: -------------------------------------------------------------------------------- 1 | def derivative(f, h): 2 | """ Approximates the derivative of function f 3 | given an h value. The closer h is to zero, 4 | the better the estimate. """ 5 | return lambda x: (f(x + h) - f(x)) / h 6 | 7 | 8 | def fun(x): # The function we wish to differentiate 9 | return 3*x**2 + 5 10 | 11 | 12 | def ans(x): # The known derivative to function fun 13 | return 6*x 14 | 15 | 16 | # Difference: Approximation better as h -> 0 17 | h = 0.0000001 18 | 19 | # Compute the function representing an approximation 20 | # of the derivative of function fun 21 | der = derivative(fun, h) 22 | 23 | # Compare the computed derivative to the exact derivative 24 | # derived symbolically 25 | x = 5.0 26 | print('------------------------------------------------------') 27 | print(' Approx. Actual') 28 | print(' x f(x) h f\'(x) f\'(x)') 29 | print('------------------------------------------------------') 30 | while x < 5.1: 31 | print('{:.5f} {:.5f} {:.8f} {:.5f} {:.5f}'.format(x, fun(x), h, der(x), ans(x))) 32 | x += 0.01 33 | -------------------------------------------------------------------------------- /Chap8/enhancedpolygon.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | import random 3 | 4 | 5 | # Draws a regular polygon with the given number of sides. 6 | # The length of each side is length. 7 | # The pen begins at point(x, y). 8 | # The color of the polygon is color (defaults to black). 9 | # The polygon is rendered solid if fill is True (defaults to False). 10 | def polygon(sides, length, x, y, color="black", fill=False): 11 | turtle.penup() 12 | turtle.setposition(x, y) 13 | turtle.pendown() 14 | turtle.color(color) 15 | if fill: 16 | turtle.begin_fill() 17 | for i in range(sides): 18 | turtle.forward(length) 19 | turtle.left(360//sides) 20 | if fill: 21 | turtle.end_fill() 22 | 23 | 24 | # Disable rendering to speed up drawing 25 | turtle.hideturtle() 26 | turtle.tracer(0) 27 | 28 | # Draw a few polygons 29 | polygon(3, 30, 10, 10) # Back triangle outline 30 | polygon(4, 30, 50, 50, "blue") # Blue square outline 31 | polygon(5, 30, 100, 100, "red", True) # Red solid pentagon 32 | 33 | turtle.update() # Render image 34 | turtle.exitonclick() # Wait for user's mouse click 35 | -------------------------------------------------------------------------------- /Chap8/factorialtest.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | """ 3 | Computes n! 4 | Returns the factorial of n. 5 | """ 6 | if n == 0: 7 | return 1 8 | else: 9 | return n * factorial(n - 1) 10 | 11 | 12 | def main(): 13 | """ Try out the factorial function """ 14 | print(" 0! = ", factorial(0)) 15 | print(" 1! = ", factorial(1)) 16 | print(" 6! = ", factorial(6)) 17 | print("10! = ", factorial(10)) 18 | 19 | 20 | main() 21 | -------------------------------------------------------------------------------- /Chap8/forgenerator.py: -------------------------------------------------------------------------------- 1 | def gen(): 2 | yield 3 3 | yield 'wow' 4 | yield -1 5 | yield 1.2 6 | 7 | 8 | for i in gen(): 9 | print(i) 10 | -------------------------------------------------------------------------------- /Chap8/funcmemory.py: -------------------------------------------------------------------------------- 1 | count = 0 # A global count variable 2 | 3 | def remember(): 4 | global count 5 | count += 1 # Count this invocation 6 | print('Calling remember (#' + str(count) + ')') 7 | 8 | 9 | print('Beginning program') 10 | remember() 11 | remember() 12 | remember() 13 | remember() 14 | remember() 15 | print('Ending program') 16 | -------------------------------------------------------------------------------- /Chap8/gcd.py: -------------------------------------------------------------------------------- 1 | def gcd(m, n): 2 | """ 3 | Uses Euclid's method to compute the greatest common divisor 4 | (also called greatest common factor) of m and n. 5 | Returns the GCD of m and n. 6 | """ 7 | if n == 0: 8 | return m 9 | else: 10 | return gcd(n, m % n) 11 | 12 | 13 | def iterative_gcd(num1, num2): 14 | """ 15 | Uses a naive algorithm to compute the greatest common divisor 16 | (also called greatest common factor) of m and n. 17 | Returns the GCD of m and n. 18 | """ 19 | # Determine the smaller of num1 and num2 20 | min = num1 if num1 < num2 else num2 21 | # 1 is definitely a common factor to all integers 22 | largest_factor = 1; 23 | for i in range(1, min + 1): 24 | if num1 % i == 0 and num2 % i == 0: 25 | largest_factor = i # Found larger factor 26 | return largest_factor 27 | 28 | 29 | def main(): 30 | """ Try out the gcd function """ 31 | for num1 in range(1, 101): 32 | for num2 in range(1, 101): 33 | print("gcd of", num1, "and", num2, "is", gcd(num1, num2)) 34 | 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /Chap8/localcounter.py: -------------------------------------------------------------------------------- 1 | def create_counter(n): 2 | """ Creates a counting function that counts up to n """ 3 | count = 0 4 | 5 | def counter(): # Local function 6 | """ Increments the outer variable unless it 7 | has reached its limit """ 8 | nonlocal count 9 | if count < n: 10 | count += 1 11 | return count 12 | 13 | return counter # Returns a function 14 | 15 | 16 | ctr = create_counter(4) 17 | print(ctr()) 18 | print(ctr()) 19 | print(ctr()) 20 | print(ctr()) 21 | print(ctr()) 22 | print(ctr()) 23 | -------------------------------------------------------------------------------- /Chap8/makeadder.py: -------------------------------------------------------------------------------- 1 | def make_adder(): 2 | loc_val = 2 # Local variable definition 3 | return lambda x: x + loc_val # Returns a function 4 | 5 | 6 | def main(): 7 | f = make_adder() 8 | print(f(10)) 9 | print(f(2)) 10 | 11 | 12 | main() 13 | -------------------------------------------------------------------------------- /Chap8/myrange.py: -------------------------------------------------------------------------------- 1 | def myrange(arg1, arg2=None, step=1): 2 | if arg2 != None: # Do we have at least two arguments? 3 | begin = arg1 4 | end = arg2 5 | else: # We must have just one argument 6 | begin = 0 # Begin value is zero by default 7 | end = arg1 8 | i = begin 9 | while i != end: 10 | yield i 11 | i += step 12 | 13 | 14 | print('0 to 9:', end=' ') 15 | for i in myrange(10): 16 | print(i, end=' ') 17 | print() 18 | 19 | print('1 to 10:', end=' ') 20 | for i in myrange(1, 11): 21 | print(i, end=' ') 22 | print() 23 | 24 | print('2 to 18 by twos:', end=' ') 25 | for i in myrange(2, 20, 2): 26 | print(i, end=' ') 27 | print() 28 | 29 | print('20 down to 2 by twos:', end=' ') 30 | for i in myrange(20, 0, -2): 31 | print(i, end=' ') 32 | print() 33 | -------------------------------------------------------------------------------- /Chap8/nonrecursfact.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | """ 3 | Computes n! 4 | Returns the factorial of n. 5 | """ 6 | product = 1 7 | while n: 8 | product *= n 9 | n -= 1 10 | return product 11 | 12 | 13 | def main(): 14 | """ Try out the factorial function """ 15 | print(" 0! = ", factorial(0)) 16 | print(" 1! = ", factorial(1)) 17 | print(" 6! = ", factorial(6)) 18 | print("10! = ", factorial(10)) 19 | 20 | 21 | main() 22 | -------------------------------------------------------------------------------- /Chap8/placesquares.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | 4 | def draw_square(x, y): 5 | """ Draws a 10 x 10 square centered at the point (x, y). """ 6 | turtle.penup() 7 | turtle.setheading(0) # Ensure the pen is pointed the proper direction 8 | turtle.setposition(x - 5, y - 5) # Center square 9 | turtle.pendown() 10 | for i in range(4): 11 | turtle.forward(10) 12 | turtle.left(90) 13 | turtle.update() 14 | 15 | 16 | # Turn off animation 17 | turtle.tracer(0) 18 | turtle.hideturtle() 19 | 20 | # Allow user to place 10 x 10 squares using the mouse 21 | turtle.onscreenclick(draw_square) 22 | 23 | # Start the graphics loop that listens for user input 24 | turtle.mainloop() 25 | -------------------------------------------------------------------------------- /Chap8/primecode.py: -------------------------------------------------------------------------------- 1 | """ Contains the definition of the is_prime function """ 2 | from math import sqrt 3 | 4 | def is_prime(n): 5 | """ Returns True if nonnegative integer n is prime; otherwise, returns false """ 6 | trial_factor = 2 7 | root = sqrt(n) 8 | 9 | while trial_factor <= root: 10 | if n % trial_factor == 0: # Is trial factor a factor? 11 | return False # Yes, return right away 12 | trial_factor += 1 # Consider next potential factor 13 | 14 | return True # Tried them all, must be prime 15 | -------------------------------------------------------------------------------- /Chap8/regulargenerator.py: -------------------------------------------------------------------------------- 1 | def generate_multiples(m, n): 2 | count = 0 3 | while count < n: 4 | yield m * count 5 | count += 1 6 | 7 | 8 | def main(): 9 | for mult in generate_multiples(3, 6): 10 | print(mult, end=' ') 11 | print() 12 | 13 | 14 | if __name__ == '__main__': 15 | main() 16 | -------------------------------------------------------------------------------- /Chap8/trackmouse.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | def report_position(x, y): 4 | """ Simply prints the values of x and y. """ 5 | print("x =", x, " y =", y, flush=True) 6 | 7 | # Establish a function the framework should call when the user clicks the mouse 8 | turtle.onscreenclick(report_position) 9 | 10 | # Start the graphics loop that listens for user input 11 | turtle.mainloop() 12 | -------------------------------------------------------------------------------- /Chap8/undecorated.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | 4 | def max(x, y): 5 | """ Determine the maximum of x and y """ 6 | return x if x > y else y 7 | 8 | def gcd(m, n): 9 | """ 10 | Uses Euclid's method to compute the greatest common divisor 11 | (also called greatest common factor) of m and n. 12 | Returns the GCD of m and n. 13 | """ 14 | if n == 0: 15 | return m 16 | else: 17 | return gcd(n, m % n) 18 | 19 | def summation(begin, end): 20 | """ Add up the integers in the range begin...end - 1, inclusive """ 21 | sum = 0 22 | while begin != end: 23 | sum += begin 24 | begin += 1 25 | return sum 26 | 27 | def star_rect(length, width): 28 | """ Draw a length x width rectangle with asterisks """ 29 | for row in range(length): 30 | print('* ' * width) 31 | 32 | 33 | print("The maximum of 20 and 30 is", max(20, 30)) 34 | print("The maximum of 30 and 20 is", max(30, 20)) 35 | print("The maximum of 20 and 20 is", max(20, 20)) 36 | print('------------------------') 37 | 38 | print("The GCD of 20 and 30 is", gcd(20, 30)) 39 | print("The GCD of 30 and 20 is", gcd(30, 20)) 40 | print("The GCD of 20 and 20 is", gcd(20, 20)) 41 | print('------------------------') 42 | 43 | print("The summation from 20 to 30 is", summation(20, 30)) 44 | print('------------------------') 45 | 46 | star_rect(7, 3) 47 | print('------------------------') 48 | star_rect(4, 4) 49 | print('------------------------') 50 | star_rect(2, 5) 51 | print('------------------------') 52 | 53 | print(randrange(10, 21), "is a pseudorandom integer in the range 10 to 20, inclusive") 54 | -------------------------------------------------------------------------------- /Chap8/usingprimecode.py: -------------------------------------------------------------------------------- 1 | from primecode import is_prime 2 | 3 | num = int(input("Enter an integer: ")) 4 | if is_prime(num): 5 | print(num, "is prime") 6 | else: 7 | print(num, "is NOT prime") 8 | -------------------------------------------------------------------------------- /Chap8/usingprimecode2.py: -------------------------------------------------------------------------------- 1 | import primecode 2 | 3 | num = int(input("Enter an integer: ")) 4 | if primecode.is_prime(num): 5 | print(num, "is prime") 6 | else: 7 | print(num, "is NOT prime") 8 | -------------------------------------------------------------------------------- /Chap8/yieldsequence.py: -------------------------------------------------------------------------------- 1 | def gen(): 2 | yield 3 3 | yield 'wow' 4 | yield -1 5 | yield 1.2 6 | -------------------------------------------------------------------------------- /Chap9/boxturtleobject.py: -------------------------------------------------------------------------------- 1 | # Draws a ractangular box in the window 2 | 3 | from turtle import Turtle, mainloop 4 | 5 | t = Turtle() # Create a turtle object named t 6 | t.pencolor('red') # t's pen color is red 7 | t.forward(200) # Move turtle t forward 200 units (create bottom of rectangle 8 | t.left(90) # Turn turtle left by 90 degrees 9 | t.pencolor('blue') # Change t's pen color to blue 10 | t.forward(150) # Move turtle t forward 150 units (create right wall) 11 | t.left(90) # Turn turtle left by 90 degrees 12 | t.pencolor('green') # Change t's pen color to green 13 | t.forward(200) # Move turtle t forward 200 units (create top) 14 | t.left(90) # Turn turtle left by 90 degrees 15 | t.pencolor('black') # Change t's pen color to black 16 | t.forward(150) # Move turtle t forward 150 units (create left wall) 17 | t.hideturtle() # Make turtle t invisible 18 | mainloop() # Await user input 19 | -------------------------------------------------------------------------------- /Chap9/buttontester.py: -------------------------------------------------------------------------------- 1 | from tkinter import Tk, Button 2 | 3 | 4 | count = 0 # Records the number of button presses 5 | 6 | 7 | def update(): 8 | """ Updates the count label within the graphical button """ 9 | global count, b 10 | count += 1 11 | b.config(text="Click Count = " + str(count)) 12 | print("Updating") 13 | 14 | 15 | root = Tk() 16 | b = Button(root) 17 | b.configure(background="yellow", text="Click Count = 0", command=update) 18 | b.pack() 19 | root.mainloop() 20 | -------------------------------------------------------------------------------- /Chap9/convertupper.py: -------------------------------------------------------------------------------- 1 | """ 2 | convertupper.py 3 | """ 4 | def capitalize(filename): 5 | """ Creates a new file with the prefix 'upper_' 6 | added to the name of the original file. 7 | All the alphabetic characters in the new 8 | are capitalized. This function does not 9 | disturb the contents of the original file. """ 10 | with open(filename, 'r') as infile: 11 | with open('upper_' + filename, 'w') as outfile: 12 | for line in infile: 13 | line = line.strip().upper() 14 | print(line, file=outfile) 15 | -------------------------------------------------------------------------------- /Chap9/fractionassign.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | # Assign some Fraction variables 4 | f1 = Fraction(1, 2) 5 | f2 = Fraction(1, 2) 6 | f3 = f1 7 | 8 | # Examine the objects involved 9 | print('f1 =', f1) 10 | print('f2 =', f2) 11 | print('f3 =', f3) 12 | 13 | # Examine the numerators and denominators separately 14 | print('f1 numerator, denominator:', f1.numerator, f1.denominator) 15 | print('f2 numerator, denominator:', f2.numerator, f2.denominator) 16 | print('f3 numerator, denominator:', f3.numerator, f3.denominator) 17 | 18 | # Compare the fractions 19 | print('f1 == f2?', f1 == f2) 20 | print('f1 == f3?', f1 == f3) 21 | print('f1 is f2?', f1 is f2) 22 | print('f1 is f3?', f1 is f3) 23 | -------------------------------------------------------------------------------- /Chap9/fractionplay.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | 3 | f1 = Fraction(3, 4) # Make the fraction 3/4 4 | print(f1) # Print it 5 | print(f1.numerator) # Print numerator 6 | print(f1.denominator) # Print denominator 7 | print(float(f1)) # Floating-point equivalent 8 | f2 = Fraction(1, 8) # Make another fraction, 1/8 9 | print(f2) # Print the second fraction 10 | f3 = f1 + f2 # Add the two fractions 11 | print(f3) # 3/4 + 1/8 = 6/8 + 1/8 = 7/8 12 | -------------------------------------------------------------------------------- /Chap9/multiturtle.py: -------------------------------------------------------------------------------- 1 | """ Uses two Turtle objects to draw on the screen """ 2 | 3 | from turtle import * 4 | 5 | # Part 1 6 | t1 = Turtle() # Create a turtle object named t1 7 | t2 = Turtle() # Create a second turtle object named t2 8 | t1.pencolor('red') # t1's pen color is red 9 | t2.pencolor('blue') # t2's pen color is blue 10 | t2.left(90) # Point t2 up (t1 autoatically points to the right) 11 | t1.forward(100) # Move turtle t1 forward 100 units 12 | t2.forward(50) # Move turtle t2 forward 50 units 13 | 14 | # Part 2 15 | t2 = t1 # Make the second turtle just like the first? 16 | t2.right(45) # Turn turtle 2 (but not turtle 1?) 17 | t2.forward(50) # Move turtle 2 (why does turtle1 move instead?) 18 | 19 | done() 20 | -------------------------------------------------------------------------------- /Chap9/numbersaver.py: -------------------------------------------------------------------------------- 1 | """ 2 | Uses Python's file class to store data to and retrieve data from 3 | a text file. 4 | """ 5 | def load_data(filename): 6 | """ Print the elements stored in the text file named filename. """ 7 | # Open file to read 8 | with open(filename) as f: # f is a file object 9 | for line in f: # Read each line as text 10 | print(int(line)) # Convert to integer and append to the list 11 | 12 | 13 | def store_data(filename): 14 | """ Allows the user to store data to the text file named filename. """ 15 | with open(filename, 'w') as f: # f is a file object 16 | number = 0 17 | while number != 999: # Loop until user provides magic number 18 | number = int(input('Please enter number (999 quits):')) 19 | if number != 999: 20 | f.write(str(number) + '\n') # Convert integer to string to save 21 | else: 22 | break # Exit loop 23 | 24 | 25 | def main(): 26 | """ Interactive function that allows the user to 27 | create or consume files of numbers. """ 28 | done = False 29 | 30 | while not done: 31 | cmd = input('S)ave L)oad Q)uit: ') 32 | if cmd == 'S' or cmd == 's': 33 | store_data(input('Enter file name:')) 34 | elif cmd == 'L' or cmd == 'l': 35 | load_data(input('Enter filename:')) 36 | elif cmd == 'Q' or cmd == 'q': 37 | done = True 38 | 39 | 40 | if __name__ == '__main__': 41 | main() 42 | -------------------------------------------------------------------------------- /Chap9/octogonobject.py: -------------------------------------------------------------------------------- 1 | """ Draws in the window a spiral surrounded with an octogon """ 2 | 3 | from turtle import * 4 | 5 | def octogon(t, x, y, color): 6 | """ Draws with turtle t an octogon centered at (x, y) 7 | with the specified color """ 8 | t.pencolor(color) # Set pen color 9 | t.penup() # Lift pen to move it 10 | t.setposition(x, y) # Move the pen to coordinates (x, y) 11 | t.pendown() # Place pen to begin drawing 12 | for i in range(8): # Draw the eight sides 13 | t.forward(80) 14 | t.right(45) 15 | 16 | 17 | def spiral(t, x, y, color): 18 | """ Draws with turtle t a spiral centered at (x, y) 19 | with the specified color """ 20 | distance = 0.2 21 | angle = 40 22 | t.pencolor(color) # Set pen color 23 | t.penup() # Left pen to move it 24 | t.setposition(x, y) # Position the pen at coordinates (x, y) 25 | t.pendown() # Set pen down to begin drawing 26 | for i in range(100): 27 | t.forward(distance) 28 | t.left(angle) 29 | distance += 0.5 30 | 31 | 32 | t = Turtle() # Create a turtle object named t 33 | octogon(t, -45, 100, 'red') 34 | spiral(t, 0, 0, 'blue') 35 | t.hideturtle() # Make turtle t invisible 36 | done() 37 | -------------------------------------------------------------------------------- /Chap9/printcharacters.py: -------------------------------------------------------------------------------- 1 | s = "ABCDEFGHIJK" 2 | print(s) 3 | for i in range(len(s)): 4 | print("[", s[i], "]", sep="", end="") 5 | print() # Print newline 6 | 7 | for ch in s: 8 | print("<", ch, ">", sep="", end="") 9 | print() # Print newline 10 | -------------------------------------------------------------------------------- /Chap9/rjustprog.py: -------------------------------------------------------------------------------- 1 | word = "ABCD" 2 | print(word.rjust(10, "*")) 3 | print(word.rjust(3, "*")) 4 | print(word.rjust(15, ">")) 5 | print(word.rjust(10)) 6 | -------------------------------------------------------------------------------- /Chap9/runconvert.py: -------------------------------------------------------------------------------- 1 | from convertupper import capitalize 2 | 3 | capitalize('declaration.txt') 4 | -------------------------------------------------------------------------------- /Chap9/simplefileread.py: -------------------------------------------------------------------------------- 1 | f = open('data.dat') # f is a file object 2 | for line in f: # Read each line as text 3 | print(line.strip()) # Remove trailing newline character 4 | f.close() # Close the file 5 | -------------------------------------------------------------------------------- /Chap9/simplerread.py: -------------------------------------------------------------------------------- 1 | with open('data.dat') as f: # f is a file object 2 | for line in f: # Read each line as text 3 | print(line.strip()) # Remove trailing newline character 4 | # No need to close the file 5 | -------------------------------------------------------------------------------- /Chap9/stringupper.py: -------------------------------------------------------------------------------- 1 | name = input("Please enter your name: ") 2 | print("Hello " + name.upper() + ", how are you?") 3 | -------------------------------------------------------------------------------- /Chap9/stripandcount.py: -------------------------------------------------------------------------------- 1 | # Strip leading and trailing whitespace and count substrings 2 | s = " ABCDEFGHBCDIJKLMNOPQRSBCDTUVWXYZ " 3 | print("[", s, "]", sep="") 4 | s = s.strip() 5 | print("[", s, "]", sep="") 6 | 7 | # Count occurrences of the substring "BCD" 8 | print(s.count("BCD")) 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonBook-SourceCode 2 | 3 | Python source code for the Fundamentals of Python Programming by Richard Halterman (see http://python.cs.southern.edu/pythonbook/pythonbook.pdf) 4 | --------------------------------------------------------------------------------