├── .gitignore ├── Chapter 06 ├── friends.txt ├── numbers.txt ├── coffee.txt ├── philosophers.txt ├── sales.txt ├── video_times.txt ├── sales_data.txt ├── employees.txt ├── division.py ├── file_write.py ├── file_read.py ├── display_file.py ├── gross_pay1.py ├── division2.py ├── read_sales2.py ├── line_read.py ├── gross_pay3.py ├── display_file2.py ├── gross_pay2.py ├── write_names.py ├── sales_report2.py ├── sales_report3.py ├── sales_report4.py ├── read_numbers.py ├── strip_newline.py ├── write_numbers.py ├── save_running_times.py ├── read_sales.py ├── show_coffee_records.py ├── write_sales.py ├── sales_report1.py ├── add_coffee_record.py ├── read_running_times.py ├── read_emp_records.py ├── save_emp_records.py ├── search_coffee_records.py ├── delete_coffee_record.py └── modify_coffee_records.py ├── Chapter 07 ├── cities.txt ├── numberlist.txt ├── charge_accounts.txt ├── write_list.py ├── write_number_list.py ├── writelines.py ├── USPopulation.txt ├── insert_list.py ├── total_list.py ├── in_list.py ├── read_list.py ├── read_number_list.py ├── average_list.py ├── random_numbers.py ├── total_function.py ├── sales_list.py ├── remove_item.py ├── list_append.py ├── barista_pay.py ├── index_list.py ├── return_list.py ├── drop_lowest_score.py ├── WorldSeriesWinners.txt ├── BoyNames.txt └── GirlNames.txt ├── Chapter 02 ├── apostrophe.py ├── display_quote.py ├── output.py ├── double_quotes.py ├── variable_demo3.py ├── variable_demo.py ├── comment1.py ├── comment2.py ├── string_variable.py ├── no_formatting.py ├── formatting.py ├── dollar_display.py ├── string_input.py ├── variable_demo2.py ├── simple_math.py ├── variable_demo4.py ├── input.py ├── sale_price.py ├── test_score_average.py ├── columns.py ├── time_converter.py └── future_value.py ├── Chapter 09 ├── info.dat ├── phonebook.dat ├── exercise9_6 │ ├── file1.txt │ ├── file2.txt │ └── exercise9_6.py ├── exercise9_3 │ ├── sampletext.txt │ └── exercise9_3.py ├── exercise9_5 │ └── exercise9_5.py ├── exercise9_4 │ ├── test.txt │ └── exercise9_4.py ├── unpickle_objects.py ├── pickle_objects.py ├── exercise9_1 │ └── ex1.py ├── exercise9_10 │ ├── text.txt │ └── index.txt ├── sets.py ├── exercise9_2 │ ├── StatesCapitals.txt │ └── ex9_2.py ├── exercise9_7 │ ├── exercise9_7.py │ └── WorldSeries.txt └── card_dealer.py ├── README.md ├── Chapter 10 ├── contacts.dat ├── cellphones.dat ├── exercise2 │ ├── exer2_2.py │ └── exer2.py ├── exercise3 │ ├── program.py │ └── information.py ├── exercise4 │ ├── employee.py │ └── program.py ├── coin_demo4.py ├── car.py ├── coin_argument.py ├── customer.py ├── exercise5 │ ├── program.py │ └── retailitem.py ├── cell_phone_test.py ├── coin.py ├── servicequote.py ├── bankaccount.py ├── account_test2.py ├── algo1.py ├── coin_demo5.py ├── account_test.py ├── pickle_cellphone.py ├── bankaccount2.py ├── unpickle_cellphone.py ├── algo3.txt ├── coin_demo3.py ├── contact.py ├── coin_demo1.py ├── cellphone.py ├── algo2.py ├── coin_demo2.py ├── exercise1 │ ├── exercise1_2.py │ └── exercise1.py ├── cell_phone_list.py └── exercise6 │ ├── procedure.py │ └── program.py ├── Chapter 04 ├── simple_loop3.py ├── simple_loop4.py ├── stair_step_pattern.py ├── triangle_pattern.py ├── simple_loop1.py ├── simple_loop2.py ├── rectangluar_pattern.py ├── squares.py ├── gross_pay.py ├── user_squares1.py ├── infinite.py ├── speed_converter.py ├── sum_numbers.py ├── user_squares2.py ├── retail_no_validation.py ├── commission.py ├── property_tax.py ├── temperature.py ├── retail_with_validation.py └── test_score_averages.py ├── Chapter 05 ├── function_demo.py ├── global1.py ├── random_numbers3.py ├── bad_local.py ├── global2.py ├── random_numbers.py ├── random_numbers2.py ├── pass_arg.py ├── two_functions.py ├── multiple_args.py ├── square_root.py ├── string_args.py ├── change_me.py ├── coin_toss.py ├── keyword_string_args.py ├── circle.py ├── rectangle.py ├── hypotenuse.py ├── birds.py ├── dice.py ├── total_ages.py ├── keyword_args.py ├── cups_to_ounces.py ├── sale_price.py ├── retirement.py ├── acme_dryer.py ├── commission_rate.py └── geometry.py ├── Chapter 12 ├── endless_recursion.py ├── recursive.py ├── fibonacci.py ├── gcd.py ├── factorial.py ├── range_sum.py └── towers_of_hanoi.py ├── Chapter 08 ├── concatenate.py ├── string_split.py ├── repetition_operator.py ├── split_date.py ├── validate_password.py ├── generate_login.py ├── count_Ts.py ├── string_test.py ├── text.txt ├── exercise8_15 │ └── exercise8_15.py └── login.py ├── Chapter 13 ├── empty_window1.py ├── empty_window2.py ├── hello_world.py ├── hello_world2.py ├── hello_world3.py ├── button_demo.py ├── quit_button.py ├── frame_demo.py ├── kilo_converter.py ├── radiobutton_demo.py └── checkbutton_demo.py ├── Chapter 03 ├── password.py ├── sort_names.py ├── loan_qualifier3.py ├── loan_qualifier2.py ├── grader.py ├── test_average.py ├── loan_qualifier.py └── auto_repair_payroll.py ├── Chapter 11 ├── wrong_type.py ├── car_demo.py ├── polymorphism_demo.py ├── polymorphism_demo2.py ├── animals.py ├── car_truck_suv_demo.py ├── account demo.py └── accounts.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.[oa] 2 | *~ 3 | -------------------------------------------------------------------------------- /Chapter 06/friends.txt: -------------------------------------------------------------------------------- 1 | Joe 2 | Rose 3 | Geri 4 | -------------------------------------------------------------------------------- /Chapter 06/numbers.txt: -------------------------------------------------------------------------------- 1 | 22 2 | 14 3 | -99 4 | -------------------------------------------------------------------------------- /Chapter 06/coffee.txt: -------------------------------------------------------------------------------- 1 | Sumatra Medium Roast 2 | 25.0 3 | -------------------------------------------------------------------------------- /Chapter 07/cities.txt: -------------------------------------------------------------------------------- 1 | New York 2 | Boston 3 | Atlanta 4 | Dallas 5 | -------------------------------------------------------------------------------- /Chapter 07/numberlist.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | -------------------------------------------------------------------------------- /Chapter 02/apostrophe.py: -------------------------------------------------------------------------------- 1 | print("Don't fear!") 2 | print("I'm here!") 3 | 4 | -------------------------------------------------------------------------------- /Chapter 06/philosophers.txt: -------------------------------------------------------------------------------- 1 | John Locke 2 | David Hume 3 | Edmund Burke 4 | -------------------------------------------------------------------------------- /Chapter 06/sales.txt: -------------------------------------------------------------------------------- 1 | 1000.0 2 | 2000.0 3 | 3000.0 4 | 4000.0 5 | 5000.0 6 | -------------------------------------------------------------------------------- /Chapter 06/video_times.txt: -------------------------------------------------------------------------------- 1 | 24.5 2 | 12.2 3 | 14.6 4 | 20.4 5 | 22.5 6 | 19.3 7 | -------------------------------------------------------------------------------- /Chapter 02/display_quote.py: -------------------------------------------------------------------------------- 1 | print('Your assignment is to read "Hamlet" by tomorrow.') 2 | -------------------------------------------------------------------------------- /Chapter 06/sales_data.txt: -------------------------------------------------------------------------------- 1 | 24987.62 2 | 26978.97 3 | 32589.45 4 | 31978.47 5 | 22781.76 6 | 29871.44 7 | -------------------------------------------------------------------------------- /Chapter 02/output.py: -------------------------------------------------------------------------------- 1 | print('Kate Austen') 2 | print('123 Full Circle Drive') 3 | print('Asheville, NC 28899') 4 | -------------------------------------------------------------------------------- /Chapter 02/double_quotes.py: -------------------------------------------------------------------------------- 1 | print("Kate Austen") 2 | print("123 Dharma Lane") 3 | print("Asheville, NC 28899") 4 | -------------------------------------------------------------------------------- /Chapter 09/info.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yorwosa/starting-out-with-python-global-4th-edition/HEAD/Chapter 09/info.dat -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # starting-out-with-python-global-4th-edition 2 | Exercises for the book Starting out with Python 4th edition. 3 | -------------------------------------------------------------------------------- /Chapter 10/contacts.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yorwosa/starting-out-with-python-global-4th-edition/HEAD/Chapter 10/contacts.dat -------------------------------------------------------------------------------- /Chapter 02/variable_demo3.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a variable. 2 | room = 503 3 | print('I am staying in room number', room) 4 | -------------------------------------------------------------------------------- /Chapter 09/phonebook.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yorwosa/starting-out-with-python-global-4th-edition/HEAD/Chapter 09/phonebook.dat -------------------------------------------------------------------------------- /Chapter 10/cellphones.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yorwosa/starting-out-with-python-global-4th-edition/HEAD/Chapter 10/cellphones.dat -------------------------------------------------------------------------------- /Chapter 02/variable_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a variable. 2 | room = 503 3 | print('I am staying in room number') 4 | print(room) 5 | -------------------------------------------------------------------------------- /Chapter 06/employees.txt: -------------------------------------------------------------------------------- 1 | Ingrid Virgo 2 | 4587 3 | Engineering 4 | Julia Rich 5 | 4588 6 | Research 7 | Greg Young 8 | 4589 9 | Marketing 10 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_6/file1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yorwosa/starting-out-with-python-global-4th-edition/HEAD/Chapter 09/exercise9_6/file1.txt -------------------------------------------------------------------------------- /Chapter 09/exercise9_6/file2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yorwosa/starting-out-with-python-global-4th-edition/HEAD/Chapter 09/exercise9_6/file2.txt -------------------------------------------------------------------------------- /Chapter 02/comment1.py: -------------------------------------------------------------------------------- 1 | # This program displays a person's 2 | # name and address. 3 | print('Kate Austen') 4 | print('123 Full Circle Drive') 5 | print('Asheville, NC 28899') 6 | -------------------------------------------------------------------------------- /Chapter 02/comment2.py: -------------------------------------------------------------------------------- 1 | print('Kate Austen') # Name 2 | print('123 Full Circle Drive') # Street address 3 | print('Asheville, NC 28899') # City, state, and ZIP 4 | -------------------------------------------------------------------------------- /Chapter 04/simple_loop3.py: -------------------------------------------------------------------------------- 1 | # This program also demonstrates a simple for 2 | # loop that uses a list of strings. 3 | 4 | for name in ['Winken', 'Blinken', 'Nod']: 5 | print(name) 6 | 7 | -------------------------------------------------------------------------------- /Chapter 04/simple_loop4.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how the range 2 | # function can be used with a for loop. 3 | 4 | # Print a message five times. 5 | for x in range(5): 6 | print('Hello world!') 7 | 8 | -------------------------------------------------------------------------------- /Chapter 04/stair_step_pattern.py: -------------------------------------------------------------------------------- 1 | # This program displays a stair-step pattern. 2 | num_steps = 6 3 | 4 | for r in range(num_steps): 5 | for c in range(r): 6 | print(' ', end='') 7 | print('#') 8 | -------------------------------------------------------------------------------- /Chapter 04/triangle_pattern.py: -------------------------------------------------------------------------------- 1 | # This program displays a triangle pattern. 2 | base_size = 8 3 | 4 | for r in range(base_size): 5 | for c in range(r + 1): 6 | print('*', end='') 7 | print() 8 | -------------------------------------------------------------------------------- /Chapter 02/string_variable.py: -------------------------------------------------------------------------------- 1 | # Create variables to reference two strings. 2 | first_name = 'Kathryn' 3 | last_name = 'Marino' 4 | 5 | # Display the values referenced by the variables. 6 | print(first_name, last_name) 7 | 8 | -------------------------------------------------------------------------------- /Chapter 04/simple_loop1.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a simple for loop 2 | # that uses a list of numbers. 3 | 4 | print('I will display the numbers 1 through 5.') 5 | for num in [1, 2, 3, 4, 5]: 6 | print(num) 7 | 8 | -------------------------------------------------------------------------------- /Chapter 04/simple_loop2.py: -------------------------------------------------------------------------------- 1 | # This program also demonstrates a simple for 2 | # loop that uses a list of numbers. 3 | 4 | print('I will display the odd numbers 1 through 9.') 5 | for num in [1, 3, 5, 7, 9]: 6 | print(num) 7 | 8 | -------------------------------------------------------------------------------- /Chapter 02/no_formatting.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how a floating-point 2 | # number is displayed with no formatting. 3 | amount_due = 5000.0 4 | monthly_payment = amount_due / 12 5 | print('The monthly payment is', monthly_payment) 6 | 7 | 8 | -------------------------------------------------------------------------------- /Chapter 02/formatting.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how a floating-point 2 | # number can be formatted. 3 | amount_due = 5000.0 4 | monthly_payment = amount_due / 12 5 | print('The monthly payment is', \ 6 | format(monthly_payment, '.2f')) 7 | 8 | -------------------------------------------------------------------------------- /Chapter 05/function_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a function. 2 | # First, we define a function named message. 3 | def message(): 4 | print('I am Arthur') 5 | print('King of the Britons') 6 | 7 | # Call the message function. 8 | message() 9 | -------------------------------------------------------------------------------- /Chapter 07/charge_accounts.txt: -------------------------------------------------------------------------------- 1 | 5658845 2 | 4520125 3 | 7895122 4 | 8777541 5 | 8451277 6 | 1302850 7 | 8080152 8 | 4562555 9 | 5552012 10 | 5050552 11 | 7825877 12 | 1250255 13 | 1005231 14 | 6545231 15 | 3852085 16 | 7576651 17 | 7881200 18 | 4581002 -------------------------------------------------------------------------------- /Chapter 12/endless_recursion.py: -------------------------------------------------------------------------------- 1 | # This program has a recursive function. 2 | 3 | def main(): 4 | message() 5 | 6 | def message(): 7 | print('This is a recursive function.') 8 | message() 9 | 10 | # Call the main function. 11 | main() 12 | -------------------------------------------------------------------------------- /Chapter 02/dollar_display.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how a floating-point 2 | # number can be displayed as currency. 3 | monthly_pay = 5000.0 4 | annual_pay = monthly_pay * 12 5 | print('Your annual pay is $', \ 6 | format(annual_pay, ',.2f'), \ 7 | sep='') 8 | -------------------------------------------------------------------------------- /Chapter 02/string_input.py: -------------------------------------------------------------------------------- 1 | # Get the user's first name. 2 | first_name = input('Enter your first name: ') 3 | 4 | # Get the user's last name. 5 | last_name = input('Enter your last name: ') 6 | 7 | # Print a greeting to the user. 8 | print('Hello', first_name, last_name) 9 | -------------------------------------------------------------------------------- /Chapter 05/global1.py: -------------------------------------------------------------------------------- 1 | # Create a global variable. 2 | my_value = 10 3 | 4 | # The show_value function prints 5 | # the value of the global variable. 6 | def show_value(): 7 | print(my_value) 8 | 9 | # Call the show_value function. 10 | show_value() 11 | 12 | 13 | -------------------------------------------------------------------------------- /Chapter 05/random_numbers3.py: -------------------------------------------------------------------------------- 1 | # This program displays five random 2 | # numbers in the range of 1 through 100. 3 | import random 4 | 5 | def main(): 6 | for count in range(5): 7 | print(random.randint(1, 100)) 8 | 9 | # Call the main function. 10 | main() 11 | -------------------------------------------------------------------------------- /Chapter 08/concatenate.py: -------------------------------------------------------------------------------- 1 | # This program concatenates strings. 2 | 3 | def main(): 4 | name = 'Carmen' 5 | print('The name is', name) 6 | name = name + ' Brown' 7 | print('Now the name is', name) 8 | 9 | # Call the main function. 10 | main() 11 | 12 | -------------------------------------------------------------------------------- /Chapter 10/exercise2/exer2_2.py: -------------------------------------------------------------------------------- 1 | import exer2 2 | 3 | Car = exer2.Car('2009','Hyundai') 4 | for x in range(5): 5 | Car.accelerate() 6 | print('Current speed is', Car.get_speed()) 7 | for y in range(5): 8 | Car.brake() 9 | print('Current speed is', Car.get_speed()) -------------------------------------------------------------------------------- /Chapter 02/variable_demo2.py: -------------------------------------------------------------------------------- 1 | # Create two variables: top_speed and distance. 2 | top_speed = 160 3 | distance = 300 4 | 5 | # Display the values referenced by the variables. 6 | print('The top speed is') 7 | print(top_speed) 8 | print('The distance traveled is') 9 | print(distance) 10 | -------------------------------------------------------------------------------- /Chapter 04/rectangluar_pattern.py: -------------------------------------------------------------------------------- 1 | # This program displays a rectangular pattern 2 | # of asterisks. 3 | rows = int(input('How many rows? ')) 4 | cols = int(input('How many columns? ')) 5 | 6 | for r in range(rows): 7 | for c in range(cols): 8 | print('*', end='') 9 | print() 10 | -------------------------------------------------------------------------------- /Chapter 10/exercise3/program.py: -------------------------------------------------------------------------------- 1 | import information 2 | 3 | my_contact_info = information.Information("Desait","Mplampla 12, Thessaloniki","35","6932319480") 4 | mom = information.Information('Mom', 'Mplampla 26','62','6936859656') 5 | dad = information.Information('Dad', 'Mpilpl 33', '83','235423535123') 6 | -------------------------------------------------------------------------------- /Chapter 05/bad_local.py: -------------------------------------------------------------------------------- 1 | # Definition of the main function. 2 | def main(): 3 | get_name() 4 | print('Hello', name) # This causes an error! 5 | 6 | # Definition of the get_name function. 7 | def get_name(): 8 | name = input('Enter your name: ') 9 | 10 | # Call the main function. 11 | main() 12 | -------------------------------------------------------------------------------- /Chapter 05/global2.py: -------------------------------------------------------------------------------- 1 | # Create a global variable. 2 | number = 0 3 | 4 | def main(): 5 | global number 6 | number = int(input('Enter a number: ')) 7 | show_number() 8 | 9 | def show_number(): 10 | print('The number you entered is', number) 11 | 12 | # Call the main function. 13 | main() 14 | 15 | -------------------------------------------------------------------------------- /Chapter 13/empty_window1.py: -------------------------------------------------------------------------------- 1 | # This program displays an empty window. 2 | 3 | import tkinter 4 | 5 | def main(): 6 | # Create the main window widget. 7 | main_window = tkinter.Tk() 8 | 9 | # Enter the tkinter main loop. 10 | tkinter.mainloop() 11 | 12 | # Call the main function. 13 | main() 14 | -------------------------------------------------------------------------------- /Chapter 05/random_numbers.py: -------------------------------------------------------------------------------- 1 | # This program displays a random number 2 | # in the range of 1 through 10. 3 | import random 4 | 5 | def main(): 6 | # Get a random number. 7 | number = random.randint(1, 10) 8 | # Display the number. 9 | print('The number is', number) 10 | 11 | # Call the main function. 12 | main() 13 | -------------------------------------------------------------------------------- /Chapter 02/simple_math.py: -------------------------------------------------------------------------------- 1 | # Assign a value to the salary variable. 2 | salary = 2500.0 3 | 4 | # Assign a value to the bonus variable. 5 | bonus = 1200.0 6 | 7 | # Calculate the total pay by adding salary 8 | # and bonus. Assign the result to pay. 9 | pay = salary + bonus 10 | 11 | # Display the pay. 12 | print('Your pay is', pay) 13 | -------------------------------------------------------------------------------- /Chapter 02/variable_demo4.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates variable reassignment. 2 | # Assign a value to the dollars variable. 3 | dollars = 2.75 4 | print('I have', dollars, 'in my account.') 5 | 6 | # Reassign dollars so it references 7 | # a different value. 8 | dollars = 99.95 9 | print('But now I have', dollars, 'in my account!') 10 | -------------------------------------------------------------------------------- /Chapter 02/input.py: -------------------------------------------------------------------------------- 1 | # Get the user's name, age, and income. 2 | name = input('What is your name? ') 3 | age = int(input('What is your age? ')) 4 | income = float(input('What is your income? ')) 5 | 6 | # Display the data. 7 | print('Here is the data you entered:') 8 | print('Name:', name) 9 | print('Age:', age) 10 | print('Income:', income) 11 | 12 | -------------------------------------------------------------------------------- /Chapter 03/password.py: -------------------------------------------------------------------------------- 1 | # This program compares two strings. 2 | # Get a password from the user. 3 | password = input('Enter the password: ') 4 | 5 | # Determine whether the correct password 6 | # was entered. 7 | if password == 'prospero': 8 | print('Password accepted.') 9 | else: 10 | print('Sorry, that is the wrong password.') 11 | 12 | -------------------------------------------------------------------------------- /Chapter 05/random_numbers2.py: -------------------------------------------------------------------------------- 1 | # This program displays five random 2 | # numbers in the range of 1 through 100. 3 | import random 4 | 5 | def main(): 6 | for count in range(5): 7 | # Get a random number. 8 | number = random.randint(1, 100) 9 | # Display the number. 10 | print(number) 11 | 12 | # Call the main function. 13 | main() 14 | -------------------------------------------------------------------------------- /Chapter 08/string_split.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the split method. 2 | 3 | def main(): 4 | # Create a string with multiple words. 5 | my_string = 'One two three four' 6 | 7 | # Split the string. 8 | word_list = my_string.split() 9 | 10 | # Print the list of words. 11 | print(word_list) 12 | 13 | # Call the main function. 14 | main() 15 | 16 | -------------------------------------------------------------------------------- /Chapter 10/exercise2/exer2.py: -------------------------------------------------------------------------------- 1 | class Car: 2 | def __init__(self,year,make): 3 | self.__year_model = year 4 | self.__make = make 5 | self.__speed = 0 6 | 7 | def accelerate(self): 8 | self.__speed += 5 9 | 10 | def brake(self): 11 | self.__speed -= 5 12 | 13 | def get_speed(self): 14 | return self.__speed -------------------------------------------------------------------------------- /Chapter 05/pass_arg.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates an argument being 2 | # passed to a function. 3 | 4 | def main(): 5 | value = 5 6 | show_double(value) 7 | 8 | # The show_double function accepts an argument 9 | # and displays double its value. 10 | def show_double(number): 11 | result = number * 2 12 | print(result) 13 | 14 | # Call the main function. 15 | main() 16 | -------------------------------------------------------------------------------- /Chapter 05/two_functions.py: -------------------------------------------------------------------------------- 1 | # This program has two functions. First we 2 | # define the main function. 3 | def main(): 4 | print('I have a message for you.') 5 | message() 6 | print('Goodbye!') 7 | 8 | # Next we define the message function. 9 | def message(): 10 | print('I am Arthur') 11 | print('King of the Britons.') 12 | 13 | # Call the main function. 14 | main() 15 | -------------------------------------------------------------------------------- /Chapter 08/repetition_operator.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the repetition operator. 2 | 3 | def main(): 4 | # Print nine rows increasing in length. 5 | for count in range(1, 10): 6 | print('Z' * count) 7 | 8 | # Print nine rows decreasing in length. 9 | for count in range(8, 0, -1): 10 | print('Z' * count) 11 | 12 | # Call the main function. 13 | main() 14 | -------------------------------------------------------------------------------- /Chapter 13/empty_window2.py: -------------------------------------------------------------------------------- 1 | # This program displays an empty window. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | def __init__(self): 7 | # Create the main window widget. 8 | self.main_window = tkinter.Tk() 9 | 10 | # Enter the tkinter main loop. 11 | tkinter.mainloop() 12 | 13 | # Create an instance of the MyGUI class. 14 | my_gui = MyGUI() 15 | 16 | -------------------------------------------------------------------------------- /Chapter 04/squares.py: -------------------------------------------------------------------------------- 1 | # This program uses a loop to display a 2 | # table showing the numbers 1 through 10 3 | # and their squares. 4 | 5 | # Print the table headings. 6 | print('Number\tSquare') 7 | print('--------------') 8 | 9 | # Print the numbers 1 through 10 10 | # and their squares. 11 | for number in range(1, 11): 12 | square = number**2 13 | print(number, '\t', square) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter 05/multiple_args.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a function that accepts 2 | # two arguments. 3 | 4 | def main(): 5 | print('The sum of 12 and 45 is') 6 | show_sum(12, 45) 7 | 8 | # The show_sum function accepts two arguments 9 | # and displays their sum. 10 | def show_sum(num1, num2): 11 | result = num1 + num2 12 | print(result) 13 | 14 | # Call the main function. 15 | main() 16 | -------------------------------------------------------------------------------- /Chapter 06/division.py: -------------------------------------------------------------------------------- 1 | # This program divides a number by another number. 2 | 3 | def main(): 4 | # Get two numbers. 5 | num1 = int(input('Enter a number: ')) 6 | num2 = int(input('Enter another number: ')) 7 | 8 | # Divide num1 by num2 and display the result. 9 | result = num1 / num2 10 | print(num1, 'divided by', num2, 'is', result) 11 | 12 | # Call the main function. 13 | main() 14 | -------------------------------------------------------------------------------- /Chapter 04/gross_pay.py: -------------------------------------------------------------------------------- 1 | # This program displays gross pay. 2 | # Get the number of hours worked. 3 | hours = int(input('Enter the hours worked this week: ')) 4 | 5 | # Get the hourly pay rate. 6 | pay_rate = float(input('Enter the hourly pay rate: ')) 7 | 8 | # Calculate the gross pay. 9 | gross_pay = hours * pay_rate 10 | 11 | # Display the gross pay. 12 | print('Gross pay: $', format(gross_pay, ',.2f')) 13 | 14 | -------------------------------------------------------------------------------- /Chapter 12/recursive.py: -------------------------------------------------------------------------------- 1 | # This program has a recursive function. 2 | 3 | def main(): 4 | # By passing the argument 5 to the message 5 | # function we are telling it to display the 6 | # message five times. 7 | message(5) 8 | 9 | def message(times): 10 | if times > 0: 11 | print('This is a recursive function.') 12 | message(times - 1) 13 | 14 | # Call the main function. 15 | main() 16 | -------------------------------------------------------------------------------- /Chapter 05/square_root.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the sqrt function. 2 | import math 3 | 4 | def main(): 5 | # Get a number. 6 | number = float(input('Enter a number: ')) 7 | 8 | # Get the square root of the number. 9 | square_root = math.sqrt(number) 10 | 11 | # Display the square root. 12 | print('The square root of', number, 'is', square_root) 13 | 14 | # Call the main function. 15 | main() 16 | -------------------------------------------------------------------------------- /Chapter 11/wrong_type.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | # Pass a string to show_mammal_info... 3 | show_mammal_info('I am a string') 4 | 5 | # The show_mammal_info function accepts an object 6 | # as an argument, and calls its show_species 7 | # and make_sound methods. 8 | 9 | def show_mammal_info(creature): 10 | creature.show_species() 11 | creature.make_sound() 12 | 13 | # Call the main function. 14 | main() 15 | -------------------------------------------------------------------------------- /Chapter 05/string_args.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates passing two string 2 | # arguments to a function. 3 | 4 | def main(): 5 | first_name = input('Enter your first name: ') 6 | last_name = input('Enter your last name: ') 7 | print('Your name reversed is') 8 | reverse_name(first_name, last_name) 9 | 10 | def reverse_name(first, last): 11 | print(last, first) 12 | 13 | # Call the main function. 14 | main() 15 | 16 | -------------------------------------------------------------------------------- /Chapter 05/change_me.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates what happens when you 2 | # change the value of a parameter. 3 | 4 | def main(): 5 | value = 99 6 | print('The value is', value) 7 | change_me(value) 8 | print('Back in main the value is', value) 9 | 10 | def change_me(arg): 11 | print('I am changing the value.') 12 | arg = 0 13 | print('Now the value is', arg) 14 | 15 | # Call the main function. 16 | main() 17 | -------------------------------------------------------------------------------- /Chapter 05/coin_toss.py: -------------------------------------------------------------------------------- 1 | # This program simulates 10 tosses of a coin. 2 | import random 3 | 4 | # Constants 5 | HEADS = 1 6 | TAILS = 2 7 | TOSSES = 10 8 | 9 | def main(): 10 | for toss in range(TOSSES): 11 | # Simulate the coin toss. 12 | if random.randint(HEADS, TAILS) == HEADS: 13 | print('Heads') 14 | else: 15 | print('Tails') 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 05/keyword_string_args.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates passes two strings as 2 | # keyword arguments to a function. 3 | 4 | def main(): 5 | first_name = input('Enter your first name: ') 6 | last_name = input('Enter your last name: ') 7 | print('Your name reversed is') 8 | reverse_name(last=last_name, first=first_name) 9 | 10 | def reverse_name(first, last): 11 | print(last, first) 12 | 13 | # Call the main function. 14 | main() 15 | 16 | -------------------------------------------------------------------------------- /Chapter 05/circle.py: -------------------------------------------------------------------------------- 1 | # The circle module has functions that perform 2 | # calculations related to circles. 3 | import math 4 | 5 | # The area function accepts a circle's radius as an 6 | # argument and returns the area of the circle. 7 | def area(radius): 8 | return math.pi * radius**2 9 | 10 | # The circumference function accepts a circle's 11 | # radius and returns the circle's circumference. 12 | def circumference(radius): 13 | return 2 * math.pi * radius 14 | 15 | -------------------------------------------------------------------------------- /Chapter 03/sort_names.py: -------------------------------------------------------------------------------- 1 | # This program compare strings with the < operator. 2 | # Get two names from the user. 3 | name1 = input('Enter a name (last name first): ') 4 | name2 = input('Enter another name (last name first): ') 5 | 6 | # Display the names in alphabetical order. 7 | print('Here are the names, listed alphabetically.') 8 | 9 | if name1 < name2: 10 | print(name1) 11 | print(name2) 12 | else: 13 | print(name2) 14 | print(name1) 15 | 16 | 17 | -------------------------------------------------------------------------------- /Chapter 02/sale_price.py: -------------------------------------------------------------------------------- 1 | # This program gets an item's original price and 2 | # calculates its sale price, with a 20% discount. 3 | 4 | # Get the item's original price. 5 | original_price = float(input("Enter the item's original price: ")) 6 | 7 | # Calculate the amount of the discount. 8 | discount = original_price * 0.2 9 | 10 | # Calculate the sale price. 11 | sale_price = original_price - discount 12 | 13 | # Display the sale price. 14 | print('The sale price is', sale_price) 15 | -------------------------------------------------------------------------------- /Chapter 06/file_write.py: -------------------------------------------------------------------------------- 1 | # This program writes three lines of data 2 | # to a file. 3 | def main(): 4 | # Open a file named philosophers.txt. 5 | outfile = open('philosophers.txt', 'w') 6 | 7 | # Write the names of three philosphers 8 | # to the file. 9 | outfile.write('John Locke\n') 10 | outfile.write('David Hume\n') 11 | outfile.write('Edmund Burke\n') 12 | 13 | # Close the file. 14 | outfile.close() 15 | 16 | # Call the main function. 17 | main() 18 | -------------------------------------------------------------------------------- /Chapter 07/write_list.py: -------------------------------------------------------------------------------- 1 | # This program saves a list of strings to a file. 2 | 3 | def main(): 4 | # Create a list of strings. 5 | cities = ['New York', 'Boston', 'Atlanta', 'Dallas'] 6 | 7 | # Open a file for writing. 8 | outfile = open('cities.txt', 'w') 9 | 10 | # Write the list to the file. 11 | for item in cities: 12 | outfile.write(item + '\n') 13 | 14 | # Close the file. 15 | outfile.close() 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 07/write_number_list.py: -------------------------------------------------------------------------------- 1 | # This program saves a list of numbers to a file. 2 | 3 | def main(): 4 | # Create a list of numbers. 5 | numbers = [1, 2, 3, 4, 5, 6, 7] 6 | 7 | # Open a file for writing. 8 | outfile = open('numberlist.txt', 'w') 9 | 10 | # Write the list to the file. 11 | for item in numbers: 12 | outfile.write(str(item) + '\n') 13 | 14 | # Close the file. 15 | outfile.close() 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 08/split_date.py: -------------------------------------------------------------------------------- 1 | # This program calls the split method, using the 2 | # '/' character as a separator. 3 | 4 | def main(): 5 | # Create a string with a date. 6 | date_string = '11/26/2012' 7 | 8 | # Split the date. 9 | date_list = date_string.split('/') 10 | 11 | # Display each piece of the date. 12 | print('Month:', date_list[0]) 13 | print('Day:', date_list[1]) 14 | print('Year:', date_list[2]) 15 | 16 | # Call the main function. 17 | main() 18 | -------------------------------------------------------------------------------- /Chapter 06/file_read.py: -------------------------------------------------------------------------------- 1 | # This program reads and displays the contents 2 | # of the philosophers.txt file. 3 | def main(): 4 | # Open a file named philosophers.txt. 5 | infile = open('philosophers.txt', 'r') 6 | 7 | # Read the file's contents. 8 | file_contents = infile.read() 9 | 10 | # Close the file. 11 | infile.close() 12 | 13 | # Print the data that was read into 14 | # memory. 15 | print(file_contents) 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 07/writelines.py: -------------------------------------------------------------------------------- 1 | # This program uses the writelines method to save 2 | # a list of strings to a file. 3 | 4 | def main(): 5 | # Create a list of strings. 6 | cities = ['New York', 'Boston', 'Atlanta', 'Dallas'] 7 | 8 | # Open a file for writing. 9 | outfile = open('cities.txt', 'w') 10 | 11 | # Write the list to the file. 12 | outfile.writelines(cities) 13 | 14 | # Close the file. 15 | outfile.close() 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 07/USPopulation.txt: -------------------------------------------------------------------------------- 1 | 151868 2 | 153982 3 | 156393 4 | 158956 5 | 161884 6 | 165069 7 | 168088 8 | 171187 9 | 174149 10 | 177135 11 | 179979 12 | 182992 13 | 185771 14 | 188483 15 | 191141 16 | 193526 17 | 195576 18 | 197457 19 | 199399 20 | 201385 21 | 203984 22 | 206827 23 | 209284 24 | 211357 25 | 213342 26 | 215465 27 | 217563 28 | 219760 29 | 222095 30 | 224567 31 | 227225 32 | 229466 33 | 231664 34 | 233792 35 | 235825 36 | 237924 37 | 240133 38 | 242289 39 | 244499 40 | 246819 41 | 249623 -------------------------------------------------------------------------------- /Chapter 06/display_file.py: -------------------------------------------------------------------------------- 1 | # This program displays the contents 2 | # of a file. 3 | 4 | def main(): 5 | # Get the name of a file. 6 | filename = input('Enter a filename: ') 7 | 8 | # Open the file. 9 | infile = open(filename, 'r') 10 | 11 | # Read the file's contents. 12 | contents = infile.read() 13 | 14 | # Display the file's contents. 15 | print(contents) 16 | 17 | # Close the file. 18 | infile.close() 19 | 20 | # Call the main function. 21 | main() 22 | 23 | -------------------------------------------------------------------------------- /Chapter 05/rectangle.py: -------------------------------------------------------------------------------- 1 | # The rectangle module has functions that perform 2 | # calculations related to rectangles. 3 | 4 | # The area function accepts a rectangle's width and 5 | # length as arguments and returns the rectangle's area. 6 | def area(width, length): 7 | return width * length 8 | 9 | # The perimeter function accepts a rectangle's width 10 | # and length as arguments and returns the rectangle's 11 | # perimeter. 12 | def perimeter(width, length): 13 | return 2 * (width + length) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Chapter 07/insert_list.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the insert method. 2 | 3 | def main(): 4 | # Create a list with some names. 5 | names = ['James', 'Kathryn', 'Bill'] 6 | 7 | # Display the list. 8 | print('The list before the insert:') 9 | print(names) 10 | 11 | # Insert a new name at element 0. 12 | names.insert(0, 'Joe') 13 | 14 | # Display the list again. 15 | print('The list after the insert:') 16 | print(names) 17 | 18 | # Call the main function. 19 | main() 20 | -------------------------------------------------------------------------------- /Chapter 02/test_score_average.py: -------------------------------------------------------------------------------- 1 | # Get three test scores and assign them to the 2 | # test1, test2, and test3 variables. 3 | test1 = float(input('Enter the first test score: ')) 4 | test2 = float(input('Enter the second test score: ')) 5 | test3 = float(input('Enter the third test score: ')) 6 | 7 | # Calculate the average of the three scores 8 | # and assign the result to the average variable. 9 | average = (test1 + test2 + test3) / 3.0 10 | 11 | # Display the average. 12 | print('The average score is', average) 13 | -------------------------------------------------------------------------------- /Chapter 06/gross_pay1.py: -------------------------------------------------------------------------------- 1 | # This program calculates gross pay. 2 | 3 | def main(): 4 | # Get the number of hours worked. 5 | hours = int(input('How many hours did you work? ')) 6 | 7 | # Get the hourly pay rate. 8 | pay_rate = float(input('Enter your hourly pay rate: ')) 9 | 10 | # Calculate the gross pay. 11 | gross_pay = hours * pay_rate 12 | 13 | # Display the gross pay. 14 | print('Gross pay: $', format(gross_pay, ',.2f'), sep='') 15 | 16 | # Call the main function. 17 | main() 18 | -------------------------------------------------------------------------------- /Chapter 08/validate_password.py: -------------------------------------------------------------------------------- 1 | # This program gets a password from the user and 2 | # validates it. 3 | 4 | import login 5 | 6 | def main(): 7 | # Get a password from the user. 8 | password = input('Enter your password: ') 9 | 10 | # Validate the password. 11 | while not login.valid_password(password): 12 | print('That password is not valid.') 13 | password = input('Enter your password: ') 14 | 15 | print('That is a valid password.') 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 07/total_list.py: -------------------------------------------------------------------------------- 1 | # This program calculates the total of the values 2 | # in a list. 3 | 4 | def main(): 5 | # Create a list. 6 | numbers = [2, 4, 6, 8, 10] 7 | 8 | # Create a variable to use as an accumulator. 9 | total = 0 10 | 11 | # Calculate the total of the list elements. 12 | for value in numbers: 13 | total += value 14 | 15 | # Display the total of the list elements. 16 | print('The total of the elements is', total) 17 | 18 | # Call the main function. 19 | main() 20 | -------------------------------------------------------------------------------- /Chapter 02/columns.py: -------------------------------------------------------------------------------- 1 | # This program displays the following 2 | # floating-point numbers in a column 3 | # with their decimal points aligned. 4 | num1 = 127.899 5 | num2 = 3465.148 6 | num3 = 3.776 7 | num4 = 264.821 8 | num5 = 88.081 9 | num6 = 799.999 10 | 11 | # Display each number in a field of 7 spaces 12 | # with 2 decimal places. 13 | print(format(num1, '7.2f')) 14 | print(format(num2, '7.2f')) 15 | print(format(num3, '7.2f')) 16 | print(format(num4, '7.2f')) 17 | print(format(num5, '7.2f')) 18 | print(format(num6, '7.2f')) 19 | -------------------------------------------------------------------------------- /Chapter 05/hypotenuse.py: -------------------------------------------------------------------------------- 1 | # This program calculates the length of a right 2 | # triangle's hypotenuse. 3 | import math 4 | 5 | def main(): 6 | # Get the length of the triangle's two sides. 7 | a = float(input('Enter the length of side A: ')) 8 | b = float(input('Enter the length of side B: ')) 9 | 10 | # Calculate the length of the hypotenuse. 11 | c = math.hypot(a, b) 12 | 13 | # Display the length of the hypotenuse. 14 | print('The length of the hypotenuse is', c) 15 | 16 | # Call the main function. 17 | main() 18 | -------------------------------------------------------------------------------- /Chapter 10/exercise4/employee.py: -------------------------------------------------------------------------------- 1 | class Employee: 2 | def __init__(self,name,id_number,department,job_title): 3 | self.__name = name 4 | self.__id_number = id_number 5 | self.__department = department 6 | self.__job_title = job_title 7 | 8 | def get_name(self): 9 | return self.__name 10 | def get_id_number(self): 11 | return self.__id_number 12 | def get_department(self): 13 | return self.__department 14 | def get_job_title(self): 15 | return self.__job_title -------------------------------------------------------------------------------- /Chapter 06/division2.py: -------------------------------------------------------------------------------- 1 | # This program divides a number by another number. 2 | 3 | def main(): 4 | # Get two numbers. 5 | num1 = int(input('Enter a number: ')) 6 | num2 = int(input('Enter another number: ')) 7 | 8 | # If num2 is not zero, divide num1 by num2 9 | # and display the result. 10 | if num2 != 0: 11 | result = num1 / num2 12 | print(num1, 'divided by', num2, 'is', result) 13 | else: 14 | print('Cannot divide by zero.') 15 | 16 | # Call the main function. 17 | main() 18 | -------------------------------------------------------------------------------- /Chapter 02/time_converter.py: -------------------------------------------------------------------------------- 1 | # Get a number of seconds from the user. 2 | total_seconds = float(input('Enter a number of seconds: ')) 3 | 4 | # Get the number of hours. 5 | hours = total_seconds // 3600 6 | 7 | # Get the number of remaining minutes. 8 | minutes = (total_seconds // 60) % 60 9 | 10 | # Get the number of remaining seconds. 11 | seconds = total_seconds % 60 12 | 13 | # Display the results. 14 | print('Here is the time in hours, minutes, and seconds:') 15 | print('Hours:', hours) 16 | print('Minutes:', minutes) 17 | print('Seconds:', seconds) 18 | -------------------------------------------------------------------------------- /Chapter 04/user_squares1.py: -------------------------------------------------------------------------------- 1 | # This program uses a loop to display a 2 | # table of numbers and their squares. 3 | 4 | # Get the ending limit. 5 | print('This program displays a list of numbers') 6 | print('(starting at 1) and their squares.') 7 | end = int(input('How high should I go? ')) 8 | 9 | # Print the table headings. 10 | print() 11 | print('Number\tSquare') 12 | print('--------------') 13 | 14 | # Print the numbers and their squares. 15 | for number in range(1, end + 1): 16 | square = number**2 17 | print(number, '\t', square) 18 | 19 | 20 | -------------------------------------------------------------------------------- /Chapter 12/fibonacci.py: -------------------------------------------------------------------------------- 1 | # This program uses recursion to print numbers 2 | # from the Fibonacci series. 3 | 4 | def main(): 5 | print('The first 10 numbers in the') 6 | print('Fibonacci series are:') 7 | 8 | for number in range(1, 11): 9 | print(fib(number)) 10 | 11 | # The fib function returns the nth number 12 | # in the Fibonacci series. 13 | def fib(n): 14 | if n == 0: 15 | return 0 16 | elif n == 1: 17 | return 1 18 | else: 19 | return fib(n - 1) + fib(n - 2) 20 | 21 | # Call the main function. 22 | main() 23 | -------------------------------------------------------------------------------- /Chapter 06/read_sales2.py: -------------------------------------------------------------------------------- 1 | # This program uses the for loop to read 2 | # all of the values in the sales.txt file. 3 | 4 | def main(): 5 | # Open the sales.txt file for reading. 6 | sales_file = open('sales.txt', 'r') 7 | 8 | # Read all the lines from the file. 9 | for line in sales_file: 10 | # Convert line to a float. 11 | amount = float(line) 12 | # Format and display the amount. 13 | print(format(amount, '.2f')) 14 | 15 | # Close the file. 16 | sales_file.close() 17 | 18 | # Call the main function. 19 | main() 20 | -------------------------------------------------------------------------------- /Chapter 02/future_value.py: -------------------------------------------------------------------------------- 1 | # Get the desired future value. 2 | future_value = float(input('Enter the desired future value: ')) 3 | 4 | # Get the annual interest rate. 5 | rate = float(input('Enter the annual interest rate: ')) 6 | 7 | # Get the number of years that the money will appreciate. 8 | years = int(input('Enter the number of years the money will grow: ')) 9 | 10 | # Calculate the amount needed to deposit. 11 | present_value = future_value / (1.0 + rate)**years 12 | 13 | # Display the amount needed to deposit. 14 | print('You will need to deposit this amount:', present_value) 15 | -------------------------------------------------------------------------------- /Chapter 10/coin_demo4.py: -------------------------------------------------------------------------------- 1 | # This program imports the coin module and 2 | # creates an instance of the Coin class. 3 | 4 | import coin 5 | 6 | def main(): 7 | # Create an object from the Coin class. 8 | my_coin = coin.Coin() 9 | 10 | # Display the side of the coin that is facing up. 11 | print('This side is up:', my_coin.get_sideup()) 12 | 13 | # Toss the coin. 14 | print('I am going to toss the coin ten times:') 15 | for count in range(10): 16 | my_coin.toss() 17 | print(my_coin.get_sideup()) 18 | 19 | # Call the main function. 20 | main() 21 | -------------------------------------------------------------------------------- /Chapter 04/infinite.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates an infinite loop. 2 | # Create a variable to control the loop. 3 | keep_going = 'y' 4 | 5 | # Warning! Infinite loop! 6 | while keep_going == 'y': 7 | # Get a salesperson's sales and commission rate. 8 | sales = float(input('Enter the amount of sales: ')) 9 | comm_rate = float(input('Enter the commission rate: ')) 10 | 11 | # Calculate the commission. 12 | commission = sales * comm_rate 13 | 14 | # Display the commission. 15 | print('The commission is $', \ 16 | format(commission, ',.2f'), sep='') 17 | 18 | -------------------------------------------------------------------------------- /Chapter 04/speed_converter.py: -------------------------------------------------------------------------------- 1 | # This program converts the speeds 60 kph 2 | # through 130 kph (in 10 kph increments) 3 | # to mph. 4 | 5 | start_speed = 60 # Starting speed 6 | end_speed = 131 # Ending speed 7 | increment = 10 # Speed increment 8 | conversion_factor = 0.6214 # Conversion factor 9 | 10 | # Print the table headings. 11 | print('KPH\tMPH') 12 | print('--------------') 13 | 14 | # Print the speeds. 15 | for kph in range(start_speed, end_speed, increment): 16 | mph = kph * conversion_factor 17 | print(kph, '\t', format(mph, '.1f')) 18 | 19 | -------------------------------------------------------------------------------- /Chapter 04/sum_numbers.py: -------------------------------------------------------------------------------- 1 | # This program calculates the sum of a series 2 | # of numbers entered by the user. 3 | 4 | max = 5 # The maximum number 5 | 6 | # Initialize an accumulator variable. 7 | total = 0.0 8 | 9 | # Explain what we are doing. 10 | print('This program calculates the sum of') 11 | print(max, 'numbers you will enter.') 12 | 13 | # Get the numbers and accumulate them. 14 | for counter in range(max): 15 | number = int(input('Enter a number: ')) 16 | total = total + number 17 | 18 | # Display the total of the numbers. 19 | print('The total is', total) 20 | 21 | 22 | -------------------------------------------------------------------------------- /Chapter 07/in_list.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the in operator 2 | # used with a list. 3 | 4 | def main(): 5 | # Create a list of product numbers. 6 | prod_nums = ['V475', 'F987', 'Q143', 'R688'] 7 | 8 | # Get a product number to search for. 9 | search = input('Enter a product number: ') 10 | 11 | # Determine whether the product number is in the list. 12 | if search in prod_nums: 13 | print(search, 'was found in the list.') 14 | else: 15 | print(search, 'was not found in the list.') 16 | 17 | # Call the main function. 18 | main() 19 | 20 | 21 | -------------------------------------------------------------------------------- /Chapter 10/car.py: -------------------------------------------------------------------------------- 1 | # Car class 2 | class Car: 3 | def __init__(self, make, model, year): 4 | self.__make = make 5 | self.__model = model 6 | self.__year = year 7 | 8 | def set_make(self, make): 9 | self.__make = make 10 | 11 | def set_model(self, model): 12 | self.__model = model 13 | 14 | def set_year(self, year): 15 | self.__year = year 16 | 17 | def get_make(self): 18 | return self.__make 19 | 20 | def get_model(self): 21 | return self.__model 22 | 23 | def get_year(self): 24 | return self.__year 25 | -------------------------------------------------------------------------------- /Chapter 06/line_read.py: -------------------------------------------------------------------------------- 1 | # This program reads the contents of the 2 | # philosophers.txt file one line at a time. 3 | def main(): 4 | # Open a file named philosophers.txt. 5 | infile = open('philosophers.txt', 'r') 6 | 7 | # Read three lines from the file 8 | line1 = infile.readline() 9 | line2 = infile.readline() 10 | line3 = infile.readline() 11 | 12 | # Close the file. 13 | infile.close() 14 | 15 | # Print the data that was read into 16 | # memory. 17 | print(line1) 18 | print(line2) 19 | print(line3) 20 | 21 | # Call the main function. 22 | main() 23 | -------------------------------------------------------------------------------- /Chapter 06/gross_pay3.py: -------------------------------------------------------------------------------- 1 | # This program calculates gross pay. 2 | 3 | def main(): 4 | try: 5 | # Get the number of hours worked. 6 | hours = int(input('How many hours did you work? ')) 7 | 8 | # Get the hourly pay rate. 9 | pay_rate = float(input('Enter your hourly pay rate: ')) 10 | 11 | # Calculate the gross pay. 12 | gross_pay = hours * pay_rate 13 | 14 | # Display the gross pay. 15 | print('Gross pay: $', format(gross_pay, ',.2f'), sep='') 16 | except ValueError as err: 17 | print(err) 18 | 19 | # Call the main function. 20 | main() 21 | -------------------------------------------------------------------------------- /Chapter 08/generate_login.py: -------------------------------------------------------------------------------- 1 | # This program gets the user's first name, last name, and 2 | # student ID number. Using this data it generates a 3 | # system login name. 4 | 5 | import login 6 | 7 | def main(): 8 | # Get the user's first name, last name, and ID number. 9 | first = input('Enter your first name: ') 10 | last = input('Enter your last name: ') 11 | idnumber = input('Enter your student ID number: ') 12 | 13 | # Get the login name. 14 | print('Your system login name is:') 15 | print(login.get_login_name(first, last, idnumber)) 16 | 17 | # Call the main function. 18 | main() 19 | -------------------------------------------------------------------------------- /Chapter 12/gcd.py: -------------------------------------------------------------------------------- 1 | # This program uses recursion to find the GCD 2 | # of two numbers. 3 | 4 | def main(): 5 | # Get two numbers. 6 | num1 = int(input('Enter an integer: ')) 7 | num2 = int(input('Enter another integer: ')) 8 | 9 | # Display the GCD. 10 | print('The greatest common divisor of') 11 | print('the two numbers is', gcd(num1, num2)) 12 | 13 | # The gcd function returns the greatest common 14 | # divisor of two numbers. 15 | def gcd(x, y): 16 | if x % y == 0: 17 | return y 18 | else: 19 | return gcd(x, x % y) 20 | 21 | # Call the main function. 22 | main() 23 | -------------------------------------------------------------------------------- /Chapter 07/read_list.py: -------------------------------------------------------------------------------- 1 | # This program reads a file's contents into a list. 2 | 3 | def main(): 4 | # Open a file for reading. 5 | infile = open('cities.txt', 'r') 6 | 7 | # Read the contents of the file into a list. 8 | cities = infile.readlines() 9 | 10 | # Close the file. 11 | infile.close() 12 | 13 | # Strip the \n from each element. 14 | index = 0 15 | while index < len(cities): 16 | cities[index] = cities[index].rstrip('\n') 17 | index += 1 18 | 19 | # Print the contents of the list. 20 | print(cities) 21 | 22 | # Call the main function. 23 | main() 24 | -------------------------------------------------------------------------------- /Chapter 07/read_number_list.py: -------------------------------------------------------------------------------- 1 | # This program reads numbers from a file into a list. 2 | 3 | def main(): 4 | # Open a file for reading. 5 | infile = open('numberlist.txt', 'r') 6 | 7 | # Read the contents of the file into a list. 8 | numbers = infile.readlines() 9 | 10 | # Close the file. 11 | infile.close() 12 | 13 | # Convert each element to an int. 14 | index = 0 15 | while index < len(numbers): 16 | numbers[index] = int(numbers[index]) 17 | index += 1 18 | 19 | # Print the contents of the list. 20 | print(numbers) 21 | 22 | # Call the main function. 23 | main() 24 | -------------------------------------------------------------------------------- /Chapter 08/count_Ts.py: -------------------------------------------------------------------------------- 1 | # This program counts the number of times 2 | # the letter T (uppercase or lowercase) 3 | # appears in a string. 4 | 5 | def main(): 6 | # Create a variable to use to hold the count. 7 | # The variable must start with 0. 8 | count = 0 9 | 10 | # Get a string from the user. 11 | my_string = input('Enter a sentence: ') 12 | 13 | # Count the Ts. 14 | for ch in my_string: 15 | if ch == 'T' or ch == 't': 16 | count += 1 17 | 18 | # Print the result. 19 | print('The letter T appears', count, 'times.') 20 | 21 | # Call the main function. 22 | main() 23 | 24 | -------------------------------------------------------------------------------- /Chapter 10/coin_argument.py: -------------------------------------------------------------------------------- 1 | # This program passes a Coin object as 2 | # an argument to a function. 3 | import coin 4 | 5 | # main function 6 | def main(): 7 | # Create a Coin object. 8 | my_coin = coin.Coin() 9 | 10 | # This will display 'Heads'. 11 | print(my_coin.get_sideup()) 12 | 13 | # Pass the object to the flip function. 14 | flip(my_coin) 15 | 16 | # This might display 'Heads', or it might 17 | # display 'Tails'. 18 | print(my_coin.get_sideup()) 19 | 20 | # The flip function flips a coin. 21 | def flip(coin_obj): 22 | coin_obj.toss() 23 | 24 | # Call the main function. 25 | main() 26 | -------------------------------------------------------------------------------- /Chapter 04/user_squares2.py: -------------------------------------------------------------------------------- 1 | # This program uses a loop to display a 2 | # table of numbers and their squares. 3 | 4 | # Get the starting value. 5 | print('This program displays a list of numbers') 6 | print('and their squares.') 7 | start = int(input('Enter the starting number: ')) 8 | 9 | # Get the ending limit. 10 | end = int(input('How high should I go? ')) 11 | 12 | # Print the table headings. 13 | print() 14 | print('Number\tSquare') 15 | print('--------------') 16 | 17 | # Print the numbers and their squares. 18 | for number in range(start, end + 1): 19 | square = number**2 20 | print(number, '\t', square) 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter 07/average_list.py: -------------------------------------------------------------------------------- 1 | # This program calculates the average of the values 2 | # in a list. 3 | 4 | def main(): 5 | # Create a list. 6 | scores = [2.5, 7.3, 6.5, 4.0, 5.2] 7 | 8 | # Create a variable to use as an accumulator. 9 | total = 0.0 10 | 11 | # Calculate the total of the list elements. 12 | for value in scores: 13 | total += value 14 | 15 | # Calculate the average of the elements. 16 | average = total / len(scores) 17 | 18 | # Display the total of the list elements. 19 | print('The average of the elements is', average) 20 | 21 | # Call the main function. 22 | main() 23 | -------------------------------------------------------------------------------- /Chapter 10/customer.py: -------------------------------------------------------------------------------- 1 | # Customer class 2 | class Customer: 3 | def __init__(self, name, address, phone): 4 | self.__name = name 5 | self.__address = address 6 | self.__phone = phone 7 | 8 | def set_name(self, name): 9 | self.__name = name 10 | 11 | def set_address(self, address): 12 | self.__address = address 13 | 14 | def set_phone(self, phone): 15 | self.__phone = phone 16 | 17 | def get_name(self): 18 | return self.__name 19 | 20 | def get_address(self): 21 | return self.__address 22 | 23 | def get_phone(self): 24 | return self.__phone 25 | -------------------------------------------------------------------------------- /Chapter 07/random_numbers.py: -------------------------------------------------------------------------------- 1 | # This program assigns random numbers to 2 | # a two-dimensional list. 3 | import random 4 | 5 | # Constants for rows and columns 6 | ROWS = 3 7 | COLS = 4 8 | 9 | def main(): 10 | # Create a two-dimensional list. 11 | values = [[0, 0, 0, 0], 12 | [0, 0, 0, 0], 13 | [0, 0, 0, 0]] 14 | 15 | # Fill the list with random numbers. 16 | for r in range(ROWS): 17 | for c in range(COLS): 18 | values[r][c] = random.randint(1, 100) 19 | 20 | # Display the random numbers. 21 | print(values) 22 | 23 | # Call the main function. 24 | main() 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Chapter 05/birds.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates two functions that 2 | # have local variables with the same name. 3 | 4 | def main(): 5 | # Call the texas function. 6 | texas() 7 | # Call the california function. 8 | california() 9 | 10 | # Definition of the texas function. It creates 11 | # a local variable named birds. 12 | def texas(): 13 | birds = 5000 14 | print('texas has', birds, 'birds.') 15 | 16 | # Definition of the california function. It also 17 | # creates a local variable named birds. 18 | def california(): 19 | birds = 8000 20 | print('california has', birds, 'birds.') 21 | 22 | # Call the main function. 23 | main() 24 | -------------------------------------------------------------------------------- /Chapter 06/display_file2.py: -------------------------------------------------------------------------------- 1 | # This program displays the contents 2 | # of a file. 3 | 4 | def main(): 5 | # Get the name of a file. 6 | filename = input('Enter a filename: ') 7 | 8 | try: 9 | # Open the file. 10 | infile = open(filename, 'r') 11 | 12 | # Read the file's contents. 13 | contents = infile.read() 14 | 15 | # Display the file's contents. 16 | print(contents) 17 | 18 | # Close the file. 19 | infile.close() 20 | except IOError: 21 | print('An error occurred trying to read') 22 | print('the file', filename) 23 | 24 | # Call the main function. 25 | main() 26 | 27 | -------------------------------------------------------------------------------- /Chapter 05/dice.py: -------------------------------------------------------------------------------- 1 | # This program simulates the rolling of dice. 2 | import random 3 | 4 | # Constants for the minimum and maximum random numbers 5 | MIN = 1 6 | MAX = 6 7 | 8 | def main(): 9 | # Create a variable to control the loop. 10 | again = 'y' 11 | 12 | # Simulate rolling the dice. 13 | while again == 'y' or again == 'Y': 14 | print('Rolling the dice...') 15 | print('Their values are:') 16 | print(random.randint(MIN, MAX)) 17 | print(random.randint(MIN, MAX)) 18 | 19 | # Do another roll of the dice? 20 | again = input('Roll them again? (y = yes): ') 21 | 22 | # Call the main function. 23 | main() 24 | -------------------------------------------------------------------------------- /Chapter 11/car_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the Car class. 2 | 3 | import vehicles 4 | 5 | def main(): 6 | # Create an object from the Car class. 7 | # The car is a 2007 Audi with 12,500 miles, priced 8 | # at $21,500.00, and has 4 doors. 9 | used_car = vehicles.Car('Audi', 2007, 12500, 21500.00, 4) 10 | 11 | # Display the car's data. 12 | print('Make:', used_car.get_make()) 13 | print('Model:', used_car.get_model()) 14 | print('Mileage:', used_car.get_mileage()) 15 | print('Price:', used_car.get_price()) 16 | print('Number of doors:', used_car.get_doors()) 17 | 18 | # Call the main function. 19 | main() 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_3/sampletext.txt: -------------------------------------------------------------------------------- 1 | Slavery was practiced throughout the American colonies in the 17th and 18th centuries, 2 | and African slaves helped build the new nation into an economic powerhouse through the 3 | production of lucrative crops such as tobacco and cotton. By the mid-19th century, 4 | America’s westward expansion and the abolition movement provoked a great debate over 5 | slavery that would tear the nation apart in the bloody Civil War. Though the Union victory 6 | freed the nation’s four million slaves, the legacy of slavery continued to influence 7 | American history, from the Reconstruction era to the civil rights movement that emerged 8 | a century after emancipation. 9 | -------------------------------------------------------------------------------- /Chapter 13/hello_world.py: -------------------------------------------------------------------------------- 1 | # This program displays a label with text. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | def __init__(self): 7 | # Create the main window widget. 8 | self.main_window = tkinter.Tk() 9 | 10 | # Create a Label widget containing the 11 | # text 'Hello World!' 12 | self.label = tkinter.Label(self.main_window, \ 13 | text='Hello World!') 14 | 15 | # Call the Label widget's pack method. 16 | self.label.pack() 17 | 18 | # Enter the tkinter main loop. 19 | tkinter.mainloop() 20 | 21 | # Create an instance of the MyGUI class. 22 | my_gui = MyGUI() 23 | 24 | -------------------------------------------------------------------------------- /Chapter 06/gross_pay2.py: -------------------------------------------------------------------------------- 1 | # This program calculates gross pay. 2 | 3 | def main(): 4 | try: 5 | # Get the number of hours worked. 6 | hours = int(input('How many hours did you work? ')) 7 | 8 | # Get the hourly pay rate. 9 | pay_rate = float(input('Enter your hourly pay rate: ')) 10 | 11 | # Calculate the gross pay. 12 | gross_pay = hours * pay_rate 13 | 14 | # Display the gross pay. 15 | print('Gross pay: $', format(gross_pay, ',.2f'), sep='') 16 | except ValueError: 17 | print('ERROR: Hours worked and hourly pay rate must') 18 | print('be valid integers.') 19 | 20 | # Call the main function. 21 | main() 22 | -------------------------------------------------------------------------------- /Chapter 03/loan_qualifier3.py: -------------------------------------------------------------------------------- 1 | # This program determines whether a bank customer 2 | # qualifies for a loan. 3 | 4 | min_salary = 30000.0 # The minimum annual salary 5 | min_years = 2 # The minimum years on the job 6 | 7 | # Get the customer's annual salary. 8 | salary = float(input('Enter your annual salary: ')) 9 | 10 | # Get the number of years on the current job. 11 | years_on_job = int(input('Enter the number of ' + 12 | 'years employed: ')) 13 | 14 | # Determine whether the customer qualifies. 15 | if salary >= min_salary or years_on_job >= min_years: 16 | print('You qualify for the loan.') 17 | else: 18 | print('You do not qualify for this loan.') 19 | -------------------------------------------------------------------------------- /Chapter 03/loan_qualifier2.py: -------------------------------------------------------------------------------- 1 | # This program determines whether a bank customer 2 | # qualifies for a loan. 3 | 4 | min_salary = 30000.0 # The minimum annual salary 5 | min_years = 2 # The minimum years on the job 6 | 7 | # Get the customer's annual salary. 8 | salary = float(input('Enter your annual salary: ')) 9 | 10 | # Get the number of years on the current job. 11 | years_on_job = int(input('Enter the number of ' + 12 | 'years employed: ')) 13 | 14 | # Determine whether the customer qualifies. 15 | if salary >= min_salary and years_on_job >= min_years: 16 | print('You qualify for the loan.') 17 | else: 18 | print('You do not qualify for this loan.') 19 | 20 | -------------------------------------------------------------------------------- /Chapter 05/total_ages.py: -------------------------------------------------------------------------------- 1 | # This program uses the return value of a function. 2 | 3 | def main(): 4 | # Get the user's age. 5 | first_age = int(input('Enter your age: ')) 6 | 7 | # Get the user's best friend's age. 8 | second_age = int(input("Enter your best friend's age: ")) 9 | 10 | # Get the sum of both ages. 11 | total = sum(first_age, second_age) 12 | 13 | # Display the total age. 14 | print('Together you are', total, 'years old.') 15 | 16 | # The sum function accepts two numeric arguments and 17 | # returns the sum of those arguments. 18 | def sum(num1, num2): 19 | result = num1 + num2 20 | return result 21 | 22 | # Call the main function. 23 | main() 24 | -------------------------------------------------------------------------------- /Chapter 12/factorial.py: -------------------------------------------------------------------------------- 1 | # This program uses recursion to calculate 2 | # the factorial of a number. 3 | 4 | def main(): 5 | # Get a number from the user. 6 | number = int(input('Enter a nonnegative integer: ')) 7 | 8 | # Get the factorial of the number. 9 | fact = factorial(number) 10 | 11 | # Display the factorial. 12 | print('The factorial of', number, 'is', fact) 13 | 14 | # The factorial function uses recursion to 15 | # calculate the factorial of its argument, 16 | # which is assumed to be nonnegative. 17 | def factorial(num): 18 | if num == 0: 19 | return 1 20 | else: 21 | return num * factorial(num - 1) 22 | 23 | # Call the main function. 24 | main() 25 | -------------------------------------------------------------------------------- /Chapter 06/write_names.py: -------------------------------------------------------------------------------- 1 | # This program gets three names from the user 2 | # and writes them to a file. 3 | 4 | def main(): 5 | # Get three names. 6 | print('Enter the names of three friends.') 7 | name1 = input('Friend #1: ') 8 | name2 = input('Friend #2: ') 9 | name3 = input('Friend #3: ') 10 | 11 | # Open a file named friends.txt. 12 | myfile = open('friends.txt', 'w') 13 | 14 | # Write the names to the file. 15 | myfile.write(name1 + '\n') 16 | myfile.write(name2 + '\n') 17 | myfile.write(name3 + '\n') 18 | 19 | # Close the file. 20 | myfile.close() 21 | print('The names were written to friends.txt.') 22 | 23 | # Call the main function. 24 | main() 25 | 26 | 27 | -------------------------------------------------------------------------------- /Chapter 04/retail_no_validation.py: -------------------------------------------------------------------------------- 1 | # This program calculates retail prices. 2 | 3 | mark_up = 2.5 # The markup percentage 4 | another = 'y' # Variable to control the loop. 5 | 6 | # Process one or more items. 7 | while another == 'y' or another == 'Y': 8 | # Get the item's wholesale cost. 9 | wholesale = float(input("Enter the item's " + \ 10 | "wholesale cost: ")) 11 | 12 | # Calculate the retail price. 13 | retail = wholesale * mark_up 14 | 15 | # Display the retail price. 16 | print('Retail price: $', format(retail, ',.2f')) 17 | 18 | 19 | # Do this again? 20 | another = input('Do you have another item? ' + \ 21 | '(Enter y for yes): ') 22 | 23 | -------------------------------------------------------------------------------- /Chapter 10/exercise5/program.py: -------------------------------------------------------------------------------- 1 | # 5. RetailItem Class 2 | # Write a class named RetailItem that holds data about an item in a retail store. 3 | # The class should store the following data in attributes: item description, 4 | # units in inventory, and price. 5 | # Once you have written the class, write a program that creates three RetailItem 6 | # objects and stores the following data in them: 7 | 8 | # Description Units in Inventory Price 9 | # Item #1 Jacket 12 59.95 10 | # Item #2 Designer Jeans 40 34.95 11 | # Item #3 Shirt 20 24.95 12 | 13 | import retailitem 14 | 15 | item1 = retailitem.RetailItem('Jacket',12,59.95) 16 | item2 = retailitem.RetailItem('Designer Jeans',40,34.95) 17 | item3 = retailitem.RetailItem('Shirt',20,24.95) -------------------------------------------------------------------------------- /Chapter 06/sales_report2.py: -------------------------------------------------------------------------------- 1 | # This program displays the total of the 2 | # amounts in the sales_data.txt file. 3 | 4 | def main(): 5 | # Initialize an accumulator. 6 | total = 0.0 7 | 8 | try: 9 | # Open the sales_data.txt file. 10 | infile = open('sales_data.txt', 'r') 11 | 12 | # Read the values from the file and 13 | # accumulate them. 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | # Close the file. 19 | infile.close() 20 | 21 | # Print the total. 22 | print(format(total, ',.2f')) 23 | except: 24 | print('An error occurred.') 25 | 26 | # Call the main function. 27 | main() 28 | -------------------------------------------------------------------------------- /Chapter 06/sales_report3.py: -------------------------------------------------------------------------------- 1 | # This program displays the total of the 2 | # amounts in the sales_data.txt file. 3 | 4 | def main(): 5 | # Initialize an accumulator. 6 | total = 0.0 7 | 8 | try: 9 | # Open the sales_data.txt file. 10 | infile = open('sales_data.txt', 'r') 11 | 12 | # Read the values from the file and 13 | # accumulate them. 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | # Close the file. 19 | infile.close() 20 | 21 | # Print the total. 22 | print(format(total, ',.2f')) 23 | except Exception as err: 24 | print(err) 25 | 26 | # Call the main function. 27 | main() 28 | -------------------------------------------------------------------------------- /Chapter 05/keyword_args.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates keyword arguments. 2 | 3 | def main(): 4 | # Show the amount of simple interest using 0.01 as 5 | # interest rate per period, 10 as the number of periods, 6 | # and $10,000 as the principal. 7 | show_interest(rate=0.01, periods=10, principal=10000.0) 8 | 9 | # The show_interest function displays the amount of 10 | # simple interest for a given principal, interest rate 11 | # per period, and number of periods. 12 | 13 | def show_interest(principal, rate, periods): 14 | interest = principal * rate * periods 15 | print('The simple interest will be $', \ 16 | format(interest, ',.2f'), \ 17 | sep='') 18 | 19 | # Call the main function. 20 | main() 21 | -------------------------------------------------------------------------------- /Chapter 06/sales_report4.py: -------------------------------------------------------------------------------- 1 | # This program displays the total of the 2 | # amounts in the sales_data.txt file. 3 | 4 | def main(): 5 | # Initialize an accumulator. 6 | total = 0.0 7 | 8 | try: 9 | # Open the sales_data.txt file. 10 | infile = open('sales_data.txt', 'r') 11 | 12 | # Read the values from the file and 13 | # accumulate them. 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | # Close the file. 19 | infile.close() 20 | except Exception as err: 21 | print(err) 22 | else: 23 | # Print the total. 24 | print(format(total, ',.2f')) 25 | 26 | # Call the main function. 27 | main() 28 | -------------------------------------------------------------------------------- /Chapter 07/total_function.py: -------------------------------------------------------------------------------- 1 | # This program uses a function to calculate the 2 | # total of the values in a list. 3 | 4 | def main(): 5 | # Create a list. 6 | numbers = [2, 4, 6, 8, 10] 7 | 8 | # Display the total of the list elements. 9 | print('The total is', get_total(numbers)) 10 | 11 | # The get_total function accepts a list as an 12 | # argument returns the total of the values in 13 | # the list. 14 | def get_total(value_list): 15 | # Create a variable to use as an accumulator. 16 | total = 0 17 | 18 | # Calculate the total of the list elements. 19 | for num in value_list: 20 | total += num 21 | 22 | # Return the total. 23 | return total 24 | 25 | # Call the main function. 26 | main() 27 | -------------------------------------------------------------------------------- /Chapter 10/cell_phone_test.py: -------------------------------------------------------------------------------- 1 | # This program tests the CellPhone class. 2 | 3 | import cellphone 4 | 5 | def main(): 6 | # Get the phone data. 7 | man = input('Enter the manufacturer: ') 8 | mod = input('Enter the model number: ') 9 | retail = float(input('Enter the retail price: ')) 10 | 11 | # Create an instance of the CellPhone class. 12 | phone = cellphone.CellPhone(man, mod, retail) 13 | 14 | # Display the data that was entered. 15 | print('Here is the data that you entered:') 16 | print('Manufacturer:', phone.get_manufact()) 17 | print('Model Number:', phone.get_model()) 18 | print('Retail Price: $', format(phone.get_retail_price(), ',.2f'), sep='') 19 | 20 | # Call the main function. 21 | main() 22 | -------------------------------------------------------------------------------- /Chapter 06/read_numbers.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how numbers that are 2 | # read from a file must be converted from strings 3 | # before they are used in a math operation. 4 | 5 | def main(): 6 | # Open a file for reading. 7 | infile = open('numbers.txt', 'r') 8 | 9 | # Read three numbers from the file. 10 | num1 = int(infile.readline()) 11 | num2 = int(infile.readline()) 12 | num3 = int(infile.readline()) 13 | 14 | # Close the file. 15 | infile.close() 16 | 17 | # Add the three numbers. 18 | total = num1 + num2 + num3 19 | 20 | # Display the numbers and their total. 21 | print('The numbers are:', num1, num2, num3) 22 | print('Their total is:', total) 23 | 24 | # Call the main function. 25 | main() 26 | -------------------------------------------------------------------------------- /Chapter 06/strip_newline.py: -------------------------------------------------------------------------------- 1 | # This program reads the contents of the 2 | # philosophers.txt file one line at a time. 3 | def main(): 4 | # Open a file named philosophers.txt. 5 | infile = open('philosophers.txt', 'r') 6 | 7 | # Read three lines from the file 8 | line1 = infile.readline() 9 | line2 = infile.readline() 10 | line3 = infile.readline() 11 | 12 | # Strip the \n from each string. 13 | line1 = line1.rstrip('\n') 14 | line2 = line2.rstrip('\n') 15 | line3 = line3.rstrip('\n') 16 | 17 | # Close the file. 18 | infile.close() 19 | 20 | # Print the data that was read into 21 | # memory. 22 | print(line1) 23 | print(line2) 24 | print(line3) 25 | 26 | # Call the main function. 27 | main() 28 | -------------------------------------------------------------------------------- /Chapter 06/write_numbers.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how numbers 2 | # must be converted to strings before they 3 | # are written to a text file. 4 | 5 | def main(): 6 | # Open a file for writing. 7 | outfile = open('numbers.txt', 'w') 8 | 9 | # Get three numbers from the user. 10 | num1 = int(input('Enter a number: ')) 11 | num2 = int(input('Enter another number: ')) 12 | num3 = int(input('Enter another number: ')) 13 | 14 | # Write the numbers to the file. 15 | outfile.write(str(num1) + '\n') 16 | outfile.write(str(num2) + '\n') 17 | outfile.write(str(num3) + '\n') 18 | 19 | # Close the file. 20 | outfile.close() 21 | print('Data written to numbers.txt') 22 | 23 | # Call the main function. 24 | main() 25 | -------------------------------------------------------------------------------- /Chapter 03/grader.py: -------------------------------------------------------------------------------- 1 | # This program gets a numeric test score from the 2 | # user and displays the corresponding letter grade. 3 | 4 | # Variables to represent the grade thresholds 5 | A_score = 90 6 | B_score = 80 7 | C_score = 70 8 | D_score = 60 9 | 10 | # Get a test score from the user. 11 | score = int(input('Enter your test score: ')) 12 | 13 | # Determine the grade. 14 | if score >= A_score: 15 | print('Your grade is A.') 16 | else: 17 | if score >= B_score: 18 | print('Your grade is B.') 19 | else: 20 | if score >= C_score: 21 | print('Your grade is C.') 22 | else: 23 | if score >= D_score: 24 | print('Your grade is D.') 25 | else: 26 | print('Your grade is F.') 27 | 28 | -------------------------------------------------------------------------------- /Chapter 04/commission.py: -------------------------------------------------------------------------------- 1 | # This program calculates sales commissions. 2 | 3 | # Create a variable to control the loop. 4 | keep_going = 'y' 5 | 6 | # Calculate a series of commissions. 7 | while keep_going == 'y': 8 | # Get a salesperson's sales and commission rate. 9 | sales = float(input('Enter the amount of sales: ')) 10 | comm_rate = float(input('Enter the commission rate: ')) 11 | 12 | # Calculate the commission. 13 | commission = sales * comm_rate 14 | 15 | # Display the commission. 16 | print('The commission is $', \ 17 | format(commission, ',.2f'), sep='') 18 | 19 | # See if the user wants to do another one. 20 | keep_going = input('Do you want to calculate another ' + \ 21 | 'commission (Enter y for yes): ') 22 | -------------------------------------------------------------------------------- /Chapter 07/sales_list.py: -------------------------------------------------------------------------------- 1 | # The NUM_DAYS constant holds the number of 2 | # days that we will gather sales data for. 3 | NUM_DAYS = 5 4 | 5 | def main(): 6 | # Create a list to hold the sales 7 | # for each day. 8 | sales = [0] * NUM_DAYS 9 | 10 | # Create a variable to hold an index. 11 | index = 0 12 | 13 | print('Enter the sales for each day.') 14 | 15 | # Get the sales for each day. 16 | while index < NUM_DAYS: 17 | print('Day #', index + 1, ': ', sep='', end='') 18 | sales[index] = float(input()) 19 | index += 1 20 | 21 | # Display the values entered. 22 | print('Here are the values you entered:') 23 | for value in sales: 24 | print(value) 25 | 26 | # Call the main function. 27 | main() 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter 13/hello_world2.py: -------------------------------------------------------------------------------- 1 | # This program displays two labels with text. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | def __init__(self): 7 | # Create the main window widget. 8 | self.main_window = tkinter.Tk() 9 | 10 | # Create two Label widget. 11 | self.label1 = tkinter.Label(self.main_window, \ 12 | text='Hello World!') 13 | self.label2 = tkinter.Label(self.main_window, \ 14 | text='This is my GUI program.') 15 | 16 | # Call both Label widgets' pack method. 17 | self.label1.pack() 18 | self.label2.pack() 19 | 20 | # Enter the tkinter main loop. 21 | tkinter.mainloop() 22 | 23 | # Create an instance of the MyGUI class. 24 | my_gui = MyGUI() 25 | 26 | -------------------------------------------------------------------------------- /Chapter 04/property_tax.py: -------------------------------------------------------------------------------- 1 | # This program displays property taxes. 2 | 3 | TAX_FACTOR = 0.0065 # Represents the tax factor. 4 | 5 | # Get the first lot number. 6 | print('Enter the property lot number') 7 | print('or enter 0 to end.') 8 | lot = int(input('Lot number: ')) 9 | 10 | # Continue processing as long as the user 11 | # does not enter lot number 0. 12 | while lot != 0: 13 | # Get the property value. 14 | value = float(input('Enter the property value: ')) 15 | 16 | # Calculate the property's tax. 17 | tax = value * TAX_FACTOR 18 | 19 | # Display the tax. 20 | print('Property tax: $', format(tax, ',.2f'), sep='') 21 | 22 | # Get the next lot number. 23 | print('Enter the next lot number or') 24 | print('enter 0 to end.') 25 | lot = int(input('Lot number: ')) 26 | -------------------------------------------------------------------------------- /Chapter 07/remove_item.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how to use the remove 2 | # method to remove an item from a list. 3 | 4 | def main(): 5 | # Create a list with some items. 6 | food = ['Pizza', 'Burgers', 'Chips'] 7 | 8 | # Display the list. 9 | print('Here are the items in the food list:') 10 | print(food) 11 | 12 | # Get the item to change. 13 | item = input('Which item should I remove? ') 14 | 15 | try: 16 | # Remove the item. 17 | food.remove(item) 18 | 19 | # Display the list. 20 | print('Here is the revised list:') 21 | print(food) 22 | 23 | except ValueError: 24 | print('That item was not found in the list.') 25 | 26 | # Call the main function. 27 | main() 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter 03/test_average.py: -------------------------------------------------------------------------------- 1 | # This program gets three test scores and displays 2 | # their average. It congratulates the user if the 3 | # average is a high score. 4 | 5 | # The high score variable holds the value that is 6 | # considered a high score. 7 | high_score = 95 8 | 9 | # Get the three test scores. 10 | test1 = int(input('Enter the score for test 1: ')) 11 | test2 = int(input('Enter the score for test 2: ')) 12 | test3 = int(input('Enter the score for test 3: ')) 13 | 14 | # Calculate the average test score. 15 | average = (test1 + test2 + test3) / 3 16 | 17 | # Print the average. 18 | print('The average score is', average) 19 | 20 | # If the average is a high score, 21 | # congratulate the user. 22 | if average >= high_score: 23 | print('Congratulations!') 24 | print('That is a great average!') 25 | 26 | -------------------------------------------------------------------------------- /Chapter 12/range_sum.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the range_sum function. 2 | 3 | def main(): 4 | # Create a list of numbers. 5 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] 6 | 7 | # Get the sum of the items at indexes 2 8 | # through 5. 9 | my_sum = range_sum(numbers, 2, 5) 10 | 11 | # Display the sum. 12 | print('The sum of items 2 through 5 is', my_sum) 13 | 14 | # The range_sum function returns the sum of a specified 15 | # range of items in num_list. The start parameter 16 | # specifies the index of the starting item. The end 17 | # parameter specifies the index of the ending item. 18 | def range_sum(num_list, start, end): 19 | if start > end: 20 | return 0 21 | else: 22 | return num_list[start] + range_sum(num_list, start + 1, end) 23 | 24 | # Call the main function. 25 | main() 26 | -------------------------------------------------------------------------------- /Chapter 06/save_running_times.py: -------------------------------------------------------------------------------- 1 | # This program saves a sequence of video running times 2 | # to the video_times.txt file. 3 | 4 | def main(): 5 | # Get the number of videos in the project. 6 | num_videos = int(input('How many videos are in the project? ')) 7 | 8 | # Open the file to hold the running times. 9 | video_file = open('video_times.txt', 'w') 10 | 11 | # Get each video's running time and write 12 | # it to the file. 13 | print('Enter the running times for each video.') 14 | for count in range(1, num_videos + 1): 15 | run_time = float(input('Video #' + str(count) + ': ')) 16 | video_file.write(str(run_time) + '\n') 17 | 18 | # Close the file. 19 | video_file.close() 20 | print('The times have been saved to video_times.txt.') 21 | 22 | # Call the main function. 23 | main() 24 | -------------------------------------------------------------------------------- /Chapter 10/coin.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # The Coin class simulates a coin that can 4 | # be flipped. 5 | 6 | class Coin: 7 | 8 | # The __init__ method initializes the 9 | # __sideup data attribute with 'Heads'. 10 | 11 | def __init__(self): 12 | self.__sideup = 'Heads' 13 | 14 | # The toss method generates a random number 15 | # in the range of 0 through 1. If the number 16 | # is 0, then sideup is set to 'Heads'. 17 | # Otherwise, sideup is set to 'Tails'. 18 | 19 | def toss(self): 20 | if random.randint(0, 1) == 0: 21 | self.__sideup = 'Heads' 22 | else: 23 | self.__sideup = 'Tails' 24 | 25 | # The get_sideup method returns the value 26 | # referenced by sideup. 27 | 28 | def get_sideup(self): 29 | return self.__sideup 30 | -------------------------------------------------------------------------------- /Chapter 10/servicequote.py: -------------------------------------------------------------------------------- 1 | # Constant for the sales tax rate 2 | TAX_RATE = 0.05 3 | 4 | # ServiceQuote class 5 | class ServiceQuote: 6 | def __init__(self, pcharge, lcharge): 7 | self.__parts_charges = pcharge 8 | self.__labor_charges = lcharge 9 | 10 | def set_parts_charges(self, pcharge): 11 | self.__parts_charges = pcharge 12 | 13 | def set_labor_charges(self, lcharge): 14 | self.__labor_charges = lcharge 15 | 16 | def get_parts_charges(self): 17 | return self.__parts_charges 18 | 19 | def get_labor_charges(self): 20 | return self.__labor_charges 21 | 22 | def get_sales_tax(self): 23 | return __parts_charges * TAX_RATE 24 | 25 | def get_total_charges(self): 26 | return __parts_charges + __labor_charges + \ 27 | (__parts_charges * TAX_RATE) 28 | -------------------------------------------------------------------------------- /Chapter 05/cups_to_ounces.py: -------------------------------------------------------------------------------- 1 | # This program converts cups to fluid ounces. 2 | 3 | def main(): 4 | # display the intro screen. 5 | intro() 6 | # Get the number of cups. 7 | cups_needed = int(input('Enter the number of cups: ')) 8 | # Convert the cups to ounces. 9 | cups_to_ounces(cups_needed) 10 | 11 | # The intro function displays an introductory screen. 12 | def intro(): 13 | print('This program converts measurements') 14 | print('in cups to fluid ounces. For your') 15 | print('reference the formula is:') 16 | print(' 1 cup = 8 fluid ounces') 17 | print() 18 | 19 | # The cups_to_ounces function accepts a number of 20 | # cups and displays the equivalent number of ounces. 21 | def cups_to_ounces(cups): 22 | ounces = cups * 8 23 | print('That converts to', ounces, 'ounces.') 24 | 25 | # Call the main function. 26 | main() 27 | -------------------------------------------------------------------------------- /Chapter 06/read_sales.py: -------------------------------------------------------------------------------- 1 | # This program reads all of the values in 2 | # the sales.txt file. 3 | 4 | def main(): 5 | # Open the sales.txt file for reading. 6 | sales_file = open('sales.txt', 'r') 7 | 8 | # Read the first line from the file, but 9 | # don't convert to a number yet. We still 10 | # need to test for an empty string. 11 | line = sales_file.readline() 12 | 13 | # As long as an empty string is not returned 14 | # from readline, continue processing. 15 | while line != '': 16 | # Convert line to a float. 17 | amount = float(line) 18 | 19 | # Format and display the amount. 20 | print(format(amount, '.2f')) 21 | 22 | # Read the next line. 23 | line = sales_file.readline() 24 | 25 | # Close the file. 26 | sales_file.close() 27 | 28 | # Call the main function. 29 | main() 30 | -------------------------------------------------------------------------------- /Chapter 06/show_coffee_records.py: -------------------------------------------------------------------------------- 1 | # This program displays the records in the 2 | # coffee.txt file. 3 | 4 | def main(): 5 | # Open the coffee.txt file. 6 | coffee_file = open('coffee.txt', 'r') 7 | 8 | # Read the first record's description field. 9 | descr = coffee_file.readline() 10 | 11 | # Read the rest of the file. 12 | while descr != '': 13 | # Read the quantity field. 14 | qty = float(coffee_file.readline()) 15 | 16 | # Strip the \n from the description. 17 | descr = descr.rstrip('\n') 18 | 19 | # Display the record. 20 | print('Description:', descr) 21 | print('Quantity:', qty) 22 | 23 | # Read the next description. 24 | descr = coffee_file.readline() 25 | 26 | # Close the file. 27 | coffee_file.close() 28 | 29 | # Call the main function. 30 | main() 31 | 32 | 33 | -------------------------------------------------------------------------------- /Chapter 13/hello_world3.py: -------------------------------------------------------------------------------- 1 | # This program uses the side='left' argument with 2 | # the pack method to change the layout of the widgets. 3 | 4 | import tkinter 5 | 6 | class MyGUI: 7 | def __init__(self): 8 | # Create the main window widget. 9 | self.main_window = tkinter.Tk() 10 | 11 | # Create two Label widget. 12 | self.label1 = tkinter.Label(self.main_window, \ 13 | text='Hello World!') 14 | self.label2 = tkinter.Label(self.main_window, \ 15 | text='This is my GUI program.') 16 | 17 | # Call both Label widgets' pack method. 18 | self.label1.pack(side='left') 19 | self.label2.pack(side='left') 20 | 21 | # Enter the tkinter main loop. 22 | tkinter.mainloop() 23 | 24 | # Create an instance of the MyGUI class. 25 | my_gui = MyGUI() 26 | 27 | -------------------------------------------------------------------------------- /Chapter 04/temperature.py: -------------------------------------------------------------------------------- 1 | # This program assists a technician in the process 2 | # of checking a substance's temperature. 3 | 4 | # Create a variable to represent the maximum 5 | # temperature. 6 | max_temp = 102.5 7 | 8 | # Get the substance's temperature. 9 | temperature = float(input("Enter the substance's Celsius temperature: ")) 10 | 11 | # As long as necessary, instruct the user to 12 | # adjust the thermostat. 13 | while temperature > max_temp: 14 | print('The temperature is too high.') 15 | print('Turn the thermostat down and wait') 16 | print('5 minutes. Then take the temperature') 17 | print('again and enter it.') 18 | temperature = float(input('Enter the new Celsius temperature: ')) 19 | 20 | # Remind the user to check the temperature again 21 | # in 15 minutes. 22 | print('The temperature is acceptable.') 23 | print('Check it again in 15 minutes.') 24 | 25 | 26 | -------------------------------------------------------------------------------- /Chapter 10/exercise3/information.py: -------------------------------------------------------------------------------- 1 | class Information: 2 | def __init__(self,name,address,age,phone_number): 3 | self.__name = name 4 | self.__address = address 5 | self.__age = age 6 | self.__phone_number = phone_number 7 | 8 | def set_name(self,name): 9 | self.__name = name 10 | 11 | def set_address(self,address): 12 | self.__address = address 13 | 14 | def set_age(self,age): 15 | self.__age = age 16 | 17 | def set_phone_number(self,phone_number): 18 | self.__phone_number = phone_number 19 | 20 | def get_name(self): 21 | return self.__name 22 | 23 | def get_address(self): 24 | return self.__address 25 | 26 | def get_age(self): 27 | return self.__age 28 | 29 | def get_phone_number(self): 30 | return self.__phone_number -------------------------------------------------------------------------------- /Chapter 11/polymorphism_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates polymorphism. 2 | 3 | import animals 4 | 5 | def main(): 6 | # Create a Mammal object, a Dog object, and 7 | # a Cat object. 8 | mammal = animals.Mammal('regular animal') 9 | dog = animals.Dog() 10 | cat = animals.Cat() 11 | 12 | # Display information about each one. 13 | print('Here are some animals and') 14 | print('the sounds they make.') 15 | print('--------------------------') 16 | show_mammal_info(mammal) 17 | print() 18 | show_mammal_info(dog) 19 | print() 20 | show_mammal_info(cat) 21 | 22 | # The show_mammal_info function accepts an object 23 | # as an argument, and calls its show_species 24 | # and make_sound methods. 25 | 26 | def show_mammal_info(creature): 27 | creature.show_species() 28 | creature.make_sound() 29 | 30 | # Call the main function. 31 | main() 32 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_5/exercise9_5.py: -------------------------------------------------------------------------------- 1 | # This program generates 100 random numbers from 1 to 10. 2 | # Then displays the frequency of the numbers. 3 | 4 | import random 5 | 6 | def generateNumbers(): 7 | # Create a dictionary 8 | numberdict = dict() 9 | # Create random numbers and save them to the dictionary. 10 | for count in range(100): 11 | number = random.randint(1,10) 12 | # If not already in dictonary, add it. 13 | if number not in numberdict: 14 | numberdict[number] = 1 15 | # If already in dictionary , raise the value by 1 16 | else: 17 | numberdict[number] += 1 18 | return numberdict 19 | 20 | def main(): 21 | numbers = generateNumbers() 22 | # print the results. 23 | for number in range(1,11): 24 | print(number,'appeared:',numbers[number],'times.') 25 | 26 | # Call the main function 27 | main() -------------------------------------------------------------------------------- /Chapter 07/list_append.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how the append 2 | # method can be used to add items to a list. 3 | 4 | def main(): 5 | # First, create an empty list. 6 | name_list = [] 7 | 8 | # Create a variable to control the loop. 9 | again = 'Y' 10 | 11 | # Add some names to the list. 12 | while again.upper() == 'Y': 13 | # Get a name from the user. 14 | name = input('Enter a name: ') 15 | 16 | # Append the name to the list. 17 | name_list.append(name) 18 | 19 | # Add another one? 20 | print('Do you want to add another name?') 21 | again = input('y = yes, anything else = no: ') 22 | print() 23 | 24 | # Display the names that were entered. 25 | print('Here are the names you entered.') 26 | 27 | for name in name_list: 28 | print(name) 29 | 30 | # Call the main function. 31 | main() 32 | -------------------------------------------------------------------------------- /Chapter 08/string_test.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates several string testing methods. 2 | 3 | def main(): 4 | # Get a string from the user. 5 | user_string = input('Enter a string: ') 6 | 7 | print('This is what I found about that string:') 8 | 9 | # Test the string. 10 | if user_string.isalnum(): 11 | print('The string is alphanumeric.') 12 | if user_string.isdigit(): 13 | print('The string contains only digits.') 14 | if user_string.isalpha(): 15 | print('The string contains only alphabetic characters.') 16 | if user_string.isspace(): 17 | print('The string contains only whitespace characters.') 18 | if user_string.islower(): 19 | print('The letters in the string are all lowercase.') 20 | if user_string.isupper(): 21 | print('The letters in the string are all uppercase.') 22 | 23 | # Call the main function. 24 | main(); 25 | -------------------------------------------------------------------------------- /Chapter 10/bankaccount.py: -------------------------------------------------------------------------------- 1 | # The BankAccount class simulates a bank account. 2 | 3 | class BankAccount: 4 | 5 | # The __init__ method accepts an argument for 6 | # the account's balance. It is assigned to 7 | # the __balance attribute. 8 | 9 | def __init__(self, bal): 10 | self.__balance = bal 11 | 12 | # The deposit method makes a deposit into the 13 | # account. 14 | 15 | def deposit(self, amount): 16 | self.__balance += amount 17 | 18 | # The withdraw method withdraws an amount 19 | # from the account. 20 | 21 | def withdraw(self, amount): 22 | if self.__balance >= amount: 23 | self.__balance -= amount 24 | else: 25 | print('Error: Insufficient funds') 26 | 27 | # The get_balance method returns the 28 | # account balance. 29 | 30 | def get_balance(self): 31 | return self.__balance 32 | 33 | -------------------------------------------------------------------------------- /Chapter 06/write_sales.py: -------------------------------------------------------------------------------- 1 | # This program prompts the user for sales amounts 2 | # and writes those amounts to the sales.txt file. 3 | 4 | def main(): 5 | # Get the number of days. 6 | num_days = int(input('For how many days do ' + \ 7 | 'you have sales? ')) 8 | 9 | # Open a new file named sales.txt. 10 | sales_file = open('sales.txt', 'w') 11 | 12 | # Get the amount of sales for each day and write 13 | # it to the file. 14 | for count in range(1, num_days + 1): 15 | # Get the sales for a day. 16 | sales = float(input('Enter the sales for day #' + \ 17 | str(count) + ': ')) 18 | 19 | # Write the sales amount to the file. 20 | sales_file.write(str(sales) + '\n') 21 | 22 | # Close the file. 23 | sales_file.close() 24 | print('Data written to sales.txt.') 25 | 26 | # Call the main function. 27 | main() 28 | -------------------------------------------------------------------------------- /Chapter 06/sales_report1.py: -------------------------------------------------------------------------------- 1 | # This program displays the total of the 2 | # amounts in the sales_data.txt file. 3 | 4 | def main(): 5 | # Initialize an accumulator. 6 | total = 0.0 7 | 8 | try: 9 | # Open the sales_data.txt file. 10 | infile = open('sales_data.txt', 'r') 11 | 12 | # Read the values from the file and 13 | # accumulate them. 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | # Close the file. 19 | infile.close() 20 | 21 | # Print the total. 22 | print(format(total, ',.2f')) 23 | 24 | except IOError: 25 | print('An error occured trying to read the file.') 26 | 27 | except ValueError: 28 | print('Non-numeric data found in the file.') 29 | 30 | except: 31 | print('An error occured.') 32 | 33 | # Call the main function. 34 | main() 35 | -------------------------------------------------------------------------------- /Chapter 10/account_test2.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the BankAccount class 2 | # with the __str__ method added to it. 3 | 4 | import bankaccount2 5 | 6 | def main(): 7 | # Get the starting balance. 8 | start_bal = float(input('Enter your starting balance: ')) 9 | 10 | # Create a BankAccount object. 11 | savings = bankaccount2.BankAccount(start_bal) 12 | 13 | # Deposit the user's paycheck. 14 | pay = float(input('How much were you paid this week? ')) 15 | print('I will deposit that into your account.') 16 | savings.deposit(pay) 17 | 18 | # Display the balance. 19 | print(savings) 20 | 21 | # Get the amount to withdraw. 22 | cash = float(input('How much would you like to withdraw? ')) 23 | print('I will withdraw that from your account.') 24 | savings.withdraw(cash) 25 | 26 | # Display the balance. 27 | print(savings) 28 | 29 | # Call the main function. 30 | main() 31 | -------------------------------------------------------------------------------- /Chapter 10/algo1.py: -------------------------------------------------------------------------------- 1 | # Write a definition for a class Book. The Book class has data attributes 2 | # for a title, an author name and the number of pages. The class also has 3 | # the following methods: 4 | 5 | # a. An _ _init_ _ method for the class. The method should accept 6 | # arguments for each of the data attributes. 7 | 8 | # b. A special _ _len_ _ method to return the number of pages in the book. 9 | 10 | # c. An _ _str_ _ method that returns a string showing the state of the 11 | # object 12 | 13 | class Book: 14 | def __init__(self,title,author,pages): 15 | self.__title = title 16 | self.__author = author 17 | self.__pages = pages 18 | 19 | def __len__(self): 20 | return int(self.__pages) 21 | 22 | def __str__(self): 23 | return "Title: " + self.__title + \ 24 | "\nAuthor: " + self.__author + \ 25 | "\nPages: " + self.__pages 26 | -------------------------------------------------------------------------------- /Chapter 03/loan_qualifier.py: -------------------------------------------------------------------------------- 1 | # This program determines whether a bank customer 2 | # qualifies for a loan. 3 | 4 | min_salary = 30000.0 # The minimum annual salary 5 | min_years = 2 # The minimum years on the job 6 | 7 | # Get the customer's annual salary. 8 | salary = float(input('Enter your annual salary: ')) 9 | 10 | # Get the number of years on the current job. 11 | years_on_job = int(input('Enter the number of ' + 12 | 'years employed: ')) 13 | 14 | # Determine whether the customer qualifies. 15 | if salary >= min_salary: 16 | if years_on_job >= min_years: 17 | print('You qualify for the loan.') 18 | else: 19 | print('You must have been employed', \ 20 | 'for at least', min_years, \ 21 | 'years to qualify.') 22 | else: 23 | print('You must earn at least $', \ 24 | format(min_salary, ',.2f'), \ 25 | ' per year to qualify.', sep='') 26 | -------------------------------------------------------------------------------- /Chapter 10/exercise4/program.py: -------------------------------------------------------------------------------- 1 | import employee 2 | 3 | employee1 = employee.Employee('Susan Meyers','47899','Accounting','Vice President') 4 | employee2 = employee.Employee('Mark Jones', '39119','IT','Programmer') 5 | employee3 = employee.Employee('Joy Rogers', '81774','Manufacturing','Engineer') 6 | 7 | print('Name\t\tID Number\t\tDepartment\t\tJob Title') 8 | print('-------------------------------------------------------') 9 | print(employee1.get_name() + "\t\t" + employee1.get_id_number()+ "\t\t" + \ 10 | employee1.get_department()+ "\t\t" + employee1.get_job_title()) 11 | print(employee2.get_name() + "\t\t" + employee2.get_id_number()+ "\t\t" + \ 12 | employee2.get_department()+ "\t\t" + employee2.get_job_title()) 13 | print(employee3.get_name() + "\t\t" + employee3.get_id_number()+ "\t\t" + \ 14 | employee3.get_department()+ "\t\t" + employee3.get_job_title()) 15 | print('-------------------------------------------------------') -------------------------------------------------------------------------------- /Chapter 12/towers_of_hanoi.py: -------------------------------------------------------------------------------- 1 | # This program simulates the Towers of Hanoi game. 2 | 3 | def main(): 4 | # Set up some initial values. 5 | num_discs = 3 6 | from_peg = 1 7 | to_peg = 3 8 | temp_peg =2 9 | 10 | # Play the game. 11 | move_discs(num_discs, from_peg, to_peg, temp_peg) 12 | print('All the pegs are moved!') 13 | 14 | # The moveDiscs function displays a disc move in 15 | # the Towers of Hanoi game. 16 | # The parameters are: 17 | # num: The number of discs to move. 18 | # from_peg: The peg to move from. 19 | # to_peg: The peg to move to. 20 | # temp_peg: The temporary peg. 21 | def move_discs(num, from_peg, to_peg, temp_peg): 22 | if num > 0: 23 | move_discs(num - 1, from_peg, temp_peg, to_peg) 24 | print('Move a disc from peg', from_peg, 'to peg', to_peg) 25 | move_discs(num - 1, temp_peg, to_peg, from_peg) 26 | 27 | # Call the main function. 28 | main() 29 | -------------------------------------------------------------------------------- /Chapter 07/barista_pay.py: -------------------------------------------------------------------------------- 1 | # This program calculates the gross pay for 2 | # each of Megan's baristas. 3 | 4 | # NUM_EMPLOYEES is used as a constant for the 5 | # size of the list. 6 | NUM_EMPLOYEES = 6 7 | 8 | def main(): 9 | # Create a list to hold employee hours. 10 | hours = [0] * NUM_EMPLOYEES 11 | 12 | # Get each employee's hours worked. 13 | for index in range(NUM_EMPLOYEES): 14 | print('Enter the hours worked by employee ', \ 15 | index + 1, ': ', sep='', end='') 16 | hours[index] = float(input()) 17 | 18 | # Get the hourly pay rate. 19 | pay_rate = float(input('Enter the hourly pay rate: ')) 20 | 21 | # Display each employee's gross pay. 22 | for index in range(NUM_EMPLOYEES): 23 | gross_pay = hours[index] * pay_rate 24 | print('Gross pay for employee ', index + 1, ': $', \ 25 | format(gross_pay, ',.2f'), sep='') 26 | 27 | # Call the main function. 28 | main() 29 | 30 | -------------------------------------------------------------------------------- /Chapter 04/retail_with_validation.py: -------------------------------------------------------------------------------- 1 | # This program calculates retail prices. 2 | 3 | mark_up = 2.5 # The markup percentage 4 | another = 'y' # Variable to control the loop. 5 | 6 | # Process one or more items. 7 | while another == 'y' or another == 'Y': 8 | # Get the item's wholesale cost. 9 | wholesale = float(input("Enter the item's " + \ 10 | "wholesale cost: ")) 11 | 12 | # Validate the wholesale cost. 13 | while wholesale < 0: 14 | print('ERROR: the cost cannot be negative.') 15 | wholesale = float(input('Enter the correct ' + \ 16 | 'wholesale cost:')) 17 | 18 | # Calculate the retail price. 19 | retail = wholesale * mark_up 20 | 21 | # Display the retail price. 22 | print('Retail price: $', format(retail, ',.2f')) 23 | 24 | 25 | # Do this again? 26 | another = input('Do you have another item? ' + \ 27 | '(Enter y for yes): ') 28 | -------------------------------------------------------------------------------- /Chapter 10/coin_demo5.py: -------------------------------------------------------------------------------- 1 | # This program imports the simulation module and 2 | # creates three instances of the Coin class. 3 | 4 | import coin 5 | 6 | def main(): 7 | # Create three objects from the Coin class. 8 | coin1 = coin.Coin() 9 | coin2 = coin.Coin() 10 | coin3 = coin.Coin() 11 | 12 | # Display the side of each coin that is facing up. 13 | print('I have three coins with these sides up:') 14 | print(coin1.get_sideup()) 15 | print(coin2.get_sideup()) 16 | print(coin3.get_sideup()) 17 | print() 18 | 19 | # Toss the coin. 20 | print('I am tossing all three coins...') 21 | print() 22 | coin1.toss() 23 | coin2.toss() 24 | coin3.toss() 25 | 26 | # Display the side of each coin that is facing up. 27 | print('Now here are the sides that are up:') 28 | print(coin1.get_sideup()) 29 | print(coin2.get_sideup()) 30 | print(coin3.get_sideup()) 31 | print() 32 | 33 | # Call the main function. 34 | main() 35 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_4/test.txt: -------------------------------------------------------------------------------- 1 | Write a program that generates 100 random numbers between 1 and 10. The program 2 | should store the frequency of each number generated in a dictionary with the number as 3 | the key and the amount of times it has occurred as the value. For example, if the program 4 | generates the number 6 a total of 11 times, the dictionary will contain a key of 6 with an 5 | associated value of 11. Once all of the numbers have been generated, display information 6 | about the frequency of each number. 7 | 6. File Analysis 8 | Write a program that reads the contents of two text files and compares them in the fol- 9 | lowing ways: 10 | It should display a list of all the unique words contained in both files. 11 | It should display a list of the words that appear in both files. 12 | It should display a list of the words that appear in the first file but not the second. 13 | It should display a list of the words that appear in the second file but not the first. 14 | It should display a list of the words that appear in either the first -------------------------------------------------------------------------------- /Chapter 03/auto_repair_payroll.py: -------------------------------------------------------------------------------- 1 | # Variables to represent the base hours and 2 | # the overtime multiplier. 3 | base_hours = 40 # Base hours per week 4 | ot_multiplier = 1.5 # Overtime multiplier 5 | 6 | # Get the hours worked and the hourly pay rate. 7 | hours = float(input('Enter the number of hours worked: ')) 8 | pay_rate = float(input('Enter the hourly pay rate: ')) 9 | 10 | # Calculate and display the gross pay. 11 | if hours > base_hours: 12 | # Calculate the gross pay with overtime. 13 | # First, get the number of overtime hours worked. 14 | overtime_hours = hours - base_hours 15 | 16 | # Calculate the amount of overtime pay. 17 | overtime_pay = overtime_hours * pay_rate * ot_multiplier 18 | 19 | # Calculate the gross pay. 20 | gross_pay = base_hours * pay_rate + overtime_pay 21 | else: 22 | # Calculate the gross pay without overtime. 23 | gross_pay = hours * pay_rate 24 | 25 | # Display the gross pay. 26 | print('The gross pay is $', format(gross_pay, ',.2f'), sep='') 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /Chapter 07/index_list.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates how to get the 2 | # index of an item in a list and then replace 3 | # that item with a new item. 4 | 5 | def main(): 6 | # Create a list with some items. 7 | food = ['Pizza', 'Burgers', 'Chips'] 8 | 9 | # Display the list. 10 | print('Here are the items in the food list:') 11 | print(food) 12 | 13 | # Get the item to change. 14 | item = input('Which item should I change? ') 15 | 16 | try: 17 | # Get the item's index in the list. 18 | item_index = food.index(item) 19 | 20 | # Get the value to replace it with. 21 | new_item = input('Enter the new value: ') 22 | 23 | # Replace the old item with the new item. 24 | food[item_index] = new_item 25 | 26 | # Display the list. 27 | print('Here is the revised list:') 28 | print(food) 29 | except ValueError: 30 | print('That item was not found in the list.') 31 | 32 | # Call the main function. 33 | main() 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Chapter 05/sale_price.py: -------------------------------------------------------------------------------- 1 | # This program calculates a retail item's 2 | # sale price. 3 | 4 | # DISCOUNT_PERCENTAGE is used as a global 5 | # constant for the discount percentage. 6 | DISCOUNT_PERCENTAGE = 0.20 7 | 8 | # The main function. 9 | def main(): 10 | # Get the item's regular price. 11 | reg_price = get_regular_price() 12 | 13 | # Calculate the sale price. 14 | sale_price = reg_price - discount(reg_price) 15 | 16 | # Display the sale price. 17 | print('The sale price is $', format(sale_price, ',.2f'), sep='') 18 | 19 | # The get_regular_price function prompts the 20 | # user to enter an item's regular price and it 21 | # returns that value. 22 | def get_regular_price(): 23 | price = float(input("Enter the item's regular price: ")) 24 | return price 25 | 26 | # The discount function accepts an item's price 27 | # as an argument and returns the amount of the 28 | # discount, specified by DISCOUNT_PERCENTAGE. 29 | def discount(price): 30 | return price * DISCOUNT_PERCENTAGE 31 | 32 | # Call the main function. 33 | main() 34 | 35 | -------------------------------------------------------------------------------- /Chapter 11/polymorphism_demo2.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates polymorphism. 2 | 3 | import animals 4 | 5 | def main(): 6 | # Create an Mammal object, a Dog object, and 7 | # a Cat object. 8 | mammal = animals.Mammal('regular animal') 9 | dog = animals.Dog() 10 | cat = animals.Cat() 11 | 12 | # Display information about each one. 13 | print('Here are some animals and') 14 | print('the sounds they make.') 15 | print('--------------------------') 16 | show_mammal_info(mammal) 17 | print() 18 | show_mammal_info(dog) 19 | print() 20 | show_mammal_info(cat) 21 | print() 22 | show_mammal_info('I am a string') 23 | 24 | # The show_mammal_info function accepts an object 25 | # as an argument, and calls its show_species 26 | # and make_sound methods. 27 | 28 | def show_mammal_info(creature): 29 | if isinstance(creature, animals.Mammal): 30 | creature.show_species() 31 | creature.make_sound() 32 | else: 33 | print('That is not a Mammal!') 34 | 35 | # Call the main function. 36 | main() 37 | -------------------------------------------------------------------------------- /Chapter 10/account_test.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates the BankAccount class. 2 | 3 | import bankaccount 4 | 5 | def main(): 6 | # Get the starting balance. 7 | start_bal = float(input('Enter your starting balance: ')) 8 | 9 | # Create a BankAccount object. 10 | savings = account.BankAccount(start_bal) 11 | 12 | # Deposit the user's paycheck. 13 | pay = float(input('How much were you paid this week? ')) 14 | print('I will deposit that into your account.') 15 | savings.deposit(pay) 16 | 17 | # Display the balance. 18 | print('Your account balance is $', \ 19 | format(savings.get_balance(), ',.2f'), 20 | sep='') 21 | 22 | # Get the amount to withdraw. 23 | cash = float(input('How much would you like to withdraw? ')) 24 | print('I will withdraw that from your account.') 25 | savings.withdraw(cash) 26 | 27 | # Display the balance. 28 | print('Your account balance is $', \ 29 | format(savings.get_balance(), ',.2f'), 30 | sep='') 31 | 32 | # Call the main function. 33 | main() 34 | -------------------------------------------------------------------------------- /Chapter 05/retirement.py: -------------------------------------------------------------------------------- 1 | # The following is used as a global constant to represent 2 | # the contribution rate. 3 | CONTRIBUTION_RATE = 0.05 4 | 5 | def main(): 6 | gross_pay = float(input('Enter the gross pay: ')) 7 | bonus = float(input('Enter the amount of bonuses: ')) 8 | show_pay_contrib(gross_pay) 9 | show_bonus_contrib(bonus) 10 | 11 | # The show_pay_contrib function accepts the gross 12 | # pay as an argument and displays the retirement 13 | # contribution for that amount of pay. 14 | def show_pay_contrib(gross): 15 | contrib = gross * CONTRIBUTION_RATE 16 | print('Contribution for gross pay: $', \ 17 | format(contrib, ',.2f'), \ 18 | sep='') 19 | 20 | # The show_bonus_contrib function accepts the 21 | # bonus amount as an argument and displays the 22 | # retirement contribution for that amount of pay. 23 | def show_bonus_contrib(bonus): 24 | contrib = bonus * CONTRIBUTION_RATE 25 | print('Contribution for bonuses: $', \ 26 | format(contrib, ',.2f'), \ 27 | sep='') 28 | 29 | # Call the main function. 30 | main() 31 | -------------------------------------------------------------------------------- /Chapter 10/pickle_cellphone.py: -------------------------------------------------------------------------------- 1 | # This program pickles CellPhone objects. 2 | import pickle 3 | import cellphone 4 | 5 | # Constant for the filename. 6 | FILENAME = 'cellphones.dat' 7 | 8 | def main(): 9 | # Initialize a variable to control the loop. 10 | again = 'y' 11 | 12 | # Open a file. 13 | output_file = open(FILENAME, 'wb') 14 | 15 | # Get data from the user. 16 | while again.lower() == 'y': 17 | # Get cell phone data. 18 | man = input('Enter the manufacturer: ') 19 | mod = input('Enter the model number: ') 20 | retail = float(input('Enter the retail price: ')) 21 | 22 | # Create a CellPhone object. 23 | phone = cellphone.CellPhone(man, mod, retail) 24 | 25 | # Pickle the object and write it to the file. 26 | pickle.dump(phone, output_file) 27 | 28 | # Get more cell phone data? 29 | again = input('Enter more phone data? (y/n): ') 30 | 31 | # Close the file. 32 | output_file.close() 33 | print('The data was written to', FILENAME) 34 | 35 | # Call the main function. 36 | main() 37 | -------------------------------------------------------------------------------- /Chapter 10/bankaccount2.py: -------------------------------------------------------------------------------- 1 | # The BankAccount class simulates a bank account. 2 | 3 | class BankAccount: 4 | 5 | # The __init__ method accepts an argument for 6 | # the account's balance. It is assigned to 7 | # the __balance attribute. 8 | 9 | def __init__(self, bal): 10 | self.__balance = bal 11 | 12 | # The deposit method makes a deposit into the 13 | # account. 14 | 15 | def deposit(self, amount): 16 | self.__balance += amount 17 | 18 | # The withdraw method withdraws an amount 19 | # from the account. 20 | 21 | def withdraw(self, amount): 22 | if self.__balance >= amount: 23 | self.__balance -= amount 24 | else: 25 | print('Error: Insufficient funds') 26 | 27 | # The get_balance method returns the 28 | # account balance. 29 | 30 | def get_balance(self): 31 | return self.__balance 32 | 33 | # The __str__ method returns a string 34 | # indicating the object's state. 35 | 36 | def __str__(self): 37 | return 'The balance is $' + format(self.__balance, ',.2f') 38 | -------------------------------------------------------------------------------- /Chapter 06/add_coffee_record.py: -------------------------------------------------------------------------------- 1 | # This program adds coffee inventory records to 2 | # the coffee.txt file. 3 | 4 | def main(): 5 | # Create a variable to control the loop. 6 | another = 'y' 7 | 8 | # Open the coffee.txt file in append mode. 9 | coffee_file = open('coffee.txt', 'a') 10 | 11 | # Add records to the file. 12 | while another == 'y' or another == 'Y': 13 | # Get the coffee record data. 14 | print('Enter the following coffee data:') 15 | descr = input('Description: ') 16 | qty = int(input('Quantity (in pounds): ')) 17 | 18 | # Append the data to the file. 19 | coffee_file.write(descr + '\n') 20 | coffee_file.write(str(qty) + '\n') 21 | 22 | # Determine whether the user wants to add 23 | # another record to the file. 24 | print('Do you want to add another record?') 25 | another = input('Y = yes, anything else = no: ') 26 | 27 | # Close the file. 28 | coffee_file.close() 29 | print('Data appended to coffee.txt.') 30 | 31 | # Call the main function. 32 | main() 33 | 34 | 35 | -------------------------------------------------------------------------------- /Chapter 06/read_running_times.py: -------------------------------------------------------------------------------- 1 | # This program reads the values in the video_times.txt 2 | # file and calculates their total. 3 | 4 | def main(): 5 | # Open the video_times.txt file for reading. 6 | video_file = open('video_times.txt', 'r') 7 | 8 | # Initialize an accumulator to 0.0. 9 | total = 0.0 10 | 11 | # Initialize a variable to keep count of the videos. 12 | count = 0 13 | 14 | print('Here are the running times for each video:') 15 | 16 | # Get the values from the file and total them. 17 | for line in video_file: 18 | # Convert a line to a float. 19 | run_time = float(line) 20 | 21 | # Add 1 to the count variable. 22 | count += 1 23 | 24 | # Display the time. 25 | print('Video #', count, ': ', run_time, sep='') 26 | 27 | # Add the time to total. 28 | total += run_time 29 | 30 | # Close the file. 31 | video_file.close() 32 | 33 | # Display the total of the running times. 34 | print('The total running time is', total, 'seconds.') 35 | 36 | # Call the main function. 37 | main() 38 | -------------------------------------------------------------------------------- /Chapter 09/unpickle_objects.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates object unpickling. 2 | import pickle 3 | 4 | # main function 5 | def main(): 6 | end_of_file = False # To indicate end of file 7 | 8 | # Open a file for binary reading. 9 | input_file = open('info.dat', 'rb') 10 | 11 | # Read to the end of the file. 12 | while not end_of_file: 13 | try: 14 | # Unpickle the next object. 15 | person = pickle.load(input_file) 16 | 17 | # Display the object. 18 | display_data(person) 19 | except EOFError: 20 | # Set the flag to indicate the end 21 | # of the file has been reached. 22 | end_of_file = True 23 | 24 | # Close the file. 25 | input_file.close() 26 | 27 | # The display_data function displays the person data 28 | # in the dictionary that is passed as an argument. 29 | def display_data(person): 30 | print('Name:', person['name']) 31 | print('Age:', person['age']) 32 | print('Weight:', person['weight']) 33 | print() 34 | 35 | # Call the main function. 36 | main() 37 | 38 | -------------------------------------------------------------------------------- /Chapter 06/read_emp_records.py: -------------------------------------------------------------------------------- 1 | # This program displays the records that are 2 | # in the employees.txt file. 3 | 4 | def main(): 5 | # Open the employees.txt file. 6 | emp_file = open('employees.txt', 'r') 7 | 8 | # Read the first line from the file, which is 9 | # the name field of the first record. 10 | name = emp_file.readline() 11 | 12 | # If a field was read, continue processing. 13 | while name != '': 14 | # Read the ID number field. 15 | id_num = emp_file.readline() 16 | 17 | # Read the department field. 18 | dept = emp_file.readline() 19 | 20 | # Strip the newlines from the fields. 21 | name = name.rstrip('\n') 22 | id_num = id_num.rstrip('\n') 23 | dept = dept.rstrip('\n') 24 | 25 | # Display the record. 26 | print('Name:', name) 27 | print('ID:', id_num) 28 | print('Dept:', dept) 29 | print() 30 | 31 | # Read the name field of the next record. 32 | name = emp_file.readline() 33 | 34 | # Close the file. 35 | emp_file.close() 36 | 37 | # Call the main function. 38 | main() 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Yorwos 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Chapter 06/save_emp_records.py: -------------------------------------------------------------------------------- 1 | # This program gets employee data from the user and 2 | # saves it as records in the employee.txt file. 3 | 4 | def main(): 5 | # Get the number of employee records to create. 6 | num_emps = int(input('How many employee records ' + \ 7 | 'do you want to create? ')) 8 | 9 | # Open a file for writing. 10 | emp_file = open('employees.txt', 'w') 11 | 12 | # Get each employee's data and write it to 13 | # the file. 14 | for count in range(1, num_emps + 1): 15 | # Get the data for an employee. 16 | print('Enter data for employee #', count, sep='') 17 | name = input('Name: ') 18 | id_num = input('ID number: ') 19 | dept = input('Department: ') 20 | 21 | # Write the data as a record to the file. 22 | emp_file.write(name + '\n') 23 | emp_file.write(id_num + '\n') 24 | emp_file.write(dept + '\n') 25 | 26 | # Display a blank line. 27 | print() 28 | 29 | # Close the file. 30 | emp_file.close() 31 | print('Employee records written to employees.txt.') 32 | 33 | # Call the main function. 34 | main() 35 | 36 | 37 | -------------------------------------------------------------------------------- /Chapter 07/return_list.py: -------------------------------------------------------------------------------- 1 | # This program uses a function to create a list. 2 | # The function returns a reference to the list. 3 | 4 | def main(): 5 | # Get a list with values stored in it. 6 | numbers = get_values() 7 | 8 | # Display the values in the list. 9 | print('The numbers in the list are:') 10 | print(numbers) 11 | 12 | # The get_values function gets a series of numbers 13 | # from the user and stores them in a list. The 14 | # function returns a reference to the list. 15 | def get_values(): 16 | # Create an empty list. 17 | values = [] 18 | 19 | # Create a variable to control the loop. 20 | again = 'Y' 21 | 22 | # Get values from the user and add them to 23 | # the list. 24 | while again.upper() == 'Y': 25 | # Get a number and add it to the list. 26 | num = int(input('Enter a number: ')) 27 | values.append(num) 28 | 29 | # Want to do this again? 30 | print('Do you want to add another number?') 31 | again = input('y = yes, anything else = no: ') 32 | print 33 | 34 | # Return the list. 35 | return values 36 | 37 | # Call the main function. 38 | main() 39 | -------------------------------------------------------------------------------- /Chapter 04/test_score_averages.py: -------------------------------------------------------------------------------- 1 | # This program averages test scores. It asks the user for the 2 | # number of students and the number of test scores per student. 3 | 4 | # Get the number of students. 5 | num_students = int(input('How many students do you have? ')) 6 | 7 | # Get the number of test scores per student. 8 | num_test_scores = int(input('How many test scores per student? ')) 9 | 10 | # Determine each students average test score. 11 | for student in range(num_students): 12 | # Initialize an accumulator for test scores. 13 | total = 0.0 14 | # Get a student's test scores. 15 | print('Student number', student + 1) 16 | print('-----------------') 17 | for test_num in range(num_test_scores): 18 | print('Test number', test_num + 1, end='') 19 | score = float(input(': ')) 20 | # Add the score to the accumulator. 21 | total += score 22 | 23 | # Calculate the average test score for this student. 24 | average = total / num_test_scores 25 | 26 | # Display the average. 27 | print('The average for student number', student + 1, \ 28 | 'is:', format(average, '.1f')) 29 | print() 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Chapter 09/pickle_objects.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates object pickling. 2 | import pickle 3 | 4 | # main function 5 | def main(): 6 | again = 'y' # To control loop repetition 7 | 8 | # Open a file for binary writing. 9 | output_file = open('info.dat', 'wb') 10 | 11 | # Get data until the user wants to stop. 12 | while again.lower() == 'y': 13 | # Get data about a person and save it. 14 | save_data(output_file) 15 | 16 | # Does the user want to enter more data? 17 | again = input('Enter more data? (y/n): ') 18 | 19 | # Close the file. 20 | output_file.close() 21 | 22 | # The save_data function gets data about a person, 23 | # stores it in a dictionary, and then pickles the 24 | # dictionary to the specified file. 25 | def save_data(file): 26 | # Create an empty dictionary. 27 | person = {} 28 | 29 | # Get data for a person and store 30 | # it in the dictionary. 31 | person['name'] = input('Name: ') 32 | person['age'] = int(input('Age: ')) 33 | person['weight'] = float(input('Weight: ')) 34 | 35 | # Pickle the dictionary. 36 | pickle.dump(person, file) 37 | 38 | # Call the main function. 39 | main() 40 | -------------------------------------------------------------------------------- /Chapter 10/exercise5/retailitem.py: -------------------------------------------------------------------------------- 1 | # 5. RetailItem Class 2 | # Write a class named RetailItem that holds data about an item in a retail store. 3 | # The class should store the following data in attributes: item description, 4 | # units in inventory, and price. 5 | # Once you have written the class, write a program that creates three RetailItem 6 | # objects and stores the following data in them: 7 | 8 | # Description Units in Inventory Price 9 | # Item #1 Jacket 12 59.95 10 | # Item #2 Designer Jeans 40 34.95 11 | # Item #3 Shirt 20 24.95 12 | 13 | class RetailItem: 14 | def __init__(self,description,units,price): 15 | self.__description = description 16 | self.__units = units 17 | self.__price = price 18 | 19 | def get_description(self): 20 | return self.__description 21 | 22 | def get_units(self): 23 | return self.__units 24 | 25 | def get_price(self): 26 | return self.__price 27 | 28 | def set_descripition(self,description): 29 | self.__description = description 30 | 31 | def set_units(self,units): 32 | self.__units == units 33 | 34 | def set_price(self,price): 35 | self.__price = price -------------------------------------------------------------------------------- /Chapter 10/unpickle_cellphone.py: -------------------------------------------------------------------------------- 1 | # This program unpickles CellPhone objects. 2 | import pickle 3 | import cellphone 4 | 5 | # Constant for the filename. 6 | FILENAME = 'cellphones.dat' 7 | 8 | def main(): 9 | end_of_file = False # To indicate end of file 10 | 11 | # Open the file. 12 | input_file = open(FILENAME, 'rb') 13 | 14 | # Read to the end of the file. 15 | while not end_of_file: 16 | try: 17 | # Unpickle the next object. 18 | phone = pickle.load(input_file) 19 | 20 | # Display the cell phone data. 21 | display_data(phone) 22 | except EOFError: 23 | # Set the flag to indicate the end 24 | # of the file has been reached. 25 | end_of_file = True 26 | 27 | # Close the file. 28 | input_file.close() 29 | 30 | # The display_data function displays the data 31 | # from the CellPhone object passed as an argument. 32 | def display_data(phone): 33 | print('Manufacturer:', phone.get_manufact()) 34 | print('Model Number:', phone.get_model()) 35 | print('Retail Price: $', \ 36 | format(phone.get_retail_price(), ',.2f'), \ 37 | sep='') 38 | print() 39 | 40 | # Call the main function. 41 | main() 42 | -------------------------------------------------------------------------------- /Chapter 13/button_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a Button widget. 2 | # When the user clicks the Button, an 3 | # info dialog box is displayed. 4 | 5 | import tkinter 6 | import tkinter.messagebox 7 | 8 | class MyGUI: 9 | def __init__(self): 10 | # Create the main window widget. 11 | self.main_window = tkinter.Tk() 12 | 13 | # Create a Button widget. The text 'Click Me!' 14 | # should appear on the face of the Button. The 15 | # do_something method should be executed when 16 | # the user clicks the Button. 17 | self.my_button = tkinter.Button(self.main_window, \ 18 | text='Click Me!', \ 19 | command=self.do_something) 20 | 21 | # Pack the Button. 22 | self.my_button.pack() 23 | 24 | # Enter the tkinter main loop. 25 | tkinter.mainloop() 26 | 27 | # The do_something method is a callback function 28 | # for the Button widget. 29 | 30 | def do_something(self): 31 | # Display an info dialog box. 32 | tkinter.messagebox.showinfo('Response', \ 33 | 'Thanks for clicking the button.') 34 | 35 | # Create an instance of the MyGUI class. 36 | my_gui = MyGUI() 37 | 38 | -------------------------------------------------------------------------------- /Chapter 10/algo3.txt: -------------------------------------------------------------------------------- 1 | Look at the following description of a problem domain: 2 | 3 | The bank offers the following types of accounts to its customers: savings accounts, 4 | checking accounts, and money market accounts. Customers are allowed to deposit 5 | money into an account (thereby increasing its balance), withdraw money from an 6 | account (thereby decreasing its balance), and earn interest on the account. Each 7 | account has an interest rate. 8 | 9 | Assume that you are writing a program that will calculate the amount of interest 10 | earned for a bank account. 11 | 12 | a. Identify the potential classes in this problem domain. 13 | b. Refine the list to include only the necessary class or classes for this problem. 14 | c. Identify the responsibilities of the class or classes. 15 | 16 | 17 | account 18 | -The account's type 19 | -The account's balance 20 | -The account's interest 21 | 22 | - Withdraw money 23 | - Deposit money 24 | - Show balance 25 | 26 | --------------------------------- 27 | Account | 28 | --------------------------------- 29 | __type | 30 | __balance | 31 | __interest | 32 | --------------------------------- 33 | __init__(type,balance,interest) | 34 | set_type(type) | 35 | deposit(balance) | 36 | withdraw(balance) | 37 | __str__() | 38 | ---------------------------------z -------------------------------------------------------------------------------- /Chapter 10/coin_demo3.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # The Coin class simulates a coin that can 4 | # be flipped. 5 | 6 | class Coin: 7 | 8 | # The __init__ method initializes the 9 | # __sideup data attribute with 'Heads'. 10 | 11 | def __init__(self): 12 | self.__sideup = 'Heads' 13 | 14 | # The toss method generates a random number 15 | # in the range of 0 through 1. If the number 16 | # is 0, then sideup is set to 'Heads'. 17 | # Otherwise, sideup is set to 'Tails'. 18 | 19 | def toss(self): 20 | if random.randint(0, 1) == 0: 21 | self.__sideup = 'Heads' 22 | else: 23 | self.__sideup = 'Tails' 24 | 25 | # The get_sideup method returns the value 26 | # referenced by sideup. 27 | 28 | def get_sideup(self): 29 | return self.__sideup 30 | 31 | # The main function. 32 | def main(): 33 | # Create an object from the Coin class. 34 | my_coin = Coin() 35 | 36 | # Display the side of the coin that is facing up. 37 | print('This side is up:', my_coin.get_sideup()) 38 | 39 | # Toss the coin. 40 | print('I am going to toss the coin ten times:') 41 | for count in range(10): 42 | my_coin.toss() 43 | print(my_coin.get_sideup()) 44 | 45 | # Call the main function. 46 | main() 47 | -------------------------------------------------------------------------------- /Chapter 10/contact.py: -------------------------------------------------------------------------------- 1 | # The Contact class holds contact information. 2 | 3 | class Contact: 4 | # The __init__ method initializes the attributes. 5 | def __init__(self, name, phone, email): 6 | self.__name = name 7 | self.__phone = phone 8 | self.__email = email 9 | 10 | # The set_name method sets the name attribute. 11 | def set_name(self, name): 12 | self.__name = name 13 | 14 | # The set_phone method sets the phone attribute. 15 | def set_phone(self, phone): 16 | self.__phone = phone 17 | 18 | # The set_email method sets the email attribute. 19 | def set_email(self, email): 20 | self.__email = email 21 | 22 | # The get_name method returns the name attribute. 23 | def get_name(self): 24 | return self.__name 25 | 26 | # The get_phone method returns the phone attribute. 27 | def get_phone(self): 28 | return self.__phone 29 | 30 | # The get_email method returns the email attribute. 31 | def get_email(self): 32 | return self.__email 33 | 34 | # The __str__ method returns the object's state 35 | # as a string. 36 | def __str__(self): 37 | return "Name: " + self.__name + \ 38 | "\nPhone: " + self.__phone + \ 39 | "\nEmail: " + self.__email 40 | 41 | -------------------------------------------------------------------------------- /Chapter 10/coin_demo1.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # The Coin class simulates a coin that can 4 | # be flipped. 5 | 6 | class Coin: 7 | 8 | # The __init__ method initializes the 9 | # sideup data attribute with 'Heads'. 10 | 11 | def __init__(self): 12 | self.sideup = 'Heads' 13 | 14 | # The toss method generates a random number 15 | # in the range of 0 through 1. If the number 16 | # is 0, then sideup is set to 'Heads'. 17 | # Otherwise, sideup is set to 'Tails'. 18 | 19 | def toss(self): 20 | if random.randint(0, 1) == 0: 21 | self.sideup = 'Heads' 22 | else: 23 | self.sideup = 'Tails' 24 | 25 | # The get_sideup method returns the value 26 | # referenced by sideup. 27 | 28 | def get_sideup(self): 29 | return self.sideup 30 | 31 | # The main function. 32 | def main(): 33 | # Create an object from the Coin class. 34 | my_coin = Coin() 35 | 36 | # Display the side of the coin that is facing up. 37 | print('This side is up:', my_coin.get_sideup()) 38 | 39 | # Toss the coin. 40 | print('I am tossing the coin...') 41 | my_coin.toss() 42 | 43 | # Display the side of the coin that is facing up. 44 | print('This side is up:', my_coin.get_sideup()) 45 | 46 | # Call the main function. 47 | main() 48 | -------------------------------------------------------------------------------- /Chapter 10/cellphone.py: -------------------------------------------------------------------------------- 1 | # The CellPhone class holds data about a cell phone. 2 | 3 | class CellPhone: 4 | 5 | # The __init__ method initializes the attributes. 6 | 7 | def __init__(self, manufact, model, price): 8 | self.__manufact = manufact 9 | self.__model = model 10 | self.__retail_price = price 11 | 12 | # The set_manufact method accepts an argument for 13 | # the phone's manufacturer. 14 | 15 | def set_manufact(self, manufact): 16 | self.__manufact = manufact 17 | 18 | # The set_model method accepts an argument for 19 | # the phone's model number. 20 | 21 | def set_model(self, model): 22 | self.__model = model 23 | 24 | # The set_retail_price method accepts an argument 25 | # for the phone's retail price. 26 | 27 | def set_retail_price(self, price): 28 | self.__retail_price = price 29 | 30 | # The get_manufact method returns the 31 | # phone's manufacturer. 32 | 33 | def get_manufact(self): 34 | return self.__manufact 35 | 36 | # The get_model method returns the 37 | # phone's model number. 38 | 39 | def get_model(self): 40 | return self.__model 41 | 42 | # The get_retail_price method returns the 43 | # phone's retail price. 44 | 45 | def get_retail_price(self): 46 | return self.__retail_price 47 | -------------------------------------------------------------------------------- /Chapter 10/algo2.py: -------------------------------------------------------------------------------- 1 | # 2. Write a class definition named Book. The Book class should have data 2 | # attributes for a book’s title, the author’s name, and the publisher’s 3 | # name. 4 | 5 | # The class should also have the following: 6 | # a. An _ _init_ _ method for the class. The method should accept an 7 | # argument for each of the data attributes. 8 | 9 | # b. Accessor and mutator methods for each data attribute. 10 | 11 | # c. An _ _str_ _ method that returns a string indicating the state 12 | #of the object. 13 | 14 | class Book: 15 | def __init__(self,title,author,publisher): 16 | self.__title = title 17 | self.__author = author 18 | self.__publisher = publisher 19 | 20 | def set_title(self,title): 21 | self.__title = title 22 | 23 | def set_author(self,author): 24 | self.__author = author 25 | 26 | def set_publisher(self,publisher): 27 | self.__publisher = publisher 28 | 29 | def get_title(self): 30 | return self.__title 31 | 32 | def get_author(self): 33 | return self.__author 34 | 35 | def get_publisher(self): 36 | return self.__publisher 37 | 38 | def __str__(self): 39 | return "Title: " + self.__title + \ 40 | '\nAuthor: ' + self.__author + \ 41 | "\nPublisher: " + self.__publisher -------------------------------------------------------------------------------- /Chapter 09/exercise9_1/ex1.py: -------------------------------------------------------------------------------- 1 | def create_dictionaries(): 2 | JupiterMoons = ('Io','Europa','Ganymede','Callisto') 3 | Radius = (1821.6,1560.8,2634.1,2410.3) 4 | Gravity = (1.796,1.314,1.438,1.235) 5 | Orbit = (1.769,3.551,7.154,16.689) 6 | MeanRadius = dict() 7 | SurfaceGravity = dict() 8 | OrbitalPeriod = dict() 9 | for index in range(len(JupiterMoons)): 10 | MeanRadius[JupiterMoons[index]] = Radius[index] 11 | SurfaceGravity[JupiterMoons[index]] = Gravity[index] 12 | OrbitalPeriod[JupiterMoons[index]] = Orbit[index] 13 | return JupiterMoons,MeanRadius, SurfaceGravity,OrbitalPeriod 14 | 15 | def main(): 16 | JupiterMoons, MeanRadius, SurfaceGravity, OrbitalPeriod = create_dictionaries() 17 | print("This program displays information about Jupiter's Moons") 18 | print() 19 | print('The Moons are: ',end ='') 20 | for moon in JupiterMoons: 21 | print(moon + ' ',end='') 22 | print() 23 | choice = input('For which moon, would you like to see more information? ') 24 | print() 25 | if choice in JupiterMoons: 26 | print('Mean Radius in KM: ', MeanRadius[choice]) 27 | print('Surface Gravity in m/sec squared: ', SurfaceGravity[choice]) 28 | print('Orbital period in days: ',OrbitalPeriod[choice]) 29 | else: 30 | print('There is no moon by this name') 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_4/exercise9_4.py: -------------------------------------------------------------------------------- 1 | # This program lists the unique words found in a specified file. 2 | def CountUniqueWords(file): 3 | # Open with utf8 encoding 4 | infile = open(file, 'r', encoding='utf8') 5 | # Create a set to store and pick the unique words. 6 | uniqueWords = set() 7 | # Split the text into words 8 | for line in infile: 9 | temp_line = line.split() 10 | for word in temp_line: 11 | # Strip the test of characters and make every word lowercase. 12 | word = word.strip('''~`!@# $%^&*()_+=-{}][:;"'<,>.?/''').lower() 13 | # Add the word to the set 14 | uniqueWords.add(word) 15 | # Turn the set into a list. 16 | uniqueWords = list(uniqueWords) 17 | # Display the results 18 | print('These are the unique words found in this file') 19 | print('---------------------------------------------') 20 | # Print all the words except the last one in the list 21 | # with a following comma 22 | for word in uniqueWords[:-1]: 23 | print(word + ',',end='') 24 | # Print the last word. 25 | print(uniqueWords[-1]) 26 | 27 | def main(): 28 | print('This program will count the number of unique words in a file.') 29 | print() 30 | 31 | # Get the filname form the user. 32 | filename = input('Please select a filename: ') 33 | CountUniqueWords(filename) 34 | 35 | # Call the main function. 36 | main() -------------------------------------------------------------------------------- /Chapter 09/exercise9_10/text.txt: -------------------------------------------------------------------------------- 1 | When an object’s data attributes are hidden from outside code, and access to the data attri- 2 | butes is restricted to the object’s methods, the data attributes are protected from accidental 3 | corruption. In addition, the code outside the object does not need to know about the format 4 | or internal structure of the object’s data. The code only needs to interact with the object’s 5 | methods. When a programmer changes the structure of an object’s internal data attributes, 6 | he or she also modifies the object’s methods so they may properly operate on the data. The 7 | way in which outside code interacts with the methods, however, does not change. 8 | Object Reusability 9 | In addition to solving the problems of code and data separation, the use of OOP has also 10 | been encouraged by the trend of object reusability. An object is not a stand-alone program, 11 | but is used by programs that need its services. For example, Sharon is a programmer who 12 | has developed a set of objects for rendering 3D images. She is a math whiz and knows a 13 | lot about computer graphics, so her objects are coded to perform all of the necessary 3D 14 | mathematical operations and handle the computer’s video hardware. Tom, who is writing a 15 | program for an architectural firm, needs his application to display 3D images of buildings. 16 | Because he is working under a tight deadline and does not possess a great deal of knowl- 17 | edge about computer graphics, 18 | -------------------------------------------------------------------------------- /Chapter 06/search_coffee_records.py: -------------------------------------------------------------------------------- 1 | # This program allows the user to search the 2 | # coffee.txt file for records matching a 3 | # description. 4 | 5 | def main(): 6 | # Create a bool variable to use as a flag. 7 | found = False 8 | 9 | # Get the search value. 10 | search = input('Enter a description to search for: ') 11 | 12 | # Open the coffee.txt file. 13 | coffee_file = open('coffee.txt', 'r') 14 | 15 | # Read the first record's description field. 16 | descr = coffee_file.readline() 17 | 18 | # Read the rest of the file. 19 | while descr != '': 20 | # Read the quantity field. 21 | qty = float(coffee_file.readline()) 22 | 23 | # Strip the \n from the description. 24 | descr = descr.rstrip('\n') 25 | 26 | # Determine whether this record matches 27 | # the search value. 28 | if descr == search: 29 | # Display the record. 30 | print('Description:', descr) 31 | print('Quantity:', qty) 32 | print() 33 | # Set the found flag to True. 34 | found = True 35 | 36 | # Read the next description. 37 | descr = coffee_file.readline() 38 | 39 | # Close the file. 40 | coffee_file.close() 41 | 42 | # If the search value was not found in the file 43 | # display a message. 44 | if not found: 45 | print('That item was not found in the file.') 46 | 47 | # Call the main function. 48 | main() 49 | 50 | 51 | -------------------------------------------------------------------------------- /Chapter 11/animals.py: -------------------------------------------------------------------------------- 1 | # The Mammal class represents a generic mammal. 2 | 3 | class Mammal: 4 | 5 | # The __init__ method accepts an argument for 6 | # the mammal's species. 7 | 8 | def __init__(self, species): 9 | self.__species = species 10 | 11 | # The show_species method displays a message 12 | # indicating the mammal's species. 13 | 14 | def show_species(self): 15 | print('I am a', self.__species) 16 | 17 | # The make_sound method is the mammal's 18 | # way of making a generic sound. 19 | 20 | def make_sound(self): 21 | print('Grrrrr') 22 | 23 | # The Dog class is a subclass of the Mammal class. 24 | 25 | class Dog(Mammal): 26 | 27 | # The __init__ method calls the superclass's 28 | # __init__ method passing 'Dog' as the species. 29 | 30 | def __init__(self): 31 | Mammal.__init__(self, 'Dog') 32 | 33 | # The make_sound method overrides the superclass's 34 | # make_sound method. 35 | 36 | def make_sound(self): 37 | print('Woof! Woof!') 38 | 39 | # The Cat class is a subclass of the Mammal class. 40 | 41 | class Cat(Mammal): 42 | 43 | # The __init__ method calls the superclass's 44 | # __init__ method passing 'Cat' as the species. 45 | 46 | def __init__(self): 47 | Mammal.__init__(self, 'Cat') 48 | 49 | # The make_sound method overrides the superclass's 50 | # make_sound method. 51 | 52 | def make_sound(self): 53 | print('Meow') 54 | -------------------------------------------------------------------------------- /Chapter 09/sets.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates various set operations. 2 | baseball = set(['Jodi', 'Carmen', 'Aida', 'Alicia']) 3 | basketball = set(['Eva', 'Carmen', 'Alicia', 'Sarah']) 4 | 5 | # Display members of the baseball set. 6 | print('The following students are on the baseball team:') 7 | for name in baseball: 8 | print(name) 9 | 10 | # Display members of the basketball set. 11 | print() 12 | print('The following students are on the basketball team:') 13 | for name in basketball: 14 | print(name) 15 | 16 | # Demonstrate intersection 17 | print() 18 | print('The following students play both baseball and basketball:') 19 | for name in baseball.intersection(basketball): 20 | print(name) 21 | 22 | # Demonstrate union 23 | print() 24 | print('The following students play either baseball or basketball:') 25 | for name in baseball.union(basketball): 26 | print(name) 27 | 28 | # Demonstrate difference of baseball and basketball 29 | print() 30 | print('The following students play baseball, but not basketball:') 31 | for name in baseball.difference(basketball): 32 | print(name) 33 | 34 | # Demonstrate difference of basketball and baseball 35 | print() 36 | print('The following students play basketball, but not baseball:') 37 | for name in basketball.difference(baseball): 38 | print(name) 39 | 40 | # Demonstrate symmetric difference 41 | print() 42 | print('The following students play one sport, but not both:') 43 | for name in baseball.symmetric_difference(basketball): 44 | print(name) 45 | -------------------------------------------------------------------------------- /Chapter 10/coin_demo2.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # The Coin class simulates a coin that can 4 | # be flipped. 5 | 6 | class Coin: 7 | 8 | # The __init__ method initializes the 9 | # sideup data attribute with 'Heads'. 10 | 11 | def __init__(self): 12 | self.sideup = 'Heads' 13 | 14 | # The toss method generates a random number 15 | # in the range of 0 through 1. If the number 16 | # is 0, then sideup is set to 'Heads'. 17 | # Otherwise, sideup is set to 'Tails'. 18 | 19 | def toss(self): 20 | if random.randint(0, 1) == 0: 21 | self.sideup = 'Heads' 22 | else: 23 | self.sideup = 'Tails' 24 | 25 | # The get_sideup method returns the value 26 | # referenced by sideup. 27 | 28 | def get_sideup(self): 29 | return self.sideup 30 | 31 | # The main function. 32 | def main(): 33 | # Create an object from the Coin class. 34 | my_coin = Coin() 35 | 36 | # Display the side of the coin that is facing up. 37 | print('This side is up:', my_coin.get_sideup()) 38 | 39 | # Toss the coin. 40 | print('I am tossing the coin...') 41 | my_coin.toss() 42 | 43 | # But now I'm going to cheat! I'm going to 44 | # directly change the value of the object's 45 | # sideup attribute to 'Heads'. 46 | my_coin.sideup = 'Heads' 47 | 48 | # Display the side of the coin that is facing up. 49 | print('This side is up:', my_coin.get_sideup()) 50 | 51 | # Call the main function. 52 | main() 53 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_2/StatesCapitals.txt: -------------------------------------------------------------------------------- 1 | Montgomery 2 | Alabama 3 | Juneau 4 | Alaska 5 | Phoenix 6 | Arizona 7 | Little Rock 8 | Arkansas 9 | Sacramento 10 | California 11 | Denver 12 | Colorado 13 | Hartford 14 | Connecticut 15 | Dover 16 | Delaware 17 | Tallahassee 18 | Florida 19 | Atlanta 20 | Georgia 21 | Honolulu 22 | Hawaii 23 | Boise 24 | Idaho 25 | Springfield 26 | Illinois 27 | Indianapolis 28 | Indiana 29 | Des Moines 30 | Iowa 31 | Topeka 32 | Kansas 33 | Frankfort 34 | Kentucky 35 | Baton Rouge 36 | Louisiana 37 | Augusta 38 | Maine 39 | Annapolis 40 | Maryland 41 | Boston 42 | Massachusetts 43 | Lansing 44 | Michigan 45 | Saint Paul 46 | Minnesota 47 | Jackson 48 | Mississippi 49 | Jefferson City 50 | Missouri 51 | Helena 52 | Montana 53 | Lincoln 54 | Nebraska 55 | Carson City 56 | Nevada 57 | Concord 58 | New Hampshire 59 | Trenton 60 | New Jersey 61 | Santa Fe 62 | New Mexico 63 | Albany 64 | New York 65 | Raleigh 66 | North Carolina 67 | Bismarck 68 | North Dakota 69 | Columbus 70 | Ohio 71 | Oklahoma City 72 | Oklahoma 73 | Salem 74 | Oregon 75 | Harrisburg 76 | Pennsylvania 77 | Providence 78 | Rhode Island 79 | Columbia 80 | South Carolina 81 | Pierre 82 | South Dakota 83 | Nashville 84 | Tennessee 85 | Austin 86 | Texas 87 | Salt Lake City 88 | Utah 89 | Montpelier 90 | Vermont 91 | Richmond 92 | Virginia 93 | Olympia 94 | Washington 95 | Charleston 96 | West Virginia 97 | Madison 98 | Wisconsin 99 | Cheyenne 100 | Wyoming 101 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_2/ex9_2.py: -------------------------------------------------------------------------------- 1 | # Capital Quiz 2 | def dictStatesCapitals(): 3 | StatesCapitals = dict() 4 | cap_list = [] 5 | stat_list = [] 6 | infile = open('StatesCapitals.txt', 'r') 7 | StCap_list = infile.readlines() 8 | for capital in StCap_list[::2]: 9 | cap_list.append(capital.rstrip('\n')) 10 | for index in range(len(cap_list)): 11 | cap_list[index] = cap_list[index].rstrip() 12 | for state in StCap_list[1::2]: 13 | stat_list.append(state.rstrip('\n')) 14 | for index in range(len(stat_list)): 15 | stat_list[index] = stat_list[index].rstrip() 16 | for index in range(len(cap_list)): 17 | StatesCapitals[stat_list[index]] = cap_list[index] 18 | infile.close() 19 | return StatesCapitals 20 | 21 | def main(): 22 | import random 23 | questions = dictStatesCapitals() 24 | correct = 0 25 | wrong = 0 26 | print('Welcome to Capital Quiz') 27 | print() 28 | print('Do you know all the State Capitals?') 29 | print() 30 | for count in range(len(questions)): 31 | state, capital = questions.popitem() 32 | print('What is the capital of',state,'?: ',end = '') 33 | answer = input() 34 | if answer.lower() == capital.lower(): 35 | correct += 1 36 | print('Correct') 37 | print('Next Question') 38 | print() 39 | else: 40 | wrong += 1 41 | print('Wrong') 42 | print('Next Question') 43 | print() 44 | print('Correct:',correct) 45 | print('Wrong:',wrong) 46 | main() 47 | -------------------------------------------------------------------------------- /Chapter 08/text.txt: -------------------------------------------------------------------------------- 1 | No one is unaware of the name of that famous English shipowner, Cunard. 2 | In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons. 3 | Eight years later, the company's assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage. 4 | In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas. 5 | So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers. 6 | If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management. 7 | No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success. 8 | In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost. 9 | Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents. 10 | Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers. 11 | -------------------------------------------------------------------------------- /Chapter 10/exercise1/exercise1_2.py: -------------------------------------------------------------------------------- 1 | # 1. Pet Class 2 | # Write a class named Pet , which should have the following data attributes: 3 | # • _ _ name (for the name of a pet) 4 | # • _ _ animal_type (for the type of animal that a pet is. Example values are ‘Dog’, ‘Cat’, 5 | # and ‘Bird’) 6 | # • _ _ age (for the pet’s age) 7 | 8 | # The Pet class should have an _ _ init _ _ method that creates these 9 | # attributes. It should also have the following methods: 10 | 11 | # • set_name 12 | # This method assigns a value to the _ _ name field. 13 | # • set_animal_type 14 | # This method assigns a value to the _ _ animal_type field. 15 | # • set_age 16 | # This method assigns a value to the _ _ age field. 17 | # • get_name 18 | # This method returns the value of the _ _ name field. 19 | # • get_animal_type 20 | # This method returns the value of the _ _ animal_type field. 21 | # • get_age 22 | # This method returns the value of the _ _ age field. 23 | 24 | #Once you have written the class, write a program that creates an object of the class and 25 | #prompts the user to enter the name, type, and age of his or her pet. This data should be 26 | #stored as the object’s attributes. Use the object’s accessor methods to retrieve the pet’s 27 | #name, type, and age and display this data on the screen. 28 | 29 | import exercise1 30 | 31 | name = input('What is the name of your pet? ') 32 | animal_type = input('What kind of animal is it? ') 33 | age = input('How old is it? ') 34 | 35 | my_pet = exercise1.Pet(name,animal_type,age) 36 | print('You have a',my_pet.get_animal_type(),'named',my_pet.get_name(),'and it is',my_pet.get_age(),'years old.') -------------------------------------------------------------------------------- /Chapter 10/cell_phone_list.py: -------------------------------------------------------------------------------- 1 | # This program creates five CellPhone objects and 2 | # stores them in a list. 3 | 4 | import cellphone 5 | 6 | def main(): 7 | # Get a list of CellPhone objects. 8 | phones = make_list() 9 | 10 | # Display the data in the list. 11 | print('Here is the data you entered:') 12 | display_list(phones) 13 | 14 | # The make_list function gets data from the user 15 | # for five phones. The function returns a list 16 | # of CellPhone objects containing the data. 17 | 18 | def make_list(): 19 | # Create an empty list. 20 | phone_list = [] 21 | 22 | # Add five CellPhone objects to the list. 23 | print('Enter data for five phones.') 24 | for count in range(1, 6): 25 | # Get the phone data. 26 | print('Phone number ' + str(count) + ':') 27 | man = input('Enter the manufacturer: ') 28 | mod = input('Enter the model number: ') 29 | retail = float(input('Enter the retail price: ')) 30 | print 31 | 32 | # Create a new CellPhone object in memory and 33 | # assign it to the phone variable. 34 | phone = cellphone.CellPhone(man, mod, retail) 35 | 36 | # Add the object to the list. 37 | phone_list.append(phone) 38 | 39 | # Return the list. 40 | return phone_list 41 | 42 | # The display_list function accepts a list containing 43 | # CellPhone objects as an argument and displays the 44 | # data stored in each object. 45 | 46 | def display_list(phone_list): 47 | for item in phone_list: 48 | print(item.get_manufact()) 49 | print(item.get_model()) 50 | print(item.get_retail_price()) 51 | print() 52 | 53 | # Call the main function. 54 | main() 55 | -------------------------------------------------------------------------------- /Chapter 05/acme_dryer.py: -------------------------------------------------------------------------------- 1 | # This program displays step-by-step instructions 2 | # for disassembling an Acme dryer. 3 | # The main function performs the program's main logic. 4 | def main(): 5 | # Display the start-up message. 6 | startup_message() 7 | input('Press Enter to see Step 1.') 8 | # Display step 1. 9 | step1() 10 | input('Press Enter to see Step 2.') 11 | # Display step 2. 12 | step2() 13 | input('Press Enter to see Step 3.') 14 | # Display step 3. 15 | step3() 16 | input('Press Enter to see Step 4.') 17 | # Display step 4. 18 | step4() 19 | 20 | # The startup_message function displays the 21 | # program's initial message on the screen. 22 | def startup_message(): 23 | print('This program tells you how to') 24 | print('disassemble an ACME laundry dryer.') 25 | print('There are 4 steps in the process.') 26 | print() 27 | 28 | # The step1 function displays the instructions 29 | # for step 1. 30 | def step1(): 31 | print('Step 1: Unplug the dryer and') 32 | print('move it away from the wall.') 33 | print() 34 | 35 | # The step2 function displays the instructions 36 | # for step 2. 37 | def step2(): 38 | print('Step 2: Remove the six screws') 39 | print('from the back of the dryer.') 40 | print() 41 | 42 | # The step3 function displays the instructions 43 | # for step 3. 44 | def step3(): 45 | print('Step 3: Remove the back panel') 46 | print('from the dryer.') 47 | print() 48 | 49 | # The step4 function displays the instructions 50 | # for step 4. 51 | def step4(): 52 | print('Step 4: Pull the top of the') 53 | print('dryer straight up.') 54 | 55 | # Call the main function to begin the program. 56 | main() 57 | -------------------------------------------------------------------------------- /Chapter 08/exercise8_15/exercise8_15.py: -------------------------------------------------------------------------------- 1 | # Caesar Cipher 2 | 3 | # A “Caesar Cipher” is a simple way of encrypting a message by replacing each letter with a 4 | # letter a certain number of spaces up the alphabet. For example, if shifting the message by 5 | # 13 an A would become an N, while an S would wrap around to the start of the alphabet to 6 | # become an F. 7 | # Write a program that asks the user for a message (a string) and a shift amount (an integer). 8 | # The values should be passed to a function that accepts a string and an integer as arguments, 9 | # and returns a string representing the original string encrypted by shifting the letters by the 10 | # integer. For example, a string of “BEWARE THE IDES OF MARCH” and an integer of 13 11 | # should result in a string of “ORJNER GUR VQRF BS ZNEPU”. 12 | 13 | def caesar_cipher(string,integer): 14 | alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 15 | cipher_message = '' 16 | # for every letter in the string 17 | for index in range(len(string)): 18 | # find the position of the letter in alphabet 19 | original_position = alphabet.find(string[index].upper()) 20 | cipher_position = original_position + integer 21 | if original_position == -1: 22 | cipher_message += ' ' 23 | elif cipher_position > len(alphabet): 24 | cipher_position = cipher_position - 26 25 | cipher_message += (alphabet[cipher_position]) 26 | else: 27 | cipher_message += (alphabet[cipher_position]) 28 | return cipher_message 29 | 30 | 31 | def main(): 32 | message = input('Enter a message: ') 33 | shift_amount = int(input('Enter a shift amount:')) 34 | message = caesar_cipher(message,shift_amount) 35 | print(message) 36 | 37 | main() 38 | -------------------------------------------------------------------------------- /Chapter 13/quit_button.py: -------------------------------------------------------------------------------- 1 | # This program has a Quit button that calls 2 | # the Tk class's destroy method when clicked. 3 | 4 | import tkinter 5 | import tkinter.messagebox 6 | 7 | class MyGUI: 8 | def __init__(self): 9 | # Create the main window widget. 10 | self.main_window = tkinter.Tk() 11 | 12 | # Create a Button widget. The text 'Click Me!' 13 | # should appear on the face of the Button. The 14 | # do_something method should be executed when 15 | # the user clicks the Button. 16 | self.my_button = tkinter.Button(self.main_window, \ 17 | text='Click Me!', \ 18 | command=self.do_something) 19 | 20 | # Create a Quit button. When this button is clicked 21 | # the root widget's destroy method is called. 22 | # (The main_window variable references the root widget, 23 | # so the callback function is self.main_window.destroy.) 24 | self.quit_button = tkinter.Button(self.main_window, \ 25 | text='Quit', \ 26 | command=self.main_window.destroy) 27 | 28 | 29 | # Pack the Buttons. 30 | self.my_button.pack() 31 | self.quit_button.pack() 32 | 33 | # Enter the tkinter main loop. 34 | tkinter.mainloop() 35 | 36 | # The do_something method is a callback function 37 | # for the Button widget. 38 | 39 | def do_something(self): 40 | # Display an info dialog box. 41 | tkinter.messagebox.showinfo('Response', \ 42 | 'Thanks for clicking the button.') 43 | 44 | # Create an instance of the MyGUI class. 45 | my_gui = MyGUI() 46 | 47 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_6/exercise9_6.py: -------------------------------------------------------------------------------- 1 | #File Analysis 2 | # 3 | #This program reads the contents of two text files and compares them. 4 | #1. It displays a list of all the unique words contained in both files. 5 | #2. It displays a list of the words that appear in both files. 6 | #3. It displays a list of words that appear in the first file but not the second 7 | #4. It displays a list of words that appear in the 2nd file but not the 1st. 8 | #5. It displays a list of words that appear in either the 1st or 2nd file, but 9 | #not in both 10 | 11 | # This function requests the two files for comparison 12 | def comparefiles(file1,file2): 13 | print() 14 | print('All the words that appear in the files.') 15 | print(file1.union(file2)) 16 | print() 17 | 18 | print('Only the words that appear in both files.') 19 | print() 20 | print(file1.intersection(file2)) 21 | print() 22 | 23 | print('Words that appear in the first but not the second') 24 | print(file1.difference(file2)) 25 | print() 26 | 27 | print('Words that appear in the second but not the first.') 28 | print(file2.difference(file1)) 29 | print() 30 | print('Words that appear either in the 1st or 2nd but not in both.') 31 | print(file1.symmetric_difference(file2)) 32 | 33 | def getFileNames(): 34 | file1 = input('First file: ') 35 | file2 = input('Second file: ') 36 | return file1, file2 37 | 38 | 39 | def main(): 40 | # Request the files 41 | file_1, file_2 = getFileNames() 42 | # Open the files. 43 | firstFile = open(file_1, 'r') 44 | secondFile = open(file_2, 'r') 45 | contents1 = firstFile.read() 46 | contents2 = secondFile.read() 47 | contents1 = contents1.split() 48 | contents2 = contents2.split() 49 | con1 = set(contents1) 50 | con2 = set(contents2) 51 | comparefiles(con1,con2) 52 | 53 | main() -------------------------------------------------------------------------------- /Chapter 11/car_truck_suv_demo.py: -------------------------------------------------------------------------------- 1 | # This program creates a Car object, a Truck object, 2 | # and an SUV object. 3 | 4 | import vehicles 5 | 6 | def main(): 7 | # Create a Car object for a used 2001 BMW 8 | # with 70,000 miles, priced at $15,000, with 9 | # 4 doors. 10 | car = vehicles.Car('BMW', 2001, 70000, 15000.0, 4) 11 | 12 | # Create a Truck object for a used 2002 13 | # Toyota pickup with 40,000 miles, priced 14 | # at $12,000, with 4-wheel drive. 15 | truck = vehicles.Truck('Toyota', 2002, 40000, 12000.0, '4WD') 16 | 17 | # Create an SUV object for a used 2000 18 | # Volvo with 30,000 miles, priced 19 | # at $18,500, with 5 passenger capacity. 20 | suv = vehicles.SUV('Volvo', 2000, 30000, 18500.0, 5) 21 | 22 | print('USED CAR INVENTORY') 23 | print('===================') 24 | 25 | # Display the car's data. 26 | print('The following car is in inventory:') 27 | print('Make:', car.get_make()) 28 | print('Model:', car.get_model()) 29 | print('Mileage:', car.get_mileage()) 30 | print('Price:', car.get_price()) 31 | print('Number of doors:', car.get_doors()) 32 | print() 33 | 34 | # Display the truck's data. 35 | print('The following pickup truck is in inventory.') 36 | print('Make:', truck.get_make()) 37 | print('Model:', truck.get_model()) 38 | print('Mileage:', truck.get_mileage()) 39 | print('Price:', truck.get_price()) 40 | print('Drive type:', truck.get_drive_type()) 41 | print() 42 | 43 | # Display the SUV's data. 44 | print('The following SUV is in inventory.') 45 | print('Make:', suv.get_make()) 46 | print('Model:', suv.get_model()) 47 | print('Mileage:', suv.get_mileage()) 48 | print('Price:', suv.get_price()) 49 | print('Passenger Capacity:', suv.get_pass_cap()) 50 | 51 | # Call the main function. 52 | main() 53 | 54 | -------------------------------------------------------------------------------- /Chapter 11/account demo.py: -------------------------------------------------------------------------------- 1 | # This program creates an instance of the SavingsAccount 2 | # class and an instance of the CD account. 3 | 4 | import accounts 5 | 6 | def main(): 7 | # Get the account number, interest rate, 8 | # and account balance for a savings account. 9 | print('Enter the following data for a savings account.') 10 | acct_num = input('Account number: ') 11 | int_rate = float(input('Interest rate: ')) 12 | balance = float(input('Balance: ')) 13 | 14 | # Create a SavingsAccount object. 15 | savings = accounts.SavingsAccount(acct_num, int_rate, \ 16 | balance) 17 | 18 | # Get the account number, interest rate, 19 | # account balance, and maturity date for a CD. 20 | print('Enter the following data for a CD.') 21 | acct_num = input('Account number: ') 22 | int_rate = float(input('Interest rate: ')) 23 | balance = float(input('Balance: ')) 24 | maturity = input('Maturity date: ') 25 | 26 | # Create a CD object. 27 | cd = accounts.CD(acct_num, int_rate, balance, maturity) 28 | 29 | # Display the data entered. 30 | print('Here is the data you entered:') 31 | print() 32 | print('Savings Account') 33 | print('---------------') 34 | print('Account number:', savings.get_account_num()) 35 | print('Interest rate:', savings.get_interest_rate()) 36 | print('Balance: $', \ 37 | format(savings.get_balance(), ',.2f'), \ 38 | sep='') 39 | print() 40 | print('CD') 41 | print('---------------') 42 | print('Account number:', cd.get_account_num()) 43 | print('Interest rate:', cd.get_interest_rate()) 44 | print('Balance: $', \ 45 | format(cd.get_balance(), ',.2f'), \ 46 | sep='') 47 | print('Maturity date:', cd.get_maturity_date()) 48 | 49 | # Call the main function. 50 | main() 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /Chapter 06/delete_coffee_record.py: -------------------------------------------------------------------------------- 1 | # This program allows the user to delete 2 | # a record in the coffee.txt file. 3 | 4 | import os # Needed for the remove and rename functions 5 | 6 | def main(): 7 | # Create a bool variable to use as a flag. 8 | found = False 9 | 10 | # Get the coffee to delete. 11 | search = input('Which coffee do you want to delete? ') 12 | 13 | # Open the original coffee.txt file. 14 | coffee_file = open('coffee.txt', 'r') 15 | 16 | # Open the temporary file. 17 | temp_file = open('temp.txt', 'w') 18 | 19 | # Read the first record's description field. 20 | descr = coffee_file.readline() 21 | 22 | # Read the rest of the file. 23 | while descr != '': 24 | # Read the quantity field. 25 | qty = float(coffee_file.readline()) 26 | 27 | # Strip the \n from the description. 28 | descr = descr.rstrip('\n') 29 | 30 | # If this is not the record to delete, then 31 | # write it to the temporary file. 32 | if descr != search: 33 | # Write the record to the temp file. 34 | temp_file.write(descr + '\n') 35 | temp_file.write(str(qty) + '\n') 36 | else: 37 | # Set the found flag to True. 38 | found = True 39 | 40 | # Read the next description. 41 | descr = coffee_file.readline() 42 | 43 | # Close the coffee file and the temporary file. 44 | coffee_file.close() 45 | temp_file.close() 46 | 47 | # Delete the original coffee.txt file. 48 | os.remove('coffee.txt') 49 | 50 | # Rename the temporary file. 51 | os.rename('temp.txt', 'coffee.txt') 52 | 53 | # If the search value was not found in the file 54 | # display a message. 55 | if found: 56 | print('The file has been updated.') 57 | else: 58 | print('That item was not found in the file.') 59 | 60 | # Call the main function. 61 | main() 62 | -------------------------------------------------------------------------------- /Chapter 10/exercise1/exercise1.py: -------------------------------------------------------------------------------- 1 | # 1. Pet Class 2 | # Write a class named Pet , which should have the following data attributes: 3 | # • _ _ name (for the name of a pet) 4 | # • _ _ animal_type (for the type of animal that a pet is. Example values are ‘Dog’, ‘Cat’, 5 | # and ‘Bird’) 6 | # • _ _ age (for the pet’s age) 7 | 8 | # The Pet class should have an _ _ init _ _ method that creates these 9 | # attributes. It should also have the following methods: 10 | 11 | # • set_name 12 | # This method assigns a value to the _ _ name field. 13 | # • set_animal_type 14 | # This method assigns a value to the _ _ animal_type field. 15 | # • set_age 16 | # This method assigns a value to the _ _ age field. 17 | # • get_name 18 | # This method returns the value of the _ _ name field. 19 | # • get_animal_type 20 | # This method returns the value of the _ _ animal_type field. 21 | # • get_age 22 | # This method returns the value of the _ _ age field. 23 | 24 | #Once you have written the class, write a program that creates an object of the class and 25 | #prompts the user to enter the name, type, and age of his or her pet. This data should be 26 | #stored as the object’s attributes. Use the object’s accessor methods to retrieve the pet’s 27 | #name, type, and age and display this data on the screen. 28 | 29 | class Pet: 30 | 31 | def __init__(self,name,animal_type,age): 32 | self.__name = name 33 | self.__animal_type = animal_type 34 | self.__age = age 35 | 36 | def set_name(self,name): 37 | self.__name = name 38 | 39 | def set_age(self,age): 40 | self.__age = age 41 | 42 | def set_animal_type(self,animal_type): 43 | self.__animal_type = animal_type 44 | 45 | def get_name(self): 46 | return self.__name 47 | 48 | def get_animal_type(self): 49 | return self.__animal_type 50 | 51 | def get_age(self): 52 | return self.__age -------------------------------------------------------------------------------- /Chapter 07/drop_lowest_score.py: -------------------------------------------------------------------------------- 1 | # This program gets a series of test scores and 2 | # calculates the average of the scores with the 3 | # lowest score dropped. 4 | 5 | def main(): 6 | # Get the test scores from the user. 7 | scores = get_scores() 8 | 9 | # Get the total of the test scores. 10 | total = get_total(scores) 11 | 12 | # Get the lowest test score. 13 | lowest = min(scores) 14 | 15 | # Subtract the lowest score from the total. 16 | total -= lowest 17 | 18 | # Calculate the average. Note that we divide 19 | # by 1 less than the number of scores because 20 | # the lowest score was dropped. 21 | average = total / (len(scores) - 1) 22 | 23 | # Display the average. 24 | print('The average, with the lowest score dropped', \ 25 | 'is:', average) 26 | 27 | # The get_scores function gets a series of test 28 | # scores from the user and stores them in a list. 29 | # A reference to the list is returned. 30 | def get_scores(): 31 | # Create an empty list. 32 | test_scores = [] 33 | 34 | # Create a variable to control the loop. 35 | again = 'y' 36 | 37 | # Get the scores from the user and add them to 38 | # the list. 39 | while again == 'y': 40 | # Get a score and add it to the list. 41 | value = float(input('Enter a test score: ')) 42 | test_scores.append(value) 43 | 44 | # Want to do this again? 45 | print('Do you want to add another score?') 46 | again = input('y = yes, anything else = no: ') 47 | print() 48 | 49 | # Return the list. 50 | return test_scores 51 | 52 | # The get_total function accepts a list as an 53 | # argument returns the total of the values in 54 | # the list. 55 | def get_total(value_list): 56 | # Create a variable to use as an accumulator. 57 | total = 0.0 58 | 59 | # Calculate the total of the list elements. 60 | for num in value_list: 61 | total += num 62 | 63 | # Return the total. 64 | return total 65 | 66 | # Call the main function. 67 | main() 68 | -------------------------------------------------------------------------------- /Chapter 11/accounts.py: -------------------------------------------------------------------------------- 1 | # The SavingsAccount class represents a 2 | # savings account. 3 | 4 | class SavingsAccount: 5 | 6 | # The __init__ method accepts arguments for the 7 | # account number, interest rate, and balance. 8 | 9 | def __init__(self, account_num, int_rate, bal): 10 | self.__account_num = account_num 11 | self.__interest_rate = int_rate 12 | self.__balance = bal 13 | 14 | # The following methods are mutators for the 15 | # data attributes. 16 | 17 | def set_account_num(self, account_num): 18 | self.__account_num = account_num 19 | 20 | def set_interest_rate(self, int_rate): 21 | self.__interest_rate = int_rate 22 | 23 | def set_balance(self, bal): 24 | self.__balance = bal 25 | 26 | # The following methods are accessors for the 27 | # data attributes. 28 | 29 | def get_account_num(self): 30 | return self.__account_num 31 | 32 | def get_interest_rate(self): 33 | return self.__interest_rate 34 | 35 | def get_balance(self): 36 | return self.__balance 37 | 38 | # The CD account represents a certificate of 39 | # deposit (CD) account. It is a subclass of 40 | # the SavingsAccount class. 41 | 42 | class CD(SavingsAccount): 43 | 44 | # The init method accepts arguments for the 45 | # account number, interest rate, balance, and 46 | # maturity date. 47 | 48 | def __init__(self, account_num, int_rate, bal, mat_date): 49 | # Call the superclass __init__ method. 50 | SavingsAccount.__init__(self, account_num, int_rate, bal) 51 | 52 | # Initialize the __maturity_date attribute. 53 | self.__maturity_date = mat_date 54 | 55 | # The set_maturity_date is a mutator for the 56 | # __maturity_date attribute. 57 | 58 | def set_maturity_date(self, mat_date): 59 | self.__maturity_date = mat_date 60 | 61 | # The get_maturity_date method is an accessor 62 | # for the __maturity_date attribute. 63 | 64 | def get_maturity_date(self): 65 | return self.__maturity_date 66 | -------------------------------------------------------------------------------- /Chapter 05/commission_rate.py: -------------------------------------------------------------------------------- 1 | # This program calculates a salesperson's pay 2 | # at Make Your Own Music. 3 | def main(): 4 | # Get the amount of sales. 5 | sales = get_sales() 6 | 7 | # Get the amount of advanced pay. 8 | advanced_pay = get_advanced_pay() 9 | 10 | # Determine the commission rate. 11 | comm_rate = determine_comm_rate(sales) 12 | 13 | # Calculate the pay. 14 | pay = sales * comm_rate - advanced_pay 15 | 16 | # Display the amount of pay. 17 | print('The pay is $', format(pay, ',.2f'), sep='') 18 | 19 | # Determine whether the pay is negative. 20 | if pay < 0: 21 | print('The salesperson must reimburse') 22 | print('the company.') 23 | 24 | # The get_sales function gets a salesperson's 25 | # monthly sales from the user and returns that value. 26 | def get_sales(): 27 | # Get the amount of monthly sales. 28 | monthly_sales = float(input('Enter the monthly sales: ')) 29 | 30 | # Return the amount entered. 31 | return monthly_sales 32 | 33 | # The get_advanced_pay function gets the amount of 34 | # advanced pay given to the salesperson and returns 35 | # that amount. 36 | def get_advanced_pay(): 37 | # Get the amount of advanced pay. 38 | print('Enter the amount of advanced pay, or') 39 | print('enter 0 if no advanced pay was given.') 40 | advanced = float(input('Advanced pay: ')) 41 | 42 | # Return the amount entered. 43 | return advanced 44 | 45 | # The determine_comm_rate function accepts the 46 | # amount of sales as an argument and returns the 47 | # applicable commission rate. 48 | def determine_comm_rate(sales): 49 | # Determine the commission rate. 50 | if sales < 10000.00: 51 | rate = 0.10 52 | elif sales >= 10000 and sales <= 14999.99: 53 | rate = 0.12 54 | elif sales >= 15000 and sales <= 17999.99: 55 | rate = 0.14 56 | elif sales >= 18000 and sales <= 21999.99: 57 | rate = 0.16 58 | else: 59 | rate = 0.18 60 | 61 | # Return the commission rate. 62 | return rate 63 | 64 | # Call the main function 65 | main() 66 | -------------------------------------------------------------------------------- /Chapter 13/frame_demo.py: -------------------------------------------------------------------------------- 1 | # This program creates labels in two different frames. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | def __init__(self): 7 | # Create the main window widget. 8 | self.main_window = tkinter.Tk() 9 | 10 | # Create two frames, one for the top of the 11 | # window, and one for the bottom. 12 | self.top_frame = tkinter.Frame(self.main_window) 13 | self.bottom_frame = tkinter.Frame(self.main_window) 14 | 15 | # Create three Label widgets for the 16 | # top frame. 17 | self.label1 = tkinter.Label(self.top_frame, \ 18 | text='Winken') 19 | self.label2 = tkinter.Label(self.top_frame, \ 20 | text='Blinken') 21 | self.label3 = tkinter.Label(self.top_frame, \ 22 | text='Nod') 23 | 24 | # Pack the labels that are in the top frame. 25 | # Use the side='top' argument to stack them 26 | # one on top of the other. 27 | self.label1.pack(side='top') 28 | self.label2.pack(side='top') 29 | self.label3.pack(side='top') 30 | 31 | # Create three Label widgets for the 32 | # bottom frame. 33 | self.label4 = tkinter.Label(self.top_frame, \ 34 | text='Winken') 35 | self.label5 = tkinter.Label(self.top_frame, \ 36 | text='Blinken') 37 | self.label6 = tkinter.Label(self.top_frame, \ 38 | text='Nod') 39 | 40 | # Pack the labels that are in the bottom frame. 41 | # Use the side='left' argument to arrange them 42 | # horizontally from the left of the frame. 43 | self.label4.pack(side='left') 44 | self.label5.pack(side='left') 45 | self.label6.pack(side='left') 46 | 47 | # Yes, we have to pack the frames too! 48 | self.top_frame.pack() 49 | self.bottom_frame.pack() 50 | 51 | # Enter the tkinter main loop. 52 | tkinter.mainloop() 53 | 54 | # Create an instance of the MyGUI class. 55 | my_gui = MyGUI() 56 | 57 | -------------------------------------------------------------------------------- /Chapter 05/geometry.py: -------------------------------------------------------------------------------- 1 | # This program allows the user to choose various 2 | # geometry calculations from a menu. This program 3 | # imports the circle and rectangle modules. 4 | import circle 5 | import rectangle 6 | 7 | # Constants for the menu choices 8 | AREA_CIRCLE_CHOICE = 1 9 | CIRCUMFERENCE_CHOICE = 2 10 | AREA_RECTANGLE_CHOICE = 3 11 | PERIMETER_RECTANGLE_CHOICE = 4 12 | QUIT_CHOICE = 5 13 | 14 | # The main function. 15 | def main(): 16 | # The choice variable controls the loop 17 | # and holds the user's menu choice. 18 | choice = 0 19 | 20 | while choice != QUIT_CHOICE: 21 | # display the menu. 22 | display_menu() 23 | 24 | # Get the user's choice. 25 | choice = int(input('Enter your choice: ')) 26 | 27 | # Perform the selected action. 28 | if choice == AREA_CIRCLE_CHOICE: 29 | radius = float(input("Enter the circle's radius: ")) 30 | print('The area is', circle.area(radius)) 31 | elif choice == CIRCUMFERENCE_CHOICE: 32 | radius = float(input("Enter the circle's radius: ")) 33 | print('The circumference is', \ 34 | circle.circumference(radius)) 35 | elif choice == AREA_RECTANGLE_CHOICE: 36 | width = float(input("Enter the rectangle's width: ")) 37 | length = float(input("Enter the rectangle's length: ")) 38 | print('The area is', rectangle.area(width, length)) 39 | elif choice == PERIMETER_RECTANGLE_CHOICE: 40 | width = float(input("Enter the rectangle's width: ")) 41 | length = float(input("Enter the rectangle's length: ")) 42 | print('The perimeter is', \ 43 | rectangle.perimeter(width, length)) 44 | elif choice == QUIT_CHOICE: 45 | print('Exiting the program...') 46 | else: 47 | print('Error: invalid selection.') 48 | 49 | # The display_menu function displays a menu. 50 | def display_menu(): 51 | print(' MENU') 52 | print('1) Area of a circle') 53 | print('2) Circumference of a circle') 54 | print('3) Area of a rectangle') 55 | print('4) Perimeter of a rectangle') 56 | print('5) Quit') 57 | 58 | # Call the main function. 59 | main() 60 | -------------------------------------------------------------------------------- /Chapter 06/modify_coffee_records.py: -------------------------------------------------------------------------------- 1 | # This program allows the user to modify the quantity 2 | # in a record in the coffee.txt file. 3 | 4 | import os # Needed for the remove and rename functions 5 | 6 | def main(): 7 | # Create a bool variable to use as a flag. 8 | found = False 9 | 10 | # Get the search value and the new quantity. 11 | search = input('Enter a description to search for: ') 12 | new_qty = int(input('Enter the new quantity: ')) 13 | 14 | # Open the original coffee.txt file. 15 | coffee_file = open('coffee.txt', 'r') 16 | 17 | # Open the temporary file. 18 | temp_file = open('temp.txt', 'w') 19 | 20 | # Read the first record's description field. 21 | descr = coffee_file.readline() 22 | 23 | # Read the rest of the file. 24 | while descr != '': 25 | # Read the quantity field. 26 | qty = float(coffee_file.readline()) 27 | 28 | # Strip the \n from the description. 29 | descr = descr.rstrip('\n') 30 | 31 | # Write either this record to the temporary file, 32 | # or the new record if this is the one that is 33 | # to be modified. 34 | if descr == search: 35 | # Write the modified record to the temp file. 36 | temp_file.write(descr + '\n') 37 | temp_file.write(str(new_qty) + '\n') 38 | 39 | # Set the found flag to True. 40 | found = True 41 | else: 42 | # Write the original record to the temp file. 43 | temp_file.write(descr + '\n') 44 | temp_file.write(str(qty) + '\n') 45 | 46 | # Read the next description. 47 | descr = coffee_file.readline() 48 | 49 | # Close the coffee file and the temporary file. 50 | coffee_file.close() 51 | temp_file.close() 52 | 53 | # Delete the original coffee.txt file. 54 | os.remove('coffee.txt') 55 | 56 | # Rename the temporary file. 57 | os.rename('temp.txt', 'coffee.txt') 58 | 59 | # If the search value was not found in the file 60 | # display a message. 61 | if found: 62 | print('The file has been updated.') 63 | else: 64 | print('That item was not found in the file.') 65 | 66 | # Call the main function. 67 | main() 68 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_7/exercise9_7.py: -------------------------------------------------------------------------------- 1 | #7. World Series Winners 2 | #In this chapter’s source code folder (available on the Premium Companion Website at www. 3 | #pearsonglobaleditions.com/gaddis), you will find a text file named WorldSeriesWinners. 4 | #txt . This file contains a chronological list of the World Series’ winning teams from 1903 5 | #through 2009. The first line in the file is the name of the team that won in 1903, and the 6 | #last line is the name of the team that won in 2009. (Note the World Series was not played 7 | #in 1904 or 1994. There are entries in the file indicating this.) 8 | #Write a program that reads this file and creates a dictionary in which the keys are the names 9 | #of the teams, and each key’s associated value is the number of times the team has won the 10 | #World Series. The program should also create a dictionary in which the keys are the years, 11 | #and each key’s associated value is the name of the team that won that year. 12 | #The program should prompt the user for a year in the range of 1903 through 2009. It 13 | #should then display the name of the team that won the World Series that year, and the 14 | #number of times that team has won the World Series. 15 | 16 | def readfile(): 17 | infile = open('WorldSeries.txt','r') 18 | timeswon = dict() 19 | teamwon = dict() 20 | year = 1903 21 | team = infile.readline() 22 | dontskip = True 23 | while team != '': 24 | team = team.rstrip('\n') 25 | if team in timeswon: 26 | timeswon[team] += 1 27 | elif team.startswith('World'): 28 | dontskip = False 29 | else: 30 | timeswon[team] = 1 31 | if dontskip: 32 | teamwon[year] = team 33 | year += 1 34 | team = infile.readline() 35 | dontskip = True 36 | return teamwon,timeswon 37 | def main(): 38 | teamwon, timeswon = readfile() 39 | selection = int(input('Choose a year between 1903 and 2009: ')) 40 | while selection == 1904 or selection == 1994: 41 | print('There was no world cup in',selection) 42 | selection = int(input('Choose another year:')) 43 | print(teamwon[selection],'won the World Cup in',selection) 44 | print('In total they won,',timeswon[teamwon[selection]],'times.') 45 | main() -------------------------------------------------------------------------------- /Chapter 09/exercise9_10/index.txt: -------------------------------------------------------------------------------- 1 | 3D 12 13 15 2 | An 10 3 | Because 16 4 | For 11 5 | In 3 9 6 | OOP 9 7 | Object 8 8 | Reusability 8 9 | Sharon 11 10 | She 12 11 | The 4 6 12 | Tom, 14 13 | When 1 5 14 | a 5 10 11 12 12 12 14 16 16 15 | about 3 13 17 16 | access 1 17 | accidental 2 18 | addition 9 19 | addition, 3 20 | all 13 21 | also 6 9 22 | an 1 5 15 23 | and 1 9 12 14 16 24 | application 15 25 | architectural 15 26 | are 1 2 13 27 | attri- 1 28 | attributes 1 2 29 | attributes, 5 30 | been 10 31 | buildings. 15 32 | but 11 33 | butes 2 34 | by 10 11 35 | change. 7 36 | changes 5 37 | code 3 4 7 9 38 | code, 1 39 | coded 13 40 | computer 13 17 41 | computer’s 14 42 | corruption. 3 43 | data 1 1 2 5 9 44 | data. 4 6 45 | deadline 16 46 | deal 16 47 | developed 12 48 | display 15 49 | does 3 7 16 50 | edge 17 51 | encouraged 10 52 | example, 11 53 | firm, 15 54 | for 12 15 55 | format 3 56 | from 1 2 57 | graphics, 13 17 58 | great 16 59 | handle 14 60 | hardware. 14 61 | has 9 12 62 | he 6 16 63 | her 13 64 | hidden 1 65 | his 15 66 | however, 7 67 | images 15 68 | images. 12 69 | in 7 70 | interact 4 71 | interacts 7 72 | internal 4 5 73 | is 2 10 11 11 12 14 16 74 | its 11 75 | know 3 76 | knowl- 16 77 | knows 12 78 | lot 13 79 | math 12 80 | mathematical 14 81 | may 6 82 | methods 6 83 | methods, 2 7 84 | methods. 5 85 | modifies 6 86 | necessary 13 87 | need 3 11 88 | needs 4 15 89 | not 3 7 10 16 90 | object 3 10 10 91 | objects 12 13 92 | object’s 1 2 4 4 5 6 93 | of 4 5 9 9 10 12 13 15 16 94 | on 6 95 | only 4 96 | operate 6 97 | operations 14 98 | or 4 6 99 | outside 1 3 7 100 | perform 13 101 | possess 16 102 | problems 9 103 | program 15 104 | program, 10 105 | programmer 5 11 106 | programs 11 107 | properly 6 108 | protected 2 109 | rendering 12 110 | restricted 2 111 | reusability. 10 112 | separation, 9 113 | services. 11 114 | set 12 115 | she 6 116 | so 6 13 117 | solving 9 118 | stand-alone 10 119 | structure 4 5 120 | that 11 121 | the 1 2 2 3 3 3 4 4 5 6 6 7 9 9 10 13 14 122 | they 6 123 | tight 16 124 | to 1 2 3 4 9 13 15 125 | trend 10 126 | under 16 127 | use 9 128 | used 11 129 | video 14 130 | way 7 131 | which 7 132 | whiz 12 133 | who 11 14 134 | with 4 7 135 | working 16 136 | writing 14 137 | -------------------------------------------------------------------------------- /Chapter 13/kilo_converter.py: -------------------------------------------------------------------------------- 1 | # This program converts distances in kilometers 2 | # to miles. The result is displayed in an info 3 | # dialog box. 4 | 5 | import tkinter 6 | import tkinter.messagebox 7 | 8 | class KiloConverterGUI: 9 | def __init__(self): 10 | 11 | # Create the main window. 12 | self.main_window = tkinter.Tk() 13 | 14 | # Create two frames to group widgets. 15 | self.top_frame = tkinter.Frame() 16 | self.bottom_frame = tkinter.Frame() 17 | 18 | # Create the widgets for the top frame. 19 | self.prompt_label = tkinter.Label(self.top_frame, \ 20 | text='Enter a distance in kilometers:') 21 | self.kilo_entry = tkinter.Entry(self.top_frame, \ 22 | width=10) 23 | 24 | # Pack the top frame's widgets. 25 | self.prompt_label.pack(side='left') 26 | self.kilo_entry.pack(side='left') 27 | 28 | # Create the button widgets for the bottom frame. 29 | self.calc_button = tkinter.Button(self.bottom_frame, \ 30 | text='Convert', \ 31 | command=self.convert) 32 | self.quit_button = tkinter.Button(self.bottom_frame, \ 33 | text='Quit', \ 34 | command=self.main_window.destroy) 35 | # Pack the buttons. 36 | self.calc_button.pack(side='left') 37 | self.quit_button.pack(side='left') 38 | 39 | # Pack the frames. 40 | self.top_frame.pack() 41 | self.bottom_frame.pack() 42 | 43 | # Enter the tkinter main loop. 44 | tkinter.mainloop() 45 | 46 | # The convert method is a callback function for 47 | # the Calculate button. 48 | 49 | def convert(self): 50 | # Get the value entered by the user into the 51 | # kilo_entry widget. 52 | kilo = float(self.kilo_entry.get()) 53 | 54 | # Convert kilometers to miles. 55 | miles = kilo * 0.6214 56 | 57 | # Display the results in an info dialog box. 58 | tkinter.messagebox.showinfo('Results', \ 59 | str(kilo) + ' kilometers is equal to ' + \ 60 | str(miles) + ' miles.') 61 | 62 | # Create an instance of the KiloConverterGUI class. 63 | kilo_conv = KiloConverterGUI() 64 | -------------------------------------------------------------------------------- /Chapter 08/login.py: -------------------------------------------------------------------------------- 1 | # The get_login_name function accepts a first name, 2 | # last name, and ID number as arguments. It returns 3 | # a system login name. 4 | 5 | def get_login_name(first, last, idnumber): 6 | # Get the first three letters of the first name. 7 | # If the name is less than 3 characters, the 8 | # slice will return the entire first name. 9 | set1 = first[0 : 3] 10 | 11 | # Get the first three letters of the last name. 12 | # If the name is less than 3 characters, the 13 | # slice will return the entire last name. 14 | set2 = last[0 : 3] 15 | 16 | # Get the last three characters of the student ID. 17 | # If the ID number is less than 3 characters, the 18 | # slice will return the entire ID number. 19 | set3 = idnumber[-3 :] 20 | 21 | # Put the sets of characters together. 22 | login_name = set1 + set2 + set3 23 | 24 | # Return the login name. 25 | return login_name 26 | 27 | # The valid_password function accepts a password as 28 | # an argument and returns either true or false to 29 | # indicate whether the password is valid. A valid 30 | # password must be at least 7 characters in length, 31 | # have at least one uppercase letter, one lowercase 32 | # letter, and one digit. 33 | 34 | def valid_password(password): 35 | # Set the Boolean variables to false. 36 | correct_length = False 37 | has_uppercase = False 38 | has_lowercase = False 39 | has_digit = False 40 | 41 | # Begin the validation. Start by testing the 42 | # password's length. 43 | if len(password) >= 7: 44 | correct_length = True 45 | 46 | # Test each character and set the 47 | # appropriate flag when a required 48 | # character is found. 49 | for ch in password: 50 | if ch.isupper(): 51 | has_uppercase = True 52 | if ch.islower(): 53 | has_lowercase = True 54 | if ch.isdigit(): 55 | has_digit = True 56 | 57 | # Determine whether all of the requirements 58 | # are met. If they are, set is_valid to true. 59 | # Otherwise, set is_valid to false. 60 | if correct_length and has_uppercase and \ 61 | has_lowercase and has_digit: 62 | is_valid = True 63 | else: 64 | is_valid = False 65 | 66 | # Return the is_valid variable. 67 | return is_valid 68 | 69 | -------------------------------------------------------------------------------- /Chapter 10/exercise6/procedure.py: -------------------------------------------------------------------------------- 1 | # Write a class named Patient that has attributes for the following data: 2 | # • First name, middle name, and last name 3 | # • Address, city, state, and ZIP code 4 | # • Phone number 5 | # • Name and phone number of emergency contact 6 | # The Patient class’s _ _ init _ _ method should accept an argument for each 7 | # attribute. The Patient class should also have accessor and mutator methods for 8 | # each attribute. 9 | # Next, write a class named Procedure that represents a medical procedure that 10 | # has been performed on a patient. The Procedure class should have attributes for the following data: 11 | # • Name of the procedure 12 | # • Date of the procedure 13 | # • Name of the practitioner who performed the procedure 14 | # • Charges for the procedure 15 | # The Procedure class’s _ _ init _ _ method should accept an argument for each 16 | # attribute. The Procedure class should also have accessor and mutator methods for 17 | # each attribute. Next, write a program that creates an instance of the Patient 18 | # class, initialized with sample data. Then, create three instances of the 19 | # Procedure class, initialized with the following data: 20 | 21 | # The program should display the patient’s information, information about all 22 | # three of the procedures, and the total charges of the three procedures. 23 | 24 | class Procedure: 25 | def __init__(self,name,date,practitioner,charge): 26 | self.__name = name 27 | self.__date = date 28 | self.__practitioner = practitioner 29 | self.__charge = charge 30 | 31 | def get_name(self): 32 | return self.__name 33 | def get_date(self): 34 | return self.__date 35 | def get_practitioner(self): 36 | return self.__practitioner 37 | def get_charge(self): 38 | return self.__charge 39 | 40 | def set_name(self,name): 41 | self.__name = name 42 | def set_date(self,date): 43 | self.__date = date 44 | def set_practitioner(self,practitioner): 45 | self.__practitioner = practitioner 46 | def set_charge(self,charge): 47 | self.__charge = charge 48 | 49 | def __str__(self): 50 | return 'Name: ' + self.__name + \ 51 | '\nDate: ' + self.__date + \ 52 | '\nPractitioner: ' + self.__practitioner + \ 53 | '\nCharge: ' + self.__charge -------------------------------------------------------------------------------- /Chapter 10/exercise6/program.py: -------------------------------------------------------------------------------- 1 | # Write a class named Patient that has attributes for the following data: 2 | # • First name, middle name, and last name 3 | # • Address, city, state, and ZIP code 4 | # • Phone number 5 | # • Name and phone number of emergency contact 6 | # The Patient class’s _ _ init _ _ method should accept an argument for each 7 | # attribute. The Patient class should also have accessor and mutator methods for 8 | # each attribute. 9 | # Next, write a class named Procedure that represents a medical procedure that 10 | # has been performed on a patient. The Procedure class should have attributes for the following data: 11 | # • Name of the procedure 12 | # • Date of the procedure 13 | # • Name of the practitioner who performed the procedure 14 | # • Charges for the procedure 15 | # The Procedure class’s _ _ init _ _ method should accept an argument for each 16 | # attribute. The Procedure class should also have accessor and mutator methods for 17 | # each attribute. 18 | 19 | # Next, write a program that creates an instance of the Patient 20 | # class, initialized with sample data. 21 | 22 | # Then, create three instances of the 23 | # Procedure class, initialized with the following data: 24 | 25 | # The program should display the patient’s information, information about all 26 | # three of the procedures, and the total charges of the three procedures. 27 | 28 | import patient 29 | import procedure 30 | 31 | def createobjects(): 32 | patient0 = patient.Patient('John','Pika','Doe','Nice street 30', 33 | 'New York','NY','NY10503', 34 | '12341234','Yeadsgfd','13241235') 35 | 36 | procedure1 = procedure.Procedure('Laser αμφιβλιστροϊδή','5/5/1990', 37 | 'Dr. Μπαμπης Παπαδημητρίου','30.000 δρχ.') 38 | procedure2 = procedure.Procedure('Αφαιρεση Χολής', '10/9/2000','Dr Μαρία Τσακαλώτου', 39 | '500 ευρώ') 40 | procedure3 = procedure.Procedure('Βλαστοκυτταρική αναγέννηση', '23/12/2018', 41 | 'Dr Frankenstein', '50.000 ευρώ') 42 | return(patient0,procedure1,procedure2,procedure3) 43 | def main(): 44 | pat,proc1,proc2,proc3 = createobjects() 45 | print(pat) 46 | print() 47 | print(proc1) 48 | print() 49 | print(proc2) 50 | print() 51 | print(proc3) 52 | 53 | main() -------------------------------------------------------------------------------- /Chapter 07/WorldSeriesWinners.txt: -------------------------------------------------------------------------------- 1 | Boston Americans 2 | New York Giants 3 | Chicago White Sox 4 | Chicago Cubs 5 | Chicago Cubs 6 | Pittsburgh Pirates 7 | Philadelphia Athletics 8 | Philadelphia Athletics 9 | Boston Red Sox 10 | Philadelphia Athletics 11 | Boston Braves 12 | Boston Red Sox 13 | Boston Red Sox 14 | Chicago White Sox 15 | Boston Red Sox 16 | Cincinnati Reds 17 | Cleveland Indians 18 | New York Giants 19 | New York Giants 20 | New York Yankees 21 | Washington Senators 22 | Pittsburgh Pirates 23 | St. Louis Cardinals 24 | New York Yankees 25 | New York Yankees 26 | Philadelphia Athletics 27 | Philadelphia Athletics 28 | St. Louis Cardinals 29 | New York Yankees 30 | New York Giants 31 | St. Louis Cardinals 32 | Detroit Tigers 33 | New York Yankees 34 | New York Yankees 35 | New York Yankees 36 | New York Yankees 37 | Cincinnati Reds 38 | New York Yankees 39 | St. Louis Cardinals 40 | New York Yankees 41 | St. Louis Cardinals 42 | Detroit Tigers 43 | St. Louis Cardinals 44 | New York Yankees 45 | Cleveland Indians 46 | New York Yankees 47 | New York Yankees 48 | New York Yankees 49 | New York Yankees 50 | New York Yankees 51 | New York Giants 52 | Brooklyn Dodgers 53 | New York Yankees 54 | Milwaukee Braves 55 | New York Yankees 56 | Los Angeles Dodgers 57 | Pittsburgh Pirates 58 | New York Yankees 59 | New York Yankees 60 | Los Angeles Dodgers 61 | St. Louis Cardinals 62 | Los Angeles Dodgers 63 | Baltimore Orioles 64 | St. Louis Cardinals 65 | Detroit Tigers 66 | New York Mets 67 | Baltimore Orioles 68 | Pittsburgh Pirates 69 | Oakland Athletics 70 | Oakland Athletics 71 | Oakland Athletics 72 | Cincinnati Reds 73 | Cincinnati Reds 74 | New York Yankees 75 | New York Yankees 76 | Pittsburgh Pirates 77 | Philadelphia Phillies 78 | Los Angeles Dodgers 79 | St. Louis Cardinals 80 | Baltimore Orioles 81 | Detroit Tigers 82 | Kansas City Royals 83 | New York Mets 84 | Minnesota Twins 85 | Los Angeles Dodgers 86 | Oakland Athletics 87 | Cincinnati Reds 88 | Minnesota Twins 89 | Toronto Blue Jays 90 | Toronto Blue Jays 91 | Atlanta Braves 92 | New York Yankees 93 | Florida Marlins 94 | New York Yankees 95 | New York Yankees 96 | New York Yankees 97 | Arizona Diamondbacks 98 | Anaheim Angels 99 | Florida Marlins 100 | Boston Red Sox 101 | Chicago White Sox 102 | St. Louis Cardinals 103 | Boston Red Sox 104 | Philadelphia Phillies -------------------------------------------------------------------------------- /Chapter 13/radiobutton_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a group of Radiobutton widgets. 2 | 3 | import tkinter 4 | import tkinter.messagebox 5 | 6 | class MyGUI: 7 | def __init__(self): 8 | # Create the main window. 9 | self.main_window = tkinter.Tk() 10 | 11 | # Create two frames. One for the Radiobuttons 12 | # and another for the regular Button widgets. 13 | self.top_frame = tkinter.Frame(self.main_window) 14 | self.bottom_frame = tkinter.Frame(self.main_window) 15 | 16 | # Create an IntVar object to use with 17 | # the Radiobuttons. 18 | self.radio_var = tkinter.IntVar() 19 | 20 | # Set the intVar object to 1. 21 | self.radio_var.set(1) 22 | 23 | # Create the Radiobutton widgets in the top_frame. 24 | self.rb1 = tkinter.Radiobutton(self.top_frame, \ 25 | text='Option 1', variable=self.radio_var, \ 26 | value=1) 27 | self.rb2 = tkinter.Radiobutton(self.top_frame, \ 28 | text='Option 2', variable=self.radio_var, \ 29 | value=2) 30 | self.rb3 = tkinter.Radiobutton(self.top_frame, \ 31 | text='Option 3', variable=self.radio_var, \ 32 | value=3) 33 | 34 | # Pack the Radiobuttons. 35 | self.rb1.pack() 36 | self.rb2.pack() 37 | self.rb3.pack() 38 | 39 | # Create an OK button and a Quit button. 40 | self.ok_button = tkinter.Button(self.bottom_frame, \ 41 | text='OK', command=self.show_choice) 42 | self.quit_button = tkinter.Button(self.bottom_frame, \ 43 | text='Quit', command=self.main_window.destroy) 44 | 45 | # Pack the Buttons. 46 | self.ok_button.pack(side='left') 47 | self.quit_button.pack(side='left') 48 | 49 | # Pack the frames. 50 | self.top_frame.pack() 51 | self.bottom_frame.pack() 52 | 53 | # Start the mainloop. 54 | tkinter.mainloop() 55 | 56 | # The show_choice method is the callback function for the 57 | # OK button. 58 | 59 | def show_choice(self): 60 | tkinter.messagebox.showinfo('Selection', 'You selected option ' +\ 61 | str(self.radio_var.get())) 62 | 63 | # Create an instance of the MyGUI class. 64 | my_gui = MyGUI() 65 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_7/WorldSeries.txt: -------------------------------------------------------------------------------- 1 | Boston Americans 2 | World Series Not Played in 1904 3 | New York Giants 4 | Chicago White Sox 5 | Chicago Cubs 6 | Chicago Cubs 7 | Pittsburgh Pirates 8 | Philadelphia Athletics 9 | Philadelphia Athletics 10 | Boston Red Sox 11 | Philadelphia Athletics 12 | Boston Braves 13 | Boston Red Sox 14 | Boston Red Sox 15 | Chicago White Sox 16 | Boston Red Sox 17 | Cincinnati Reds 18 | Cleveland Indians 19 | New York Giants 20 | New York Giants 21 | New York Yankees 22 | Washington Senators 23 | Pittsburgh Pirates 24 | St. Louis Cardinals 25 | New York Yankees 26 | New York Yankees 27 | Philadelphia Athletics 28 | Philadelphia Athletics 29 | St. Louis Cardinals 30 | New York Yankees 31 | New York Giants 32 | St. Louis Cardinals 33 | Detroit Tigers 34 | New York Yankees 35 | New York Yankees 36 | New York Yankees 37 | New York Yankees 38 | Cincinnati Reds 39 | New York Yankees 40 | St. Louis Cardinals 41 | New York Yankees 42 | St. Louis Cardinals 43 | Detroit Tigers 44 | St. Louis Cardinals 45 | New York Yankees 46 | Cleveland Indians 47 | New York Yankees 48 | New York Yankees 49 | New York Yankees 50 | New York Yankees 51 | New York Yankees 52 | New York Giants 53 | Brooklyn Dodgers 54 | New York Yankees 55 | Milwaukee Braves 56 | New York Yankees 57 | Los Angeles Dodgers 58 | Pittsburgh Pirates 59 | New York Yankees 60 | New York Yankees 61 | Los Angeles Dodgers 62 | St. Louis Cardinals 63 | Los Angeles Dodgers 64 | Baltimore Orioles 65 | St. Louis Cardinals 66 | Detroit Tigers 67 | New York Mets 68 | Baltimore Orioles 69 | Pittsburgh Pirates 70 | Oakland Athletics 71 | Oakland Athletics 72 | Oakland Athletics 73 | Cincinnati Reds 74 | Cincinnati Reds 75 | New York Yankees 76 | New York Yankees 77 | Pittsburgh Pirates 78 | Philadelphia Phillies 79 | Los Angeles Dodgers 80 | St. Louis Cardinals 81 | Baltimore Orioles 82 | Detroit Tigers 83 | Kansas City Royals 84 | New York Mets 85 | Minnesota Twins 86 | Los Angeles Dodgers 87 | Oakland Athletics 88 | Cincinnati Reds 89 | Minnesota Twins 90 | Toronto Blue Jays 91 | World Series Not Played in 1994 92 | Toronto Blue Jays 93 | Atlanta Braves 94 | New York Yankees 95 | Florida Marlins 96 | New York Yankees 97 | New York Yankees 98 | New York Yankees 99 | Arizona Diamondbacks 100 | Anaheim Angels 101 | Florida Marlins 102 | Boston Red Sox 103 | Chicago White Sox 104 | St. Louis Cardinals 105 | Boston Red Sox 106 | Philadelphia Phillies -------------------------------------------------------------------------------- /Chapter 07/BoyNames.txt: -------------------------------------------------------------------------------- 1 | Jacob 2 | Michael 3 | Joshua 4 | Matthew 5 | Daniel 6 | Christopher 7 | Andrew 8 | Ethan 9 | Joseph 10 | William 11 | Anthony 12 | David 13 | Alexander 14 | Nicholas 15 | Ryan 16 | Tyler 17 | James 18 | John 19 | Jonathan 20 | Noah 21 | Brandon 22 | Christian 23 | Dylan 24 | Samuel 25 | Benjamin 26 | Zachary 27 | Nathan 28 | Logan 29 | Justin 30 | Gabriel 31 | Jose 32 | Austin 33 | Kevin 34 | Elijah 35 | Caleb 36 | Robert 37 | Thomas 38 | Jordan 39 | Cameron 40 | Jack 41 | Hunter 42 | Jackson 43 | Angel 44 | Isaiah 45 | Evan 46 | Isaac 47 | Mason 48 | Luke 49 | Jason 50 | Gavin 51 | Jayden 52 | Aaron 53 | Connor 54 | Aiden 55 | Aidan 56 | Kyle 57 | Juan 58 | Charles 59 | Luis 60 | Adam 61 | Lucas 62 | Brian 63 | Eric 64 | Adrian 65 | Nathaniel 66 | Sean 67 | Alex 68 | Carlos 69 | Bryan 70 | Ian 71 | Owen 72 | Jesus 73 | Landon 74 | Julian 75 | Chase 76 | Cole 77 | Diego 78 | Jeremiah 79 | Steven 80 | Sebastian 81 | Xavier 82 | Timothy 83 | Carter 84 | Wyatt 85 | Brayden 86 | Blake 87 | Hayden 88 | Devin 89 | Cody 90 | Richard 91 | Seth 92 | Dominic 93 | Jaden 94 | Antonio 95 | Miguel 96 | Liam 97 | Patrick 98 | Carson 99 | Jesse 100 | Tristan 101 | Alejandro 102 | Henry 103 | Victor 104 | Trevor 105 | Bryce 106 | Jake 107 | Riley 108 | Colin 109 | Jared 110 | Jeremy 111 | Mark 112 | Caden 113 | Garrett 114 | Parker 115 | Marcus 116 | Vincent 117 | Kaleb 118 | Kaden 119 | Brady 120 | Colton 121 | Kenneth 122 | Joel 123 | Oscar 124 | Josiah 125 | Jorge 126 | Cooper 127 | Ashton 128 | Tanner 129 | Eduardo 130 | Paul 131 | Edward 132 | Ivan 133 | Preston 134 | Maxwell 135 | Alan 136 | Levi 137 | Stephen 138 | Grant 139 | Nicolas 140 | Omar 141 | Dakota 142 | Alexis 143 | George 144 | Collin 145 | Eli 146 | Spencer 147 | Gage 148 | Max 149 | Cristian 150 | Ricardo 151 | Derek 152 | Micah 153 | Brody 154 | Francisco 155 | Nolan 156 | Ayden 157 | Dalton 158 | Shane 159 | Peter 160 | Damian 161 | Jeffrey 162 | Brendan 163 | Travis 164 | Fernando 165 | Peyton 166 | Conner 167 | Andres 168 | Javier 169 | Giovanni 170 | Shawn 171 | Braden 172 | Jonah 173 | Cesar 174 | Bradley 175 | Emmanuel 176 | Manuel 177 | Edgar 178 | Erik 179 | Mario 180 | Edwin 181 | Johnathan 182 | Devon 183 | Erick 184 | Wesley 185 | Oliver 186 | Trenton 187 | Hector 188 | Malachi 189 | Jalen 190 | Raymond 191 | Gregory 192 | Abraham 193 | Elias 194 | Leonardo 195 | Sergio 196 | Donovan 197 | Colby 198 | Marco 199 | Bryson 200 | Martin -------------------------------------------------------------------------------- /Chapter 07/GirlNames.txt: -------------------------------------------------------------------------------- 1 | Emily 2 | Madison 3 | Emma 4 | Olivia 5 | Hannah 6 | Abigail 7 | Isabella 8 | Samantha 9 | Elizabeth 10 | Ashley 11 | Alexis 12 | Sarah 13 | Sophia 14 | Alyssa 15 | Grace 16 | Ava 17 | Taylor 18 | Brianna 19 | Lauren 20 | Chloe 21 | Natalie 22 | Kayla 23 | Jessica 24 | Anna 25 | Victoria 26 | Mia 27 | Hailey 28 | Sydney 29 | Jasmine 30 | Julia 31 | Morgan 32 | Destiny 33 | Rachel 34 | Ella 35 | Kaitlyn 36 | Megan 37 | Katherine 38 | Savannah 39 | Jennifer 40 | Alexandra 41 | Allison 42 | Haley 43 | Maria 44 | Kaylee 45 | Lily 46 | Makayla 47 | Brooke 48 | Mackenzie 49 | Nicole 50 | Addison 51 | Stephanie 52 | Lillian 53 | Andrea 54 | Zoe 55 | Faith 56 | Kimberly 57 | Madeline 58 | Alexa 59 | Katelyn 60 | Gabriella 61 | Gabrielle 62 | Trinity 63 | Amanda 64 | Kylie 65 | Mary 66 | Paige 67 | Riley 68 | Jenna 69 | Leah 70 | Sara 71 | Rebecca 72 | Michelle 73 | Sofia 74 | Vanessa 75 | Jordan 76 | Angelina 77 | Caroline 78 | Avery 79 | Audrey 80 | Evelyn 81 | Maya 82 | Claire 83 | Autumn 84 | Jocelyn 85 | Ariana 86 | Nevaeh 87 | Arianna 88 | Jada 89 | Bailey 90 | Brooklyn 91 | Aaliyah 92 | Amber 93 | Isabel 94 | Danielle 95 | Mariah 96 | Melanie 97 | Sierra 98 | Erin 99 | Molly 100 | Amelia 101 | Isabelle 102 | Madelyn 103 | Melissa 104 | Jacqueline 105 | Marissa 106 | Shelby 107 | Angela 108 | Leslie 109 | Katie 110 | Jade 111 | Catherine 112 | Diana 113 | Aubrey 114 | Mya 115 | Amy 116 | Briana 117 | Sophie 118 | Gabriela 119 | Breanna 120 | Gianna 121 | Kennedy 122 | Gracie 123 | Peyton 124 | Adriana 125 | Christina 126 | Courtney 127 | Daniela 128 | Kathryn 129 | Lydia 130 | Valeria 131 | Layla 132 | Alexandria 133 | Natalia 134 | Angel 135 | Laura 136 | Charlotte 137 | Margaret 138 | Cheyenne 139 | Mikayla 140 | Miranda 141 | Naomi 142 | Kelsey 143 | Payton 144 | Ana 145 | Alicia 146 | Jillian 147 | Daisy 148 | Mckenzie 149 | Ashlyn 150 | Caitlin 151 | Sabrina 152 | Summer 153 | Ruby 154 | Rylee 155 | Valerie 156 | Skylar 157 | Lindsey 158 | Kelly 159 | Genesis 160 | Zoey 161 | Eva 162 | Sadie 163 | Alexia 164 | Cassidy 165 | Kylee 166 | Kendall 167 | Jordyn 168 | Kate 169 | Jayla 170 | Karen 171 | Tiffany 172 | Cassandra 173 | Juliana 174 | Reagan 175 | Caitlyn 176 | Giselle 177 | Serenity 178 | Alondra 179 | Lucy 180 | Kiara 181 | Bianca 182 | Crystal 183 | Erica 184 | Angelica 185 | Hope 186 | Chelsea 187 | Alana 188 | Liliana 189 | Brittany 190 | Camila 191 | Makenzie 192 | Veronica 193 | Lilly 194 | Abby 195 | Jazmin 196 | Adrianna 197 | Karina 198 | Delaney 199 | Ellie 200 | Jasmin -------------------------------------------------------------------------------- /Chapter 09/card_dealer.py: -------------------------------------------------------------------------------- 1 | # This program uses a dictionary as a deck of cards. 2 | 3 | def main(): 4 | # Create a deck of cards. 5 | deck = create_deck() 6 | 7 | # Get the number of cards to deal. 8 | num_cards = int(input('How many cards should I deal? ')) 9 | 10 | # Deal the cards. 11 | deal_cards(deck, num_cards) 12 | 13 | # The create_deck function returns a dictionary 14 | # representing a deck of cards. 15 | def create_deck(): 16 | # Create a dictionary with each card and its value 17 | # stored as key-value pairs. 18 | deck = {'Ace of Spades':1, '2 of Spades':2, '3 of Spades':3, 19 | '4 of Spades':4, '5 of Spades':5, '6 of Spades':6, 20 | '7 of Spades':7, '8 of Spades':8, '9 of Spades':9, 21 | '10 of Spades':10, 'Jack of Spades':10, 22 | 'Queen of Spades':10, 'King of Spades': 10, 23 | 24 | 'Ace of Hearts':1, '2 of Hearts':2, '3 of Hearts':3, 25 | '4 of Hearts':4, '5 of Hearts':5, '6 of Hearts':6, 26 | '7 of Hearts':7, '8 of Hearts':8, '9 of Hearts':9, 27 | '10 of Hearts':10, 'Jack of Hearts':10, 28 | 'Queen of Hearts':10, 'King of Hearts': 10, 29 | 30 | 'Ace of Clubs':1, '2 of Clubs':2, '3 of Clubs':3, 31 | '4 of Clubs':4, '5 of Clubs':5, '6 of Clubs':6, 32 | '7 of Clubs':7, '8 of Clubs':8, '9 of Clubs':9, 33 | '10 of Clubs':10, 'Jack of Clubs':10, 34 | 'Queen of Clubs':10, 'King of Clubs': 10, 35 | 36 | 'Ace of Diamonds':1, '2 of Diamonds':2, '3 of Diamonds':3, 37 | '4 of Diamonds':4, '5 of Diamonds':5, '6 of Diamonds':6, 38 | '7 of Diamonds':7, '8 of Diamonds':8, '9 of Diamonds':9, 39 | '10 of Diamonds':10, 'Jack of Diamonds':10, 40 | 'Queen of Diamonds':10, 'King of Diamonds': 10} 41 | 42 | # Return the deck. 43 | return deck 44 | 45 | # The deal_cards function deals a specified number of cards 46 | # from the deck. 47 | 48 | def deal_cards(deck, number): 49 | # Initialize an accumulator for the hand value. 50 | hand_value = 0 51 | 52 | # Make sure the number of cards to deal is not 53 | # greater than the number of cards in the deck. 54 | if number > len(deck): 55 | number = len(deck) 56 | 57 | # Deal the cards and accumulate their values. 58 | for count in range(number): 59 | card, value = deck.popitem() 60 | print(card) 61 | hand_value += value 62 | 63 | # Display the value of the hand. 64 | print('Value of this hand:', hand_value) 65 | 66 | # Call the main function. 67 | main() 68 | -------------------------------------------------------------------------------- /Chapter 09/exercise9_3/exercise9_3.py: -------------------------------------------------------------------------------- 1 | def encryption_rules(): 2 | encryption_dataset = dict() 3 | decryption_dataset = dict() 4 | characters = "!@#$%^&*()_+~`1234567890-={[}]:;>.<,?/AaBbCcFfRrDdTtGgYyHhJjUuKkOoLlp" 5 | letters = """AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz 1234567890’'"-.,""" 6 | for index in range(len(letters)): 7 | encryption_dataset[letters[index]] = characters[index] 8 | decryption_dataset[characters[index]] = letters[index] 9 | return encryption_dataset, decryption_dataset 10 | 11 | def main(): 12 | encryption_dataset, decryption_dataset = encryption_rules() 13 | filename = input('Select a txt file: ') 14 | print() 15 | choice = int(input('Press 1 to Encrypt, 2 to Decrypt: ')) 16 | if choice == 1: 17 | encrypt(filename,encryption_dataset) 18 | elif choice == 2: 19 | decrypt(filename,decryption_dataset) 20 | else: 21 | print('Not a valid choice') 22 | 23 | def encrypt(a_file,encryption_rule): 24 | # Open the infile and outfile. 25 | infile = open(a_file,'r', encoding='utf8') 26 | outfile = open('encrypted_' + a_file,'w', encoding='utf8') 27 | # Strip the contents of '\n' 28 | text = [] 29 | encrypted_text = [] 30 | for line in infile: 31 | text.append(line.rstrip('\n')) 32 | # For every line in the text file 33 | for line in text: 34 | encrypted_line = '' 35 | # For every character in each line. 36 | for char in line: 37 | # Find the character's value in the dictionary 38 | # and added to the encrypted text line. 39 | encrypted_line += str(encryption_rule.get(char)) 40 | encrypted_text.append(encrypted_line) 41 | for line in encrypted_text: 42 | outfile.write(line + '\n') 43 | infile.close() 44 | outfile.close() 45 | 46 | def decrypt(a_file,decryption_rules): 47 | # Open the infile and outfile 48 | infile = open('encrypted_' + a_file,'r', encoding='utf8') 49 | outfile = open('decrypted_' + a_file,'w', encoding='utf8') 50 | # Strip the contents of \n 51 | encrypted_text = [] 52 | decrypted_text = [] 53 | for line in infile: 54 | encrypted_text.append(line.rstrip('\n')) 55 | # For every line in the text file. 56 | for line in encrypted_text: 57 | decrypted_line = '' 58 | # For every character in each line. 59 | for char in line: 60 | # Find the character's value in the dictionary 61 | # and add it to the decrypted text line 62 | decrypted_line += str(decryption_rules.get(char)) 63 | decrypted_text.append(decrypted_line) 64 | for line in decrypted_text: 65 | outfile.write(line + '\n') 66 | infile.close() 67 | outfile.close() 68 | main() 69 | -------------------------------------------------------------------------------- /Chapter 13/checkbutton_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a group of Checkbutton widgets. 2 | 3 | import tkinter 4 | import tkinter.messagebox 5 | 6 | class MyGUI: 7 | def __init__(self): 8 | # Create the main window. 9 | self.main_window = tkinter.Tk() 10 | 11 | # Create two frames. One for the checkbuttons 12 | # and another for the regular Button widgets. 13 | self.top_frame = tkinter.Frame(self.main_window) 14 | self.bottom_frame = tkinter.Frame(self.main_window) 15 | 16 | # Create three IntVar objects to use with 17 | # the Checkbuttons. 18 | self.cb_var1 = tkinter.IntVar() 19 | self.cb_var2 = tkinter.IntVar() 20 | self.cb_var3 = tkinter.IntVar() 21 | 22 | # Set the intVar objects to 0. 23 | self.cb_var1.set(0) 24 | self.cb_var2.set(0) 25 | self.cb_var3.set(0) 26 | 27 | # Create the Checkbutton widgets in the top_frame. 28 | self.cb1 = tkinter.Checkbutton(self.top_frame, \ 29 | text='Option 1', variable=self.cb_var1) 30 | self.cb2 = tkinter.Checkbutton(self.top_frame, \ 31 | text='Option 2', variable=self.cb_var2) 32 | self.cb3 = tkinter.Checkbutton(self.top_frame, \ 33 | text='Option 3', variable=self.cb_var3) 34 | 35 | # Pack the Checkbuttons. 36 | self.cb1.pack() 37 | self.cb2.pack() 38 | self.cb3.pack() 39 | 40 | # Create an OK button and a Quit button. 41 | self.ok_button = tkinter.Button(self.bottom_frame, \ 42 | text='OK', command=self.show_choice) 43 | self.quit_button = tkinter.Button(self.bottom_frame, \ 44 | text='Quit', command=self.main_window.destroy) 45 | 46 | # Pack the Buttons. 47 | self.ok_button.pack(side='left') 48 | self.quit_button.pack(side='left') 49 | 50 | # Pack the frames. 51 | self.top_frame.pack() 52 | self.bottom_frame.pack() 53 | 54 | # Start the mainloop. 55 | tkinter.mainloop() 56 | 57 | # The show_choice method is the callback function for the 58 | # OK button. 59 | 60 | def show_choice(self): 61 | # Create a message string. 62 | self.message = 'You selected:\n' 63 | 64 | # Determine which Checkbuttons are selected and 65 | # build the message string accordingly. 66 | if self.cb_var1.get() == 1: 67 | self.message = self.message + '1\n' 68 | if self.cb_var2.get() == 1: 69 | self.message = self.message + '2\n' 70 | if self.cb_var3.get() == 1: 71 | self.message = self.message + '3\n' 72 | 73 | # Display the message in an info dialog box. 74 | tkinter.messagebox.showinfo('Selection', self.message) 75 | 76 | # Create an instance of the MyGUI class. 77 | my_gui = MyGUI() 78 | --------------------------------------------------------------------------------