├── chapter_09 ├── temp.dat ├── info.dat ├── coded.txt ├── plaintext.txt ├── uncoded.txt ├── name_email.dat ├── fileanalysis_1.txt ├── fileanalysis_2.txt ├── uniquewords.txt ├── q04.py ├── q01.py ├── unpickle_objects.py ├── pickle_objects.py └── q05.py ├── test.txt ├── chapter_06 ├── numbers.txt ├── coffee.txt ├── friends.txt ├── golf.txt ├── philosophers.txt ├── random_numbers.txt ├── sales.txt ├── video_times.txt ├── sales_data.txt ├── names.txt ├── employees.txt ├── division.py ├── q01.py ├── display_file.py ├── file_read.py ├── division2.py ├── gross_pay1.py ├── q02_1.py ├── file_write.py ├── read_sales2.py ├── line_read.py ├── gross_pay3.py ├── gross_pay2.py ├── display_file2.py ├── q08.py ├── read_numbers.py ├── strip_newline.py ├── write_names.py ├── q07.py ├── sales_report4.py ├── sales_report2.py ├── sales_report3.py ├── save_running_times.py ├── write_numbers.py ├── write_sales.py ├── q04_1.py ├── read_sales.py ├── show_coffee_records.py ├── q04.py ├── q05.py ├── q03.py ├── q02.py ├── sales_report1.py ├── read_running_times.py ├── q06.py ├── save_emp_records.py ├── read_emp_records.py ├── add_coffee_record.py └── q09.py ├── chapter_07 ├── cities.txt ├── numberlist.txt ├── answers.txt ├── charge_accounts.txt ├── write_list.py ├── writelines.py ├── USPopulation.txt ├── insert_list.py ├── total_list.py ├── write_number_list.py ├── read_list.py ├── average_list.py ├── in_list.py ├── read_number_list.py ├── q02.py ├── total_function.py ├── random_numbers.py ├── sales_list.py ├── remove_item.py ├── q01.py ├── q04.py ├── list_append.py ├── barista_pay.py ├── q10.py ├── q06.py ├── index_list.py ├── return_list.py └── q05.py ├── book_cover.jpg ├── chapter_10 ├── contacts.dat ├── employees.dat ├── cellphones.dat ├── __pycache__ │ ├── q08.cpython-37.pyc │ ├── coin.cpython-37.pyc │ ├── contact.cpython-37.pyc │ ├── bankaccount.cpython-37.pyc │ ├── cellphone.cpython-37.pyc │ └── bankaccount2.cpython-37.pyc ├── q02.py ├── coin_demo4.py ├── customer.py ├── car.py ├── coin_argument.py ├── q01_1.py ├── q01.py ├── q04_1.py ├── cell_phone_test.py ├── coin.py ├── q05_1.py ├── servicequote.py ├── q04_2.py ├── bankaccount.py ├── account_test2.py ├── q05.py ├── coin_demo5.py ├── q02_1.py ├── q07_1.py ├── bankaccount2.py ├── pickle_cellphone.py ├── q04.py ├── employee.py ├── unpickle_cellphone.py └── q08.py ├── chapter_02 ├── comment1.py ├── string_variable.py ├── double_quotes.py ├── q07.py ├── comment2.py ├── variable_demo.py ├── variable_demo2.py ├── variable_demo4.py ├── simple_math.py ├── q03.py ├── q09.py ├── variable_demo3.py ├── q05.py ├── dollar_display.py ├── string_input.py ├── apostrophe.py ├── sale_price.py ├── test_score_average.py ├── no_formatting.py ├── time_converter.py ├── q02.py ├── q10.py ├── q11.py ├── q08.py ├── input.py ├── future_value.py ├── q01.py ├── algorithm_workbench.py ├── q06.py ├── print_function_details.py ├── q04.py ├── columns.py └── q12.py ├── chapter_04 ├── simple_loop3.py ├── simple_loop4.py ├── simple_loop1.py ├── simple_loop2.py ├── triangle_pattern.py ├── q02.py ├── stair_step_pattern.py ├── q06.py ├── rectangular_pattern.py ├── q09.py ├── q10.py ├── temperature.py ├── gross_pay.py ├── q01.py ├── q13.py ├── q08.py ├── squares.py ├── infinite.py ├── q14.py ├── q04.py ├── user_squares.py ├── speed_converter.py ├── sum_numbers.py ├── q11.py ├── user_squares2.py ├── q07.py ├── retail_no_validation.py ├── q12.py ├── commission.py ├── property_tax.py ├── q05.py ├── retail_with_validation.py ├── q03.py └── test_score_averages.py ├── chapter_05 ├── global1.py ├── function_demo.py ├── random_numbers3.py ├── global2.py ├── bad_local.py ├── random_numbers.py ├── q10.py ├── random_numbers2.py ├── boolean_values.py ├── pass_arg.py ├── multiple_args.py ├── two_functions.py ├── q01.py ├── q03.py ├── change_me.py ├── square_root.py ├── string_args.py ├── keywords_string_args.py ├── circle.py ├── q14.py ├── rectangle.py ├── hypotenuse.py ├── birds.py ├── q19.py ├── dice.py ├── q13.py ├── total_ages.py ├── q12.py ├── keyword_args.py ├── coin_toss.py ├── q07.py ├── q05.py ├── q06.py ├── cups_to_ounces.py ├── q11.py ├── q16.py ├── q18.py ├── q09.py ├── retirement.py ├── sale_price.py ├── q02.py ├── q17.py └── q20.py ├── chapter_08 ├── concatenate.py ├── q03_1.py ├── string_split.py ├── repetition_operator.py ├── q12.py ├── split_date.py ├── validate_password.py ├── q08.py ├── generate_login.py ├── q01.py ├── count_Ts.py ├── q11.py ├── string_test.py ├── q02.py ├── q05.py ├── q09.py └── q03.py ├── chapter_03 ├── password.py ├── q06.py ├── q05.py ├── sort_names.py ├── grader.py ├── q03.py ├── loan_qualifier2.py ├── loan_qualifier3.py ├── q15.py ├── q10.py ├── test_average.py ├── q04.py ├── q01.py ├── loan_qualifier.py ├── q14.py ├── auto_repair_payroll.py ├── q02.py ├── q11.py ├── q13.py ├── q15_1.py ├── q07.py └── q09.py ├── chapter_13 ├── empty_window1.py ├── empty_window2.py ├── hello_world.py ├── hello_world2.py └── hello_world3.py ├── chapter_12 ├── endless_recursion.py ├── recursive.py ├── fibonacci.py ├── q08.py ├── factorial.py ├── gcd.py ├── sum.py ├── q01.py ├── q06.py ├── q02.py ├── towers_of_hanoi.py ├── q03.py └── q05.py ├── .project ├── .pydevproject ├── chapter_11 ├── car_demo.py ├── polymorphism_demo.py ├── q01_demo.py ├── q03_demo.py ├── polymorphism_demo2.py ├── q02_demo.py └── q03.py └── README.md /chapter_09/temp.dat: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test.txt: -------------------------------------------------------------------------------- 1 | test for gitbash -------------------------------------------------------------------------------- /chapter_06/numbers.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 10 -------------------------------------------------------------------------------- /chapter_06/coffee.txt: -------------------------------------------------------------------------------- 1 | Sumatra Medium Roast 2 | 25.0 3 | -------------------------------------------------------------------------------- /chapter_06/friends.txt: -------------------------------------------------------------------------------- 1 | Mehmet 2 | Mustafa 3 | Tayfun 4 | -------------------------------------------------------------------------------- /chapter_07/cities.txt: -------------------------------------------------------------------------------- 1 | New York 2 | Boston 3 | Atlanta 4 | Dallas 5 | -------------------------------------------------------------------------------- /chapter_06/golf.txt: -------------------------------------------------------------------------------- 1 | Tay 2 | 1000 3 | Mus 4 | 2000 5 | Kaa 6 | 3000 7 | -------------------------------------------------------------------------------- /chapter_06/philosophers.txt: -------------------------------------------------------------------------------- 1 | John Locke 2 | David Hume 3 | Edmund Burke 4 | -------------------------------------------------------------------------------- /chapter_06/random_numbers.txt: -------------------------------------------------------------------------------- 1 | 152 2 | 252 3 | 183 4 | 422 5 | 317 6 | -------------------------------------------------------------------------------- /chapter_07/numberlist.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 8 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /book_cover.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/book_cover.jpg -------------------------------------------------------------------------------- /chapter_06/sales_data.txt: -------------------------------------------------------------------------------- 1 | 24987.62 2 | 26978.97 3 | 32589.45 4 | 31978.47 5 | 22781.76 6 | 29871.44 -------------------------------------------------------------------------------- /chapter_09/info.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_09/info.dat -------------------------------------------------------------------------------- /chapter_09/coded.txt: -------------------------------------------------------------------------------- 1 | >1j1d1b 29i 1713 7929 k5b m5 8li 2 | m5 29i fid1e 7929 b1i45j35j9e5, 3 | 2l 81ji5k 29q9d... -------------------------------------------------------------------------------- /chapter_09/plaintext.txt: -------------------------------------------------------------------------------- 1 | Yasamak bir agac gibi tek ve hur 2 | ve bir orman gibi kardescesine, 3 | bu hasret bizim... -------------------------------------------------------------------------------- /chapter_09/uncoded.txt: -------------------------------------------------------------------------------- 1 | Yasamak bir agac gibi tek ve hur 2 | ve bir orman gibi kardescesine, 3 | bu hasret bizim... -------------------------------------------------------------------------------- /chapter_10/contacts.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/contacts.dat -------------------------------------------------------------------------------- /chapter_10/employees.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/employees.dat -------------------------------------------------------------------------------- /chapter_09/name_email.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_09/name_email.dat -------------------------------------------------------------------------------- /chapter_10/cellphones.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/cellphones.dat -------------------------------------------------------------------------------- /chapter_06/names.txt: -------------------------------------------------------------------------------- 1 | Julia Roberts 2 | Michael Scott 3 | Kevin Malone 4 | Jim Halpert 5 | Pam Halpert 6 | Dwight Schrute -------------------------------------------------------------------------------- /chapter_09/fileanalysis_1.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_09/fileanalysis_1.txt -------------------------------------------------------------------------------- /chapter_09/fileanalysis_2.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_09/fileanalysis_2.txt -------------------------------------------------------------------------------- /chapter_02/comment1.py: -------------------------------------------------------------------------------- 1 | # This program displays a person's 2 | # name and address 3 | print("Mehmet Icer") 4 | print("Dallas, TX.") -------------------------------------------------------------------------------- /chapter_02/string_variable.py: -------------------------------------------------------------------------------- 1 | # Create variables to reference two strings. 2 | first_name="Mehmet" 3 | last_name="Icer" 4 | print(first_name, last_name) -------------------------------------------------------------------------------- /chapter_10/__pycache__/q08.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/__pycache__/q08.cpython-37.pyc -------------------------------------------------------------------------------- /chapter_10/__pycache__/coin.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/__pycache__/coin.cpython-37.pyc -------------------------------------------------------------------------------- /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_10/__pycache__/contact.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/__pycache__/contact.cpython-37.pyc -------------------------------------------------------------------------------- /chapter_10/__pycache__/bankaccount.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/__pycache__/bankaccount.cpython-37.pyc -------------------------------------------------------------------------------- /chapter_10/__pycache__/cellphone.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/__pycache__/cellphone.cpython-37.pyc -------------------------------------------------------------------------------- /chapter_10/__pycache__/bankaccount2.cpython-37.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mmustafaicer/StartingOutWithPython/HEAD/chapter_10/__pycache__/bankaccount2.cpython-37.pyc -------------------------------------------------------------------------------- /chapter_02/double_quotes.py: -------------------------------------------------------------------------------- 1 | print('Mehmet Mustafa Icer') 2 | print("1004 Cleveland St") 3 | print('Denton, TX. 76201') 4 | #You can use single-quote marks or double in Python. -------------------------------------------------------------------------------- /chapter_07/answers.txt: -------------------------------------------------------------------------------- 1 | A 2 | C 3 | A 4 | A 5 | D 6 | B 7 | C 8 | A 9 | C 10 | A 11 | C 12 | D 13 | A 14 | C 15 | C 16 | C 17 | B 18 | B 19 | D 20 | A -------------------------------------------------------------------------------- /chapter_04/simple_loop3.py: -------------------------------------------------------------------------------- 1 | # this program also demonstrates a sample for 2 | # loop that uses a list of strings. 3 | 4 | for name in ["Winken", "Blinken", "Nod"]: 5 | print(name) -------------------------------------------------------------------------------- /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.") -------------------------------------------------------------------------------- /chapter_04/simple_loop1.py: -------------------------------------------------------------------------------- 1 | # this program demonstrates a sample for loop that uses a list of numbers 2 | 3 | print("I will display the numbers 1 through 5.") 4 | for num in [1,2,3,4,5]: 5 | print (num) 6 | -------------------------------------------------------------------------------- /chapter_04/simple_loop2.py: -------------------------------------------------------------------------------- 1 | # this program also demonstrates a sample for loop that uses 2 | # 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) -------------------------------------------------------------------------------- /chapter_09/uniquewords.txt: -------------------------------------------------------------------------------- 1 | Python is an interpreted, high-level, general-purpose programming language. 2 | Python is a language therefore. Trial, unique, stack, overflow. 3 | Trial trial trial. Triathlon. Maybe maybe maybe -------------------------------------------------------------------------------- /chapter_02/q07.py: -------------------------------------------------------------------------------- 1 | # Miles-per-Gallon 2 | 3 | miles=float(input("Enter the number of miles driven: ")) 4 | gas=float(input("Enter the amount of gallons of gas used: ")) 5 | 6 | mpg=miles//gas 7 | 8 | print("Your car's mpg is ", mpg) -------------------------------------------------------------------------------- /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() # this is for new line. -------------------------------------------------------------------------------- /chapter_02/comment2.py: -------------------------------------------------------------------------------- 1 | print("Mehmet Icer") # Print name 2 | print("Dallas TX") # Print street name or address 3 | # Variables 4 | width=10 5 | length=5 6 | print (width) # Variable name in parantheses 7 | print (length) -------------------------------------------------------------------------------- /chapter_02/variable_demo.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a variable 2 | room = 503 3 | print ("I am staying in room number " + str(room)) # You can make number string then concatenate 4 | 5 | # Or 6 | 7 | print("I am staying in room number") 8 | print(room) -------------------------------------------------------------------------------- /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('Top speed is '+ str(top_speed)) 7 | print('The distance traveled is ' + str(distance)) -------------------------------------------------------------------------------- /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 | 7 | def show_value(): 8 | print(my_value) 9 | 10 | # call the show_value function 11 | show_value() -------------------------------------------------------------------------------- /chapter_02/variable_demo4.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates variable reassignment 2 | dollars=2.75 3 | print("I have", dollars, "in my account.") 4 | dollars=99.95 5 | print("But now, I have", dollars, "in my account.") # We changed or reassigned the dollars variable. 6 | -------------------------------------------------------------------------------- /chapter_05/function_demo.py: -------------------------------------------------------------------------------- 1 | # this program demonstrates a function. 2 | # first, we define a function named message. 3 | 4 | def message(): 5 | print("My name is Mehmet.") 6 | print("Author of this program.") 7 | 8 | # call the message function 9 | message() -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_04/q02.py: -------------------------------------------------------------------------------- 1 | # calories burned 2 | 3 | cal_per_min=4.2 4 | 5 | # print the headers 6 | print("Minutes\t\tCalories") 7 | print("------------------------") 8 | 9 | for mins in range(10,31,5): 10 | calories=mins*cal_per_min 11 | print(mins,"\t\t",calories) -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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_02/simple_math.py: -------------------------------------------------------------------------------- 1 | # Assign a value to the salary variable. 2 | salary=float(input("What is your salary?: ")) 3 | bonus=float(input("What is your bonus?: ")) 4 | 5 | # Calculate the total pay by adding salary 6 | total_pay=salary+bonus 7 | print("Your total pay is", total_pay) -------------------------------------------------------------------------------- /chapter_04/stair_step_pattern.py: -------------------------------------------------------------------------------- 1 | # this program displays a stair step pattern 2 | num_steps=6 3 | 4 | # create the repetition structure. 5 | for r in range(num_steps): 6 | for c in range(r): 7 | print(' ', end='') # do not forget to put a space between ' ' 8 | print("#") -------------------------------------------------------------------------------- /chapter_02/q03.py: -------------------------------------------------------------------------------- 1 | # Land Calculation 2 | 3 | area=float(input("Enter the total square feet in your land: ")) 4 | acres=float(area/43560) 5 | 6 | # If you want to have 2 digits after decimal, you need to put that argument in format parantheses. 7 | print("Your area is", format(acres, '.2f'), "acres") -------------------------------------------------------------------------------- /chapter_02/q09.py: -------------------------------------------------------------------------------- 1 | # Celcius to Fahrenheit Temperature Converter 2 | 3 | # ask user to enter a temperature in Celcius. 4 | celcius=float(input("Please enter the temperature in Celcius: ")) 5 | fahrenheit=(9/5)*celcius+32 6 | 7 | print(celcius, "celcius equals to", fahrenheit, "fahrenheit degrees.") -------------------------------------------------------------------------------- /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 | def show_number(): 9 | print("The number you entered is", number) 10 | 11 | # call the main function 12 | main() -------------------------------------------------------------------------------- /chapter_02/variable_demo3.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a variable. 2 | room=503 3 | print('I am staying in room number', room) 4 | 5 | # or again you can concatenate. Since room is integer, you have to make it string first using 6 | # str function 7 | 8 | print("I am staying in room number " + str(room)) -------------------------------------------------------------------------------- /chapter_03/password.py: -------------------------------------------------------------------------------- 1 | # This program compares two strings 2 | # Get a password from the user. 3 | password=input("Please enter the password: ") 4 | 5 | # Determine whether the correct password was entered. 6 | if password=="prospero": 7 | print("Password accepted") 8 | else: 9 | print("Wrong password.") -------------------------------------------------------------------------------- /chapter_04/q06.py: -------------------------------------------------------------------------------- 1 | # celcius to fahrenheit table 2 | 3 | # print headings 4 | print("Celcius\t\tFahrenheit") 5 | print("--------------------------") 6 | 7 | # create loop structure 8 | for c in range(0,21,1): 9 | fahrenheit=((9/5)*c)+32 10 | print(c,"\t\t", format(fahrenheit, ".2f")) 11 | -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_02/q05.py: -------------------------------------------------------------------------------- 1 | # Distance Traveled 2 | 3 | speed=70 4 | 5 | # The distance in 6 hours 6 | print("The distance the car will travel in 6 hours is", speed*6, "miles") 7 | print("The distance the car will travel in 10 hours is", speed*10, "miles") 8 | print("The distance the car will travel in 15 hours is", speed*15, "miles") -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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"), sep='') 7 | 8 | # We use sep='', so there will be a no space between $ sign and amount of dollar. -------------------------------------------------------------------------------- /chapter_02/string_input.py: -------------------------------------------------------------------------------- 1 | # Get the first name 2 | first_name=input("What is your first name: ") 3 | # Get the last name 4 | last_name=input("What is your last name: ") 5 | print("Hello", first_name, last_name) 6 | 7 | 8 | hours=int(input("How many hours do you work?: ")) # Every input is stored as string. So we use int 9 | 10 | print(hours*4) -------------------------------------------------------------------------------- /chapter_04/rectangular_pattern.py: -------------------------------------------------------------------------------- 1 | # this program displays a rectangular pattern of asterisks 2 | rows=int(input("How many rows?: ")) 3 | cols=int(input("How many columns?: ")) 4 | print() 5 | for r in range(rows): 6 | for c in range(cols): 7 | print("*", end='') # end states that " do not go to new line. put asterisk beside it. 8 | print() -------------------------------------------------------------------------------- /chapter_02/apostrophe.py: -------------------------------------------------------------------------------- 1 | print("Don't fear") 2 | print("I'm here!") 3 | 4 | #Display quote 5 | print('Your assignment is to read "Hamlet" by tomorrow.') 6 | #Triple quotes also work 7 | print("""I'm reading "Hamlet" tonight.""") 8 | print("""One 9 | Two 10 | Three""") 11 | 12 | #Checkpoint 13 | print("Python's the best") 14 | print('The cat said "meow"') -------------------------------------------------------------------------------- /chapter_05/q10.py: -------------------------------------------------------------------------------- 1 | # feet to inches 2 | 3 | def main(): 4 | print("This is a Feet to Inches Converter program.") 5 | feet=float(input("Enter the feet to be converted: ")) 6 | feet_to_inches(feet) 7 | 8 | def feet_to_inches(feet): 9 | inches=feet*12 10 | print(feet, "feet equals to", inches, "inches.") 11 | 12 | main() -------------------------------------------------------------------------------- /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 | # call the main function 12 | main() -------------------------------------------------------------------------------- /chapter_12/endless_recursion.py: -------------------------------------------------------------------------------- 1 | # this program has a recursive function. 2 | 3 | def main(): 4 | i=1 # to track of how many times it appeard. 5 | message(i) 6 | 7 | def message(i): 8 | print(i) 9 | print("This is a recursive function.") 10 | i+=1 11 | message(i) 12 | 13 | # call the main function. 14 | main() -------------------------------------------------------------------------------- /chapter_02/sale_price.py: -------------------------------------------------------------------------------- 1 | # Get the original price 2 | original_price=float(input("What is the price of this product: ")) 3 | # Calculate the discounted amount 4 | discounted=original_price*(0.2) 5 | # Subtract the discounted amount from original price. 6 | final_price=original_price-discounted 7 | # Show the final price 8 | print("The price after %20 discount is", final_price ) 9 | -------------------------------------------------------------------------------- /chapter_04/q09.py: -------------------------------------------------------------------------------- 1 | # ocean levels 2 | # set an accumulator 3 | yearly_increase=0 4 | 5 | start_year=2019 6 | end_year=2044 7 | 8 | # print headings 9 | print("Years\t\tOcean Rise in mm") 10 | print("--------------------------------") 11 | 12 | for y in range (start_year, end_year+1, 1): 13 | yearly_increase+=1.6 14 | print(y, "\t\t", format(yearly_increase, ".1f")) -------------------------------------------------------------------------------- /chapter_05/boolean_values.py: -------------------------------------------------------------------------------- 1 | def is_even(number): 2 | if (number%2)==0: 3 | status=True 4 | else: 5 | status=False 6 | return status 7 | 8 | number=int(input("Enter a number: ")) 9 | 10 | if is_even(number): # means that if the result of this function is True. 11 | print("The number is even") 12 | else: 13 | print("The number is odd.") -------------------------------------------------------------------------------- /chapter_04/q10.py: -------------------------------------------------------------------------------- 1 | # tuition increase 2 | 3 | tuition=8000 4 | increase_rate=0.03 5 | 6 | # print headings 7 | print("Years\t\tTuition") 8 | print("---------------------------") 9 | 10 | # create loop structure 11 | 12 | for y in range(1,6,1): 13 | tuition_inc=tuition*increase_rate 14 | tuition+=tuition_inc 15 | print(y, "\t\t$", format(tuition, ",.2f"), sep='') 16 | -------------------------------------------------------------------------------- /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 | 11 | def show_double(number): 12 | result=number*2 13 | print(result) 14 | 15 | # call the main function 16 | main() -------------------------------------------------------------------------------- /chapter_04/temperature.py: -------------------------------------------------------------------------------- 1 | # get the substance's temperature 2 | 3 | sub_temp=float(input("Enter the temperature of substance: ")) 4 | max_temp=102.5 5 | 6 | while sub_temp>max_temp: 7 | print("Please turn down the thermostat and wait 5 minutes.") 8 | sub_temp=float(input("Enter the temperature of substance again: ")) 9 | print("The temperature is acceptable. Check it again in 15 minutes.") -------------------------------------------------------------------------------- /chapter_08/q03_1.py: -------------------------------------------------------------------------------- 1 | # import datetime library 2 | from datetime import datetime 3 | 4 | # get the date from the user 5 | date_input = input('Enter a date(mm/dd/yyyy): ') 6 | 7 | # strip the time as month, day, year 8 | date_object = datetime.strptime(date_input, '%m/%d/%Y') 9 | 10 | # print the full month name (%B), day and year. 11 | print(date_object.strftime('%B %d, %Y')) 12 | -------------------------------------------------------------------------------- /chapter_02/test_score_average.py: -------------------------------------------------------------------------------- 1 | # Calculate the average score of three different exam 2 | # Get the exam grades 3 | exam1=float(input("What is the score for exam 1: ")) 4 | exam2=float(input("What is the score for exam 2: ")) 5 | exam3=float(input("What is the score for exam 3: ")) 6 | 7 | # Get the average of three exams. 8 | average=(exam1+exam2+exam3)/3 9 | 10 | print("Your average is ", average) -------------------------------------------------------------------------------- /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 | 11 | def show_sum(num1,num2): 12 | result=num1+num2 13 | print(result) 14 | 15 | # call the main function 16 | main() -------------------------------------------------------------------------------- /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. it is a list now 11 | print(word_list) 12 | 13 | # call the main function 14 | main() -------------------------------------------------------------------------------- /chapter_13/empty_window2.py: -------------------------------------------------------------------------------- 1 | # this program displays an empty window. 2 | import tkinter 3 | 4 | class MyGUI: 5 | def __init__(self): 6 | # create the main window widget. 7 | self.main_windows=tkinter.Tk() 8 | 9 | # enter the tkinter main loop. 10 | tkinter.mainloop() 11 | 12 | # create an instance of the MyGUI class. 13 | my_gui=MyGUI() -------------------------------------------------------------------------------- /chapter_04/gross_pay.py: -------------------------------------------------------------------------------- 1 | # this program displays gross pay 2 | # get the number of hours workerd 3 | 4 | hours=int(input("Enter the hours worked this week: ")) 5 | 6 | # get the hourly pay rate 7 | pay_rate=float(input("Enter the hourly pay rate: ")) 8 | 9 | # calculate the gross pay. 10 | gross_pay=hours*pay_rate 11 | 12 | # display the gross pay. 13 | print("Gross pay: $", format(gross_pay, ",.2f"), sep='') -------------------------------------------------------------------------------- /chapter_05/two_functions.py: -------------------------------------------------------------------------------- 1 | # this program has two functions. first 2 | # we define main function 3 | 4 | def main(): 5 | print("I have a message for you.") 6 | message() 7 | print("Goodbye!") 8 | 9 | # next we define the message function. 10 | def message(): 11 | print("I am Mehmet.") 12 | print("The author of this program.") 13 | 14 | # call the main function to execute 15 | main() -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_05/q01.py: -------------------------------------------------------------------------------- 1 | # kilometer converter 2 | 3 | def main(): 4 | # ask user to enter a distance in km 5 | km=int(input("Enter a distance in km: ")) 6 | convert(km) 7 | 8 | # now create convert function 9 | def convert(kilometer): 10 | miles=kilometer*0.6214 11 | print(kilometer, "km is equal to", format(miles, ",.2f"), "miles.") 12 | 13 | # call main function 14 | main() -------------------------------------------------------------------------------- /chapter_03/q06.py: -------------------------------------------------------------------------------- 1 | # magic dates 2 | 3 | # ask user for date 4 | month=int(input("Enter a month (1-12): ")) 5 | day=int(input("Enter a day (1-30): ")) 6 | year=int(input("Enter a year (two-digit): ")) 7 | 8 | # magic date calculation. 9 | 10 | if month*day==year: 11 | print(month, "/", day, "/",year, " is a magic date.", sep="") 12 | else: 13 | print(month, "/", day, "/",year, " is NOT a magic date.", sep="") -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_04/q01.py: -------------------------------------------------------------------------------- 1 | # bug collector 2 | 3 | # set an accumulator for bugs 4 | bugs_total=0.0 5 | 6 | # set repetition structure. 7 | for day in range(5): # it is five days. 8 | print("Enter the collected bugs for day", day+1, end='') 9 | bugs=int(input(": ")) 10 | # add bugs to accumulator 11 | bugs_total+=bugs 12 | # display the total bugs 13 | print() 14 | print("The total bugs collected: ", bugs_total) -------------------------------------------------------------------------------- /chapter_03/q05.py: -------------------------------------------------------------------------------- 1 | # mass and weight. 2 | 3 | # ask user to enter a mass for an object 4 | mass=float(input("Please enter the mass the object's mass: ")) 5 | 6 | # calculate the weight using formula given 7 | weight=mass*9.8 8 | 9 | # print outputs 10 | print("Weight is", format(weight, ".2f"), "newtons.") 11 | if weight>500: 12 | print("It is too heavy!") 13 | elif weight<100: 14 | print("It is too light!") 15 | 16 | -------------------------------------------------------------------------------- /chapter_06/q01.py: -------------------------------------------------------------------------------- 1 | # file display 2 | 3 | def main(): 4 | 5 | # open the numbers.txt file. Make sure it exists. 6 | myfile=open("numbers.txt", "r") 7 | 8 | # this loop reads every line on that file. 9 | for line in myfile: 10 | line=float(line) 11 | print(line) 12 | 13 | # close the file 14 | myfile.close() 15 | 16 | # call the main function 17 | main() -------------------------------------------------------------------------------- /chapter_05/q03.py: -------------------------------------------------------------------------------- 1 | # how much insurance 2 | 3 | def main(): 4 | cost_house=float(input("Enter the replacement cost of a building: ")) 5 | print() 6 | insurance(cost_house) 7 | 8 | # write insurance function 9 | def insurance(cost_house): 10 | insurance_amount=cost_house*0.80 11 | print("Your insurance amount is $", format(insurance_amount, ",.2f")) 12 | 13 | # call the main function 14 | main() -------------------------------------------------------------------------------- /chapter_05/change_me.py: -------------------------------------------------------------------------------- 1 | # this program demonstrates what happens 2 | # when you 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/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", format(square_root, ",.1f")) 13 | 14 | # call the main function 15 | main() -------------------------------------------------------------------------------- /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() 8 | print("Your name reversed is ", end='') 9 | reverse_name(first_name, last_name) 10 | 11 | def reverse_name(first,last): 12 | print(last,first) 13 | 14 | # call the main function 15 | main() -------------------------------------------------------------------------------- /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_04/q13.py: -------------------------------------------------------------------------------- 1 | # pattern 1 2 | # print the following using loop structures. 3 | 4 | # ******* 5 | # ****** 6 | # ***** 7 | # **** 8 | # *** 9 | # ** 10 | # * 11 | 12 | # we will use descending for in range structure 13 | # do not forget to use "-1" to show it will decrease one by one 14 | for r in range(8,1,-1): 15 | for c in range(r,1,-1): 16 | print("*", end='') # using end to command that "Do not go to new line" 17 | print() -------------------------------------------------------------------------------- /chapter_03/sort_names.py: -------------------------------------------------------------------------------- 1 | # this program compares strings with the < operator 2 | # Get two names from the user 3 | 4 | name1=input("Enter a name(last name first): ") 5 | name2=input("Enter another name(last name first): ") 6 | 7 | # Display the names in alphabetical order. 8 | print() 9 | print("Here are the names, listed alphabetically.") 10 | 11 | if name1=0: 8 | total+=user_number 9 | print("Enter a positive number to continue or negative number to end ", end='') 10 | user_number=int(input(":")) 11 | 12 | print() 13 | print("The total of your number entered is", total) 14 | -------------------------------------------------------------------------------- /chapter_05/keywords_string_args.py: -------------------------------------------------------------------------------- 1 | # this program demonstrates passing two strings as 2 | # key words 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 ", end='') 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() -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | StartingOutWithPython 4 | 5 | 6 | 7 | 8 | 9 | org.python.pydev.PyDevBuilder 10 | 11 | 12 | 13 | 14 | 15 | org.python.pydev.pythonNature 16 | 17 | 18 | -------------------------------------------------------------------------------- /.pydevproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | /${PROJECT_DIR_NAME} 5 | 6 | python interpreter 7 | Default 8 | 9 | -------------------------------------------------------------------------------- /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.0 5 | print("The monthly payment is", monthly_payment) 6 | # As you see float numbers have 12 digits after decimal point. 7 | 8 | # we have a format function we can use. 2f: 2 means two digits ; f means float 9 | print() 10 | print("The monthly payment is", format(monthly_payment, '.2f')) 11 | -------------------------------------------------------------------------------- /chapter_02/time_converter.py: -------------------------------------------------------------------------------- 1 | # Get the total seconds from user 2 | total_seconds=float(input("Enter a number of seconds: ")) 3 | 4 | hours=total_seconds//3600 # Because there is 3600 seconds in 1 hour. We do not want fraction. 5 | minutes=(total_seconds//60)%60 6 | seconds=total_seconds%60 7 | 8 | # Display the results 9 | print("Here is the time in hours, minutes, and seconds:") 10 | print("Hours: ", hours) 11 | print("Minutes: ", minutes) 12 | print("Seconds: ", seconds) -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /chapter_08/q12.py: -------------------------------------------------------------------------------- 1 | # pig latin 2 | 3 | def main(): 4 | # ask user to enter a sentence 5 | string=input("Please enter a string: ").upper() 6 | # split each word using whitespace 7 | word_list=string.split() 8 | 9 | # process each word one by one 10 | for word in word_list: 11 | # concatenate strings using [index] 12 | print(word[1:],word[0], "AY ", sep="", end="") 13 | 14 | # call the main function 15 | main() -------------------------------------------------------------------------------- /chapter_05/q14.py: -------------------------------------------------------------------------------- 1 | # kinetic energy 2 | 3 | def main(): 4 | mass=float(input("Please enter the object's mass in kg: ")) 5 | velocity=float(input("Please enter the object's velocity in meters per second: ")) 6 | kin_energy=kinetic_energy(mass,velocity) 7 | print("The total kinetic energy is", format(kin_energy, ",.2f"), "joule") 8 | 9 | def kinetic_energy(m,v): 10 | kin_energy=(1/2)*m*v**2 11 | return kin_energy 12 | 13 | main() 14 | 15 | -------------------------------------------------------------------------------- /chapter_02/q02.py: -------------------------------------------------------------------------------- 1 | # Sales Prediction 2 | 3 | # Ask user to enter the projected amount of total sales 4 | total_sales_projected=float(input("What is the projected amount of total sales?: ")) 5 | 6 | # Display the annual profit. %23 of total sales 7 | profit=total_sales_projected*0.23 8 | # Format to use comma to show thousands in dollars by using format function. 9 | # Use sep= argument to write after $ sign. 10 | print("The expected annual profit is $", format(profit, ',.1f'), sep='') -------------------------------------------------------------------------------- /chapter_02/q10.py: -------------------------------------------------------------------------------- 1 | # Ingredient Adjuster 2 | 3 | # Ask user how many cookies he or she wants 4 | cookie=int(input("Enter the amount of cookies you want: ")) 5 | 6 | # Find the ingredients (Simple ratio and proportion 7 | 8 | sugar=cookie*(1.5)/48 9 | butter=cookie*(1)/48 10 | flour=cookie*(2.75)/48 11 | 12 | print() 13 | print("You will need following ingredients: ") 14 | print(sugar, "cups of sugar") 15 | print(butter, "cups of butter") 16 | print(flour, "cups of flour") 17 | 18 | -------------------------------------------------------------------------------- /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 | # backlash \t is for tab space remember from chapter 2 11 | # range function does not use last number. See it does not print 11. 12 | for number in range (1,11): 13 | square=number**2 14 | print(number, '\t', square) -------------------------------------------------------------------------------- /chapter_02/q11.py: -------------------------------------------------------------------------------- 1 | # Male and Female Percentages 2 | 3 | # Ask user for male and female numbers 4 | 5 | male=int(input("Please enter the number of males in the class: ")) 6 | female=int(input("Please enter the number of females in the class: ")) 7 | total=male+female 8 | 9 | # Calculate the percentages. 10 | p_male=(male/total)*100 11 | p_female=(female/total)*100 12 | 13 | # Display the data. 14 | print() 15 | print("Male is %", p_male, sep='') 16 | print("Female is %", p_female, sep='') 17 | -------------------------------------------------------------------------------- /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 | sales=float(input("Enter the amount of sales: ")) 8 | comm_rate=float(input("Enter the commission rate: ")) 9 | 10 | # calculate commission 11 | commission=sales*comm_rate 12 | 13 | # display the commission 14 | print("The commission is $", format(commission, ',.2f'), sep='') -------------------------------------------------------------------------------- /chapter_04/q14.py: -------------------------------------------------------------------------------- 1 | # pattern 2 | 3 | # there are 6 rows 4 | rows=6 5 | 6 | # create loop structure 7 | # there will be a 6 six row 8 | # there will be 0 space between #'s. And 1 space bw #'s. and so and so forth. 9 | 10 | for r in range(0,rows,1): 11 | print("#", end="") # every line starts with #. So, every outer loop will have this command. 12 | for col in range(0,r,1): # this is for space between two # signs. 13 | print(" ", end="") 14 | print("#") 15 | 16 | -------------------------------------------------------------------------------- /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/2014" 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() -------------------------------------------------------------------------------- /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 | 13 | def perimeter(width,length): 14 | return 2*(width+length) -------------------------------------------------------------------------------- /chapter_02/q08.py: -------------------------------------------------------------------------------- 1 | # Tip, Tax, and Total 2 | 3 | # ask user to enter the charge for the food 4 | price_def=float(input("Please enter the charge for the food: ")) 5 | 6 | tip=price_def*0.18 7 | sales_tax=price_def*0.07 8 | 9 | total=price_def+tip+sales_tax 10 | 11 | # Display the data 12 | 13 | print() 14 | print("Your subtotal is", price_def) 15 | print("Your tip amount is $", tip, sep='') 16 | print("Your sales tax is $", format(sales_tax, ".2f"), sep='') 17 | print() 18 | print("Your total is $", total, sep='') -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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() 8 | print("Here is the data you entered.") 9 | print("Name: ", name) 10 | print("Age: ", age) 11 | print("Income: ", income) 12 | 13 | # Checkpint 2.17 and 2.18 14 | last_name=input("Please enter your last name: ") 15 | sales_week=float(input("Please enter the amount of sales for the week: ")) -------------------------------------------------------------------------------- /chapter_04/q04.py: -------------------------------------------------------------------------------- 1 | # distance traveled 2 | 3 | # ask user to enter the speed of the vehicle in mph 4 | 5 | speed=int(input("Please enter the speed of vehicle in mph: ")) 6 | hours=int(input("Please enter hours that you traveled on that speed: ")) 7 | 8 | # print the headings for table-like view 9 | print("Hour\t\tDistance Traveled") 10 | print("____________________________") 11 | 12 | # for structure. Hours will start from 1. 13 | for hour in range(1, hours+1): 14 | distance=hour*speed 15 | print(hour,"\t\t", distance) -------------------------------------------------------------------------------- /chapter_04/user_squares.py: -------------------------------------------------------------------------------- 1 | # this program uses a loop to display a 2 | # table of numbers and their squares 3 | 4 | # get the ending limits 5 | print("This program display a list of numbers") 6 | print("(starting at) 1 and their squares.") 7 | end=int(input("How high should I go?: ")) 8 | print() 9 | 10 | # print the table headings 11 | print("Number\tSquare") 12 | print("---------------") 13 | 14 | # print the numbers and their squares. 15 | for num in range (1,end+1): 16 | square=num**2 17 | print(num,"\t", square) -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_02/future_value.py: -------------------------------------------------------------------------------- 1 | # Get the desired future value 2 | future=float(input("Enter the desired future value: ")) 3 | # Get the annual interest rate 4 | rate=float(input("What is the annual interest rate?: ")) 5 | # Get the number of years that the money will sit in the account 6 | years=float(input("Enter the number of years the money will grow: ")) 7 | # Calculate the amount that will have to be deposited 8 | present_amount=future/((1+rate)**years) 9 | 10 | 11 | print("You need to deposit" \ 12 | , present_amount, "dollars.") -------------------------------------------------------------------------------- /chapter_06/file_read.py: -------------------------------------------------------------------------------- 1 | # this program reads and displays the contents of 2 | # the philosophers.txt file 3 | 4 | def main(): 5 | # open a file named philosophers.txt 6 | infile=open("philosophers.txt", "r") 7 | 8 | # read the file's contents and assign to a variable. 9 | file_contents=infile.read() 10 | 11 | # close the file 12 | infile.close() 13 | 14 | # print the data that was read into memory 15 | print(file_contents) 16 | 17 | # call the main function 18 | main() -------------------------------------------------------------------------------- /chapter_02/q01.py: -------------------------------------------------------------------------------- 1 | # Personal Information 2 | 3 | name=input("Please enter your name: ") 4 | address=input("Please enter your address with city, state and ZIP code: ") 5 | tel=input("Please enter your phone number: ") 6 | col_major=input("Please enter your college major: ") 7 | 8 | 9 | print() 10 | # Show the information that is provided by user. 11 | print("Your information is below: ") 12 | 13 | print("Your name: ", name) 14 | print("Your address is ", address) 15 | print("Your phone number is ",tel) 16 | print("Your major is ", col_major) -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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 0, 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() -------------------------------------------------------------------------------- /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 is $", format(gross_pay, ",.2f"), sep="") 15 | 16 | # call the main function. 17 | main() -------------------------------------------------------------------------------- /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_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() -------------------------------------------------------------------------------- /chapter_03/grader.py: -------------------------------------------------------------------------------- 1 | # get the grades from user 2 | a_score=90 3 | b_score=80 4 | c_score=70 5 | d_score=60 6 | 7 | # get a test score from the user 8 | score=int(input("Enter your test score: ")) 9 | 10 | # Determine the grade 11 | # Be careful on indentation. 12 | if score>=a_score: 13 | print("Your grade is A.") 14 | else: 15 | if score>=b_score: 16 | print("Your grade is B.") 17 | else: 18 | if score>=c_score: 19 | print("Your grade is C.") 20 | else: 21 | print("Your grade is D.") -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_06/q02_1.py: -------------------------------------------------------------------------------- 1 | # file head display shorter version 2 | 3 | def main(): 4 | 5 | # ask user to enter a filename. 6 | filename=input("Enter the file name: ") 7 | 8 | # open that file name 9 | infile=open(filename, "r") 10 | 11 | # read the 5 lines from the file. 12 | for i in range(5): 13 | line=infile.readline() 14 | line=line.rstrip("\n") 15 | print(line) 16 | 17 | # close the file. 18 | infile.close() 19 | 20 | # call the main function 21 | main() -------------------------------------------------------------------------------- /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") # to write on file; it should be string. 13 | 14 | # close the file. 15 | outfile.close() 16 | 17 | # call the main function 18 | main() -------------------------------------------------------------------------------- /chapter_08/validate_password.py: -------------------------------------------------------------------------------- 1 | # this program gets a password from the user and validates it. 2 | 3 | import login 4 | 5 | def main(): 6 | # get a password from the user. 7 | password=input("Enter your password: ") 8 | 9 | # validate the password 10 | while not login.valid_password(password): 11 | print("That password is not valid.") 12 | password=input("Enter your password again: ") 13 | 14 | print("SUCCESS: That is a valid password.") 15 | 16 | # call the main function 17 | main() -------------------------------------------------------------------------------- /chapter_08/q08.py: -------------------------------------------------------------------------------- 1 | # sentence capitalizer 2 | 3 | def main(): 4 | # get the string from user 5 | user_string=input("Enter a string: ") 6 | 7 | # after each exclamation mark, it gets capitalized 8 | sentence=user_string.split(".") 9 | print(sentence) 10 | 11 | # strip for deleting whitespace after. 12 | # sentences start like "asdsad. New sentence" there is one space after dot 13 | for i in sentence: 14 | print(i.strip().capitalize() + ". ", end="") 15 | 16 | # call the main function 17 | main() -------------------------------------------------------------------------------- /chapter_04/speed_converter.py: -------------------------------------------------------------------------------- 1 | # this program converts the speeds 60 kph through 2 | # 130 kph (in 10 kph increments) to mph 3 | 4 | start_speed=60 # Starting speed 5 | end_speed=131 # Ending speed (remember range does not take last digit so, increment by 1) 6 | increment=10 7 | conversion=0.6214 8 | 9 | # print the table headings 10 | print("KPH\tMPH") 11 | print("------------------") 12 | 13 | for kph in range (start_speed, end_speed, increment): 14 | # calculate conversion 15 | mph=kph*conversion 16 | print(kph,"\t", format(mph, ".1f")) -------------------------------------------------------------------------------- /chapter_04/sum_numbers.py: -------------------------------------------------------------------------------- 1 | # this program calculates the sum of a series 2 | # of numbers entered by the user. 3 | 4 | max_num=5 # maximum number. 5 | # initialize an accumulator variable. 6 | total=0.0 7 | 8 | # explain what we are doing 9 | print("This program calculates the sum of") 10 | print(max, "numbers you will enter.") 11 | 12 | # get the numbers and accumulate them 13 | for counter in range(max_num): 14 | number=int(input("Enter a number: ")) 15 | total=total+number 16 | 17 | # display the total of the numbers. 18 | print("The total is", total) -------------------------------------------------------------------------------- /chapter_04/q11.py: -------------------------------------------------------------------------------- 1 | # calculating the factorial of a number 2 | 3 | # ask user to enter a nonnegative number 4 | user_number=int(input("Enter a nonnegative integer to calculate factorial: ")) 5 | 6 | # set an accumulator 7 | factorial=1 8 | 9 | # check if user entered a negative number and prompt user to enter again. 10 | while user_number<0: 11 | user_number=int(input("ERROR: Please enter a positive number.")) 12 | 13 | # factorial part. 14 | for n in range(1,user_number+1, 1): 15 | factorial*=n 16 | print() 17 | print("Factorial of", user_number, "is", factorial) 18 | 19 | -------------------------------------------------------------------------------- /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 ending limits 5 | print("This program display a list of numbers") 6 | print("(starting at) 1 and their squares.") 7 | 8 | start=int(input("Enter the starting number: ")) 9 | end=int(input("Enter the ending number: ")) 10 | print() 11 | 12 | # print the table headings 13 | print("Number\tSquare") 14 | print("---------------") 15 | 16 | # print the numbers and their squares. 17 | for num in range (start,end+1): 18 | square=num**2 19 | print(num,"\t", square) -------------------------------------------------------------------------------- /chapter_03/q03.py: -------------------------------------------------------------------------------- 1 | # age classifier 2 | 3 | # ask user to enter an age 4 | 5 | age=int(input("Please enter your age: ")) 6 | 7 | # determine the category of age 8 | 9 | if age<=1 and age>0: 10 | print("The category is infant!") 11 | elif age>1 and age<13: 12 | print("The category is child!") 13 | elif age>=13 and age<20: 14 | print("The category is teenager!") 15 | elif age>=20: 16 | print("The category is adult!") 17 | else: # in case user enters a number less than 0, it will give an error. Age can't be 0 and less than 0. 18 | print("The age you entered is not valid.") -------------------------------------------------------------------------------- /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 | # it will be in the same folder as of Python file. 6 | outfile=open("philosophers.txt", "w") 7 | 8 | # write the names of three philosophers 9 | # to the file 10 | outfile.write("John Locke\n") # \n for new line 11 | outfile.write("David Hume\n") 12 | outfile.write("Edmund Burke\n") 13 | 14 | # close the file 15 | outfile.close() 16 | 17 | # call the main function 18 | main() -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_12/fibonacci.py: -------------------------------------------------------------------------------- 1 | # this program uses recursion to print number 2 | # from the Fibonacci series. 3 | 4 | def main(): 5 | print("The first 10 numbers in the \ 6 | 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 | 14 | def fib(n): 15 | if n==0: 16 | return 0 17 | if n==1: 18 | return 1 19 | if n>1: 20 | return fib(n-1) + fib(n-2) 21 | 22 | # call the main function. 23 | main() -------------------------------------------------------------------------------- /chapter_04/q07.py: -------------------------------------------------------------------------------- 1 | # pennies for pay 2 | # updated 3 | 4 | # ask user number of days 5 | days=int(input("Enter the number of days to calculate: ")) 6 | 7 | # print headings 8 | print() 9 | print("Days\tSalary in $") 10 | print("-----------------------------") 11 | 12 | # set an accumulator and create loop structure 13 | salary=0.01 # the first day is one penny 14 | total=0 15 | for d in range(1,days+1,1): 16 | print(d,"\t$", salary) 17 | total += salary 18 | salary*=2 19 | 20 | # show total 21 | print() 22 | print("The total earnings is ${}".format(total, ",.2f")) 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /chapter_02/algorithm_workbench.py: -------------------------------------------------------------------------------- 1 | # 1 2 | height=int(input("Enter your height in cm: ")) 3 | # 2 4 | fav_color=input("Enter your favorite color: ") 5 | # 3 6 | b=a+2 7 | a=4*b 8 | b=a/3.14 9 | a=b-8 10 | # 4 11 | # a = 12 , b=4, c=2.0, d=6, e=2 12 | 13 | #5 14 | 15 | total=10+14 16 | 17 | # 6 18 | 19 | due=total-down_payment 20 | 21 | # 7 22 | 23 | total=subtotal*0.15 24 | 25 | # 8 the answer is 11 26 | 27 | # 9 the answer is 5 28 | 29 | # 10 30 | print(sales, '.2f') 31 | 32 | # 11 33 | 34 | number = 1234567.456 35 | print(format(number, '12,.1f')) 36 | 37 | # 12 it will display George@John@Paul@Ringo -------------------------------------------------------------------------------- /chapter_12/q08.py: -------------------------------------------------------------------------------- 1 | # Ackermann's Function 2 | 3 | def main(): 4 | # ask user for data 5 | m=int(input("Enter a positive integer for m: ")) 6 | n=int(input("Enter a positive integer for n: ")) 7 | 8 | # call the function 9 | result=ackermann(m,n) 10 | print(result) 11 | 12 | # define the function. algorithm given in the book 13 | def ackermann(m,n): 14 | if m==0: 15 | return n+1 16 | if n==0: 17 | return ackermann(m-1, 1) 18 | else: 19 | return ackermann(m-1, ackermann(m, n-1)) 20 | 21 | # call the main function 22 | main() -------------------------------------------------------------------------------- /chapter_03/loan_qualifier2.py: -------------------------------------------------------------------------------- 1 | # this program determines whether a bank customer qualifies for a loan. 2 | min_salary=30000. # The minimum annual salary 3 | min_years=2 # The minimum years on the job 4 | 5 | # get the customer's salary 6 | salary=float(input("Enter your annual salary: ")) 7 | # get the years on job 8 | years=int(input("Enter the number of years employed: ")) 9 | # Determine whether the customer qualifies 10 | 11 | if salary>=min_salary and years>=min_years: 12 | print("Congratulations! You qualify for a loan.") 13 | else: 14 | print("You do not qualify for a loan.") 15 | 16 | -------------------------------------------------------------------------------- /chapter_03/loan_qualifier3.py: -------------------------------------------------------------------------------- 1 | # this program determines whether a bank customer qualifies for a loan. 2 | min_salary=30000. # The minimum annual salary 3 | min_years=2 # The minimum years on the job 4 | 5 | # get the customer's salary 6 | salary=float(input("Enter your annual salary: ")) 7 | # get the years on job 8 | years=int(input("Enter the number of years employed: ")) 9 | # Determine whether the customer qualifies 10 | 11 | if salary>=min_salary or years>=min_years: 12 | print("Congratulations! You qualify for a loan.") 13 | else: 14 | print("You do not qualify for a loan.") 15 | 16 | -------------------------------------------------------------------------------- /chapter_10/q02.py: -------------------------------------------------------------------------------- 1 | # Car Class 2 | 3 | class Car: 4 | def __init__(self,year_model, make, speed): 5 | self.__year_model=year_model 6 | self.__make=make 7 | self.__speed=0 8 | 9 | def accelerate(self, speed): 10 | self.__speed+=5 11 | 12 | def brake(self, speed): 13 | self.__speed-=5 14 | 15 | def get_speed(self, speed): 16 | return self.__speed 17 | 18 | # write a __str__ method for object's state 19 | def __str__(self): 20 | return "The speed is " + str(self.__speed) # this will be **STRING.** -------------------------------------------------------------------------------- /chapter_06/line_read.py: -------------------------------------------------------------------------------- 1 | # this program reads the contents of the 2 | # philosophers.txt file one line at a time. 3 | 4 | def main(): 5 | # open a file named philosophers.txt. 6 | infile=open("philosophers.txt", "r") 7 | 8 | # read the three lines from the file 9 | line1=infile.readline() 10 | line2=infile.readline() 11 | line3=infile.readline() 12 | 13 | # close the file 14 | infile.close() 15 | 16 | # print the data that was read into memory 17 | print(line1) 18 | print(line2) 19 | print(line3) 20 | 21 | # call the main function 22 | main() -------------------------------------------------------------------------------- /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 system 3 | # 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() -------------------------------------------------------------------------------- /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_08/q01.py: -------------------------------------------------------------------------------- 1 | # initials. 2 | 3 | def main(): 4 | # get the first, middle, and last name from user. 5 | name=get_name() 6 | 7 | # using split method separate them into first, middle, and last. 8 | name_separated=name.split() 9 | 10 | # display the result. 11 | print("Your initials") 12 | 13 | # read every piece as a separate with for loop. 14 | for ch in name_separated: 15 | print(ch[0], ".", sep='', end="") 16 | 17 | def get_name(): 18 | name=input("Enter your full name: ") 19 | return name 20 | 21 | # call the main function 22 | main() 23 | -------------------------------------------------------------------------------- /chapter_02/q06.py: -------------------------------------------------------------------------------- 1 | # Sales Tax 2 | 3 | # get the amount of purchase 4 | 5 | purchase=float(input("Enter the amount of purchase: ")) 6 | 7 | # Calculate state and county sales tax 8 | state_tax=purchase*0.05 9 | county_tax=purchase*0.025 10 | total_tax=state_tax+county_tax 11 | 12 | # Display the results. 13 | 14 | print() 15 | print("Your purchase amount is $", purchase, sep='') 16 | print("Your state tax is $", format(state_tax, ".2f"), sep='') 17 | print("Your county tax is $", format(county_tax, ".2f"), sep='') 18 | print("Your total tax is $", total_tax, sep='') 19 | print() 20 | print("Your total is $", purchase+total_tax, sep='') -------------------------------------------------------------------------------- /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 variabel 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() -------------------------------------------------------------------------------- /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=86400: 10 | days=user_seconds//86400 11 | print("There are", days, "days in", user_seconds, "seconds.") 12 | elif user_seconds>=3600: 13 | hours=user_seconds//3600 14 | print("There are", hours, "hours in", user_seconds, "seconds.") 15 | elif user_seconds>=60: 16 | minutes=user_seconds//60 17 | print("There are", minutes, "minutes in ", user_seconds, "seconds.") 18 | else: 19 | print("ERROR: Invalid Response.") -------------------------------------------------------------------------------- /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 wholesale cost: ")) 10 | 11 | # calculate the retail price. 12 | retail=wholesale*mark_up 13 | 14 | # display the retail price. 15 | print("Retail price: $", format(retail, ",.2f"), sep="") 16 | 17 | # do this again? 18 | another=input("Do you have another item? Enter 'y' for yes") -------------------------------------------------------------------------------- /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 | # 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 | except ValueError as err: 17 | print(err) 18 | 19 | # call the main function 20 | main() -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /chapter_07/average_list.py: -------------------------------------------------------------------------------- 1 | # this program calculates the average of the 2 | # values 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() -------------------------------------------------------------------------------- /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: # it returns True if found in the list. 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() -------------------------------------------------------------------------------- /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 indexb: 14 | print("The number", a,"is greater than number",b) 15 | else: 16 | print("The number", b,"is greater than number", a) 17 | 18 | # call the main function 19 | main() 20 | -------------------------------------------------------------------------------- /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 per period 11 | # and the number of periods 12 | 13 | def show_interest(principal, rate, periods): 14 | interest=principal*rate*periods 15 | print("The simple interest will be $", format(interest, ",.2f"), sep='') 16 | 17 | # call the main function 18 | main() -------------------------------------------------------------------------------- /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 | # call the main function. 17 | main() 18 | 19 | 20 | # My version 21 | 22 | #def main(): 23 | # coin_toss() 24 | 25 | #def coin_toss(): 26 | # for i in range(10): 27 | # number=random.randint(1,2) 28 | # if number==1: 29 | # print("Heads") 30 | # else: 31 | # print("Tails") 32 | #main() -------------------------------------------------------------------------------- /chapter_05/q07.py: -------------------------------------------------------------------------------- 1 | # stadium seating 2 | 3 | def main(): 4 | # ask user to enter number of seats sold for each class. 5 | class_a_numbers=int(input("How many Class A tickets are sold?: ")) 6 | class_b_numbers=int(input("How many Class B tickets are sold?: ")) 7 | class_c_numbers=int(input("How many Class C tickets are sold?: ")) 8 | print() 9 | total(class_a_numbers,class_b_numbers,class_c_numbers) 10 | 11 | # remember arguments are passed in their relative order. 12 | # Notice that we just entered a,b, and c. 13 | def total(a,b,c): 14 | total=20*a+15*b+10*c 15 | print("The total income generated from tickets are $", format(total, ",.2f"), sep='') 16 | 17 | main() -------------------------------------------------------------------------------- /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 is $", format(gross_pay, ",.2f"), sep='') 16 | except ValueError: 17 | print("ERROR: Hours worked and hourly pay rate must be valid numbers.") 18 | 19 | # call the main function 20 | main() -------------------------------------------------------------------------------- /chapter_03/test_average.py: -------------------------------------------------------------------------------- 1 | high_score=95 2 | 3 | # Get the three exam scores 4 | test1=int(input("Enter the grade for test 1: ")) 5 | test2=int(input("Enter the grade for test 2: ")) 6 | test3=int(input("Enter the grade for test 3: ")) 7 | 8 | # Calculate the average test score 9 | average=(test1+test2+test3)/3 10 | 11 | # print the average 12 | print("The average score is", format(average, ".2f")) 13 | 14 | # If the average is higher than 95 congratulate the user 15 | print() 16 | if average>=high_score: 17 | print("Congratulations! Your average is above 95.") 18 | 19 | # Check point page 89 20 | # 3.6 21 | 22 | #if y==20: 23 | # x=0 24 | 25 | # 3.7 26 | 27 | #if sales>=10000: 28 | # commissionRate:0.2 -------------------------------------------------------------------------------- /chapter_13/hello_world.py: -------------------------------------------------------------------------------- 1 | # this program displays a label with text. 2 | import tkinter 3 | 4 | 5 | class MyGUI: 6 | def __init__(self): 7 | # create the main windows 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() -------------------------------------------------------------------------------- /chapter_02/print_function_details.py: -------------------------------------------------------------------------------- 1 | # argument of end. You can print all print functions in same line using end="" argument. 2 | 3 | print("One", end=" ") 4 | print("Two", end=" ") 5 | print("Three") 6 | 7 | # There is also separator argument 8 | 9 | print("One", "Two", "Three", sep=" ** ") # Separate the three different arguments using two asterisks (**) 10 | 11 | # Escape characters \n is an escape character that goes to next line. 12 | print() 13 | print("One\nTwo\nThree") 14 | 15 | # \t next tab position on same line 16 | print() 17 | print("Mon\tTues\tWed") 18 | print("Thur\tFri\tSat") 19 | 20 | # concatenation 21 | 22 | print("You suck at " + \ 23 | "computer gaming. "+\ 24 | "Get the hell out of here.") -------------------------------------------------------------------------------- /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 commission 13 | commission=sales*comm_rate 14 | 15 | # display the commission 16 | print("The commission is $", format(commission, ',.2f'), sep='') 17 | 18 | # see if the user wants to do another one. 19 | keep_going=input("Do you want to calculate another commission (Enter y for yes)?: ") -------------------------------------------------------------------------------- /chapter_06/display_file2.py: -------------------------------------------------------------------------------- 1 | # this program displays the contents 2 | # of a file. 3 | 4 | def main(): 5 | # get the mane 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 | 21 | except IOError: 22 | print("An error occured trying to read " + \ 23 | "the file", filename) 24 | 25 | # call the main function 26 | main() -------------------------------------------------------------------------------- /chapter_03/q04.py: -------------------------------------------------------------------------------- 1 | # roman numerals 2 | 3 | # ask user for a number within the range of 1 through 10 4 | 5 | number=int(input("Please enter a number within the range of 1 through 10: ")) 6 | 7 | # display the roman version 8 | 9 | if number==1: 10 | print("I") 11 | elif number==2: 12 | print("II") 13 | elif number==3: 14 | print("III") 15 | elif number==4: 16 | print("IV") 17 | elif number==5: 18 | print("V") 19 | elif number==6: 20 | print("VI") 21 | elif number==7: 22 | print("VII") 23 | elif number==8: 24 | print("VIII") 25 | elif number==9: 26 | print("IX") 27 | elif number==10: 28 | print("X") 29 | else: 30 | print("ERROR: You entered a number outside the range of 1 through 10!") 31 | -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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 the list 13 | 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 total 23 | 24 | # call the main function 25 | main() -------------------------------------------------------------------------------- /chapter_10/q01.py: -------------------------------------------------------------------------------- 1 | # Pet Class 2 | 3 | class Pet: 4 | def __init__(self, name, animal_type, age): 5 | self.__name=name 6 | self.__animal_type=animal_type 7 | self.__age=age 8 | 9 | def set_name(self, name): 10 | self.__name=name 11 | 12 | def set_animal_type(self, animal_type): 13 | self.__animal_type=animal_type 14 | 15 | def set_age(self, age): 16 | self.__age=age 17 | 18 | def get_name(self, name): 19 | return self.__name 20 | 21 | def get_animal_type(self, animal_type): 22 | return self.__animal_type 23 | 24 | def get_age(self, age): 25 | return self.__age 26 | 27 | -------------------------------------------------------------------------------- /chapter_06/q08.py: -------------------------------------------------------------------------------- 1 | # random number file reader 2 | 3 | def main(): 4 | 5 | # open the file to read 6 | myfile=open("random_numbers.txt", "r") 7 | 8 | # set accumulators 9 | total=0.0 10 | numbers=0.0 11 | print("The numbers in the file as follows:") 12 | print() 13 | 14 | # read the contents of the file. 15 | for line in myfile: 16 | line=float(line) 17 | print(line) 18 | total+=line 19 | numbers+=1 20 | 21 | # print the results. 22 | print() 23 | print("There are", int(numbers), "numbers in the file.") 24 | print("And their total is", total) 25 | 26 | # call the main function. 27 | main() -------------------------------------------------------------------------------- /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 | # print(y) # if you want to see remainder uncomment it. 18 | return y 19 | else: 20 | # print(y) 21 | return gcd(x, x % y) 22 | 23 | # Call the main function. 24 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Starting Out with Python (3rd Edition) by Tony Gaddis 2 | 3 |

4 | 5 |

6 | 7 | The codes of examples and programming exercises for [Starting Out With Python 3rd Edition](https://www.amazon.com/Starting-Out-Python-Tony-Gaddis/dp/0133582736) by Tony Gaddis 8 | prepared by Mehmet Icer for teaching purposes. Feel free to use and edit. 9 | 10 | End of chapter questions are marked by 11 | q01.py, 12 | q02.py, 13 | q03.py , 14 | etc. 15 | 16 | If there is an alternative version it is numbered as q03_1.py (Alternative to q03.py) 17 | 18 | Thanks. 19 | for any inquiries 20 | mmustafaicer@gmail.com 21 | -------------------------------------------------------------------------------- /chapter_03/q01.py: -------------------------------------------------------------------------------- 1 | # day of the week 2 | 3 | # ask user to enter a number in the range of 1 through 7 4 | 5 | user_number=int(input("Enter a number in the range of 1 through 7: ")) 6 | 7 | # it is better to use if-elif-else structure. Else for the outside of the range. 8 | if user_number==1: 9 | print("It is Monday!") 10 | elif user_number==2: 11 | print("It is Tuesday!") 12 | elif user_number==3: 13 | print("It is Wednesday!") 14 | elif user_number==4: 15 | print("It is Thursday!") 16 | elif user_number==5: 17 | print("It is Friday!") 18 | elif user_number==6: 19 | print("It is Saturday!") 20 | elif user_number==7: 21 | print("It is Sunday!") 22 | else: 23 | print("You entered a number that is outside the range of 1 through 7.") 24 | -------------------------------------------------------------------------------- /chapter_10/q04_1.py: -------------------------------------------------------------------------------- 1 | # Employee Class 2 | 3 | # there is an alternative to this. 4 | import q04 5 | 6 | def main(): 7 | # create a list for employee data 8 | emp_list=[] 9 | 10 | # get the data and add it to object 11 | for i in range(3): 12 | name=input("Name: ") 13 | id=int(input("ID Number: ")) 14 | dep=input("Department: ") 15 | job=input("Job Title: ") 16 | print() 17 | 18 | # add it to object. 19 | employee=q04.Employee(name, id, dep, job) 20 | emp_list.append(employee) 21 | 22 | # show the data. 23 | for item in emp_list: 24 | print(item) 25 | print() 26 | 27 | # call the main function 28 | main() -------------------------------------------------------------------------------- /chapter_02/q04.py: -------------------------------------------------------------------------------- 1 | # Total Purchase 2 | 3 | # Ask user for the price of each item 4 | item1=float(input("Enter the price of item 1: ")) 5 | item2=float(input("Enter the price of item 2: ")) 6 | item3=float(input("Enter the price of item 3: ")) 7 | item4=float(input("Enter the price of item 4: ")) 8 | item5=float(input("Enter the price of item 5: ")) 9 | 10 | # Display the subtotal 11 | print() 12 | subtotal=item1+item2+item3+item4+item5 13 | print("Your subtotal is $", subtotal, sep='') 14 | 15 | # Calculate the tax. It is 7 percent. 16 | print() 17 | tax_calculated=subtotal*0.07 18 | print("Sales tax is $", format(tax_calculated, '.2f'), sep='') 19 | 20 | # Calculate the total and display it 21 | print() 22 | total=subtotal+tax_calculated 23 | print("Your total is $", total, sep='') -------------------------------------------------------------------------------- /chapter_03/loan_qualifier.py: -------------------------------------------------------------------------------- 1 | # this program determines whether a bank customer qualifies for a loan. 2 | min_salary=30000. # The minimum annual salary 3 | min_years=2 # The minimum years on the job 4 | 5 | # get the customer's salary 6 | salary=float(input("Enter your annual salary: ")) 7 | # get the years on job 8 | years=int(input("Enter the number of years employed: ")) 9 | # Determine whether the customer qualifies 10 | 11 | if salary>=min_salary: 12 | if years>=min_years: 13 | print("Congratulations you qualify for a loan.") 14 | else: 15 | print("You must have been employed for at least", min_years, "years to qualify.") 16 | else: 17 | print("You must earn at least $", format(min_salary, ',.2f'), " per year to qualify.", sep='') 18 | -------------------------------------------------------------------------------- /chapter_03/q14.py: -------------------------------------------------------------------------------- 1 | # body mass index 2 | 3 | # ask user to enter weight and height 4 | 5 | user_weight=float(input("Enter the weight in pounds: ")) 6 | user_height=float(input("Enter the height in inches: ")) 7 | print() 8 | 9 | # calculate body mass index 10 | bmi=user_weight*(703/(user_height**2)) 11 | 12 | # create decision structure for categories 13 | 14 | if bmi>=18.5 and bmi<=25: 15 | print("Your body mass index (BMI) is", format(bmi, ",.2f"), "and your category is optimal.") 16 | elif bmi<18.5: 17 | print("Your body mass index (BMI) is", format(bmi, ",.2f"), "and your category is under-weight.") 18 | elif bmi>25: 19 | print("Your body mass index (BMI) is", format(bmi, ",.2f"), "and your category is over-weight.") 20 | else: 21 | print("ERROR: Invalid Value.") -------------------------------------------------------------------------------- /chapter_08/q11.py: -------------------------------------------------------------------------------- 1 | # string separator 2 | 3 | def main(): 4 | print("Example: StopAndSmellTheRoses\n") 5 | user_string=input("Enter a string like one above: ") 6 | separator(user_string) 7 | 8 | def separator(string): 9 | # separate it by uppercase letter. 10 | # first letter would be capital 11 | print (string[0].upper(), end="") 12 | 13 | # since we skip first letter, index=1 14 | index=1 15 | while indexbase_hours: 10 | # Calculate the gross pay 11 | overtime_hours=hours-base_hours # overtimed hours 12 | overtime_pay=overtime_hours*pay_rate*ot_multiplier 13 | gross_pay=(base_hours*pay_rate)+overtime_pay 14 | 15 | else: 16 | # Calculate the gross pay without overtime 17 | gross_pay=hours*pay_rate 18 | 19 | # Display the gross pay 20 | print("The gross pay is $", format(gross_pay, ",.2f"), sep='') -------------------------------------------------------------------------------- /chapter_04/property_tax.py: -------------------------------------------------------------------------------- 1 | # this program display property taxes. 2 | tax_factor=0.0065 # represents the tax factor given. 3 | 4 | # get the first lot number 5 | print("Enter the property lot number") 6 | print("or enter 0 to end") 7 | lot=int(input("Lot number: ")) 8 | 9 | # continue processing as long as the user 10 | # does not enter lot number 0 11 | while lot!=0: 12 | # get the property value. 13 | value=float(input("Enter the property value: ")) 14 | 15 | # calculate the property tax 16 | tax=value*tax_factor 17 | 18 | # Display the tax 19 | print("Property tax: $", format(tax, ",.2f"), sep='') 20 | 21 | # get the next lot number 22 | print() 23 | print("Enter the next lot number or enter 0 to end.") 24 | lot=int(input("Lot number: ")) -------------------------------------------------------------------------------- /chapter_07/random_numbers.py: -------------------------------------------------------------------------------- 1 | # this program assigns random numbers to a 2 | # 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 | # or 24 | 25 | # for r in range(ROWS): 26 | # for c in range(COLS): 27 | # print(values[r][c]) 28 | 29 | # call the main function 30 | main() -------------------------------------------------------------------------------- /chapter_06/strip_newline.py: -------------------------------------------------------------------------------- 1 | # this program reads the contents of the 2 | # philosophers.txt file one line at a time. 3 | 4 | def main(): 5 | # open a file named philosophers.txt. 6 | infile=open("philosophers.txt", "r") 7 | 8 | # read the three lines from the file 9 | line1=infile.readline() 10 | line2=infile.readline() 11 | line3=infile.readline() 12 | 13 | # strip the \n from each string 14 | line1=line1.rstrip("\n") 15 | line2=line2.rstrip("\n") 16 | line3=line3.rstrip("\n") 17 | 18 | # close the file. 19 | infile.close() 20 | 21 | # print the data that was read into 22 | # memory 23 | print(line1) 24 | print(line2) 25 | print(line3) 26 | 27 | # call the main function 28 | main() -------------------------------------------------------------------------------- /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 names to the file 15 | myfile.write(name1+"\n") # \n escape character necessary to separate. 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 | -------------------------------------------------------------------------------- /chapter_06/q07.py: -------------------------------------------------------------------------------- 1 | # random number file writer 2 | 3 | import random 4 | def main(): 5 | 6 | # open a file to write 7 | myfile=open("random_numbers.txt", "w") 8 | 9 | # ask user how many random numbers will be generated and store. 10 | total_numbers=int(input("How many random numbers will be generated?: ")) 11 | 12 | for i in range(total_numbers): 13 | # produce the random number. 14 | # in the range of 1 through 500. 15 | number=random.randrange(1,501,1) 16 | 17 | # write the number to the file using \n 18 | myfile.write(str(number)+"\n") 19 | 20 | print("The numbers are generated and written to . ") 21 | # close the file 22 | myfile.close() 23 | 24 | main() -------------------------------------------------------------------------------- /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 13 | # and accumulate them. 14 | for line in infile: 15 | amount=float(line) 16 | total+=amount 17 | 18 | # close the file. 19 | infile.close() 20 | 21 | except Exception as err: 22 | print(err) 23 | else: 24 | # print the total. 25 | print(format(total, ",.2f")) 26 | 27 | # call the main function. 28 | main() -------------------------------------------------------------------------------- /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 for each day 7 | sales=[0]*NUM_DAYS 8 | 9 | # create a variable to hold an index 10 | index=0 11 | 12 | print("Enter the sales for each day.") 13 | 14 | # get the sales for each day. 15 | while indexarea2: 18 | print("Area of rectangle 1:", area1, "is greater than the area of rectangle 2:", area2) 19 | elif area1 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() -------------------------------------------------------------------------------- /chapter_04/q03.py: -------------------------------------------------------------------------------- 1 | # budget analysis 2 | 3 | # ask user for budgeted amount 4 | user_budget=float(input("Please enter the budgeted amount for this month: ")) 5 | 6 | keep_going="y" 7 | total_expense=0 8 | counter=0 9 | 10 | while keep_going=="y" or keep_going=="Y": 11 | print("Please enter the expense", counter+1, end='') 12 | expense=float(input(":")) 13 | total_expense+=expense 14 | print("If you want to add another expense please type 'y'. To end type 'n'", end="") 15 | keep_going=input(":") 16 | counter+=1 # this is for to make expense 1 expense 2 expense 3. It is better. 17 | 18 | # Show the result 19 | print() 20 | print("Your budget is ", user_budget) 21 | print("Your total expenses is ", total_expense) 22 | 23 | if user_budget>total_expense: 24 | print("You are under budget.") 25 | else: 26 | print("You are over budget.") 27 | -------------------------------------------------------------------------------- /chapter_09/q04.py: -------------------------------------------------------------------------------- 1 | # unique words 2 | 3 | def main(): 4 | 5 | # read the file 6 | myfile=open("uniquewords.txt", "r") 7 | # read the lines 8 | lines=myfile.readlines() 9 | # close the file 10 | myfile.close() 11 | 12 | # create a set of words 13 | unique_words=set() 14 | 15 | # read each word. 16 | for line in lines: # each line 17 | for word in line.split(): # each word: split words by space (a.k.a. word) 18 | unique_words.add(word) # add the word to set 19 | 20 | # remember. Set does not have duplicate items. So you can just iterate 21 | # unique_words.add(word) without checking >>>> if word is not in unique_words. etc. 22 | 23 | print("Unique words are below: ") 24 | print(unique_words) 25 | 26 | # call the main function 27 | main() -------------------------------------------------------------------------------- /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 the 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 | # str function applies numerical variables only. 16 | # be careful on parantheses () 17 | outfile.write(str(num1)+"\n") 18 | outfile.write(str(num2)+"\n") 19 | outfile.write(str(num3)+"\n") 20 | 21 | # close the file 22 | outfile.close() 23 | print("Data written to numbers.txt") 24 | 25 | # call the main function 26 | main() -------------------------------------------------------------------------------- /chapter_12/q01.py: -------------------------------------------------------------------------------- 1 | # recursive printing 2 | 3 | def main(): 4 | # explain the program 5 | print("This program displays the numbers from \ 6 | 1 up through the 'n' that you stated") 7 | print() 8 | 9 | # get the number from the user. 10 | beg_num=1 11 | end_num=int(input("Please enter an integer: ")) 12 | print() 13 | 14 | print_numbers(beg_num, end_num) 15 | 16 | # algorithm: if beg_num=amount: 18 | self.__balance-=amount 19 | else: 20 | print("ERROR: Insufficient Funds.") 21 | 22 | # the get balance method returns the account balance 23 | def get_balance(self): 24 | return self.__balance 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /chapter_06/q05.py: -------------------------------------------------------------------------------- 1 | # sum of numbers 2 | 3 | def main(): 4 | try: 5 | # read the file. 6 | myfile=open("numbers.txt", "r") 7 | 8 | # set an accumulator for total 9 | total=0.0 10 | 11 | # read all the lines from the file 12 | for line in myfile: 13 | # the line is always string. convert it to float 14 | line=float(line) 15 | total+=line 16 | 17 | # print the total 18 | print("The total of the numbers in the file is", total) 19 | 20 | # close the file 21 | myfile.close() 22 | 23 | # in case one of the lines is not numeric. Such as "xyz". 24 | except ValueError: 25 | print("ERROR: At least one of the lines in the file is not numeric.") 26 | 27 | 28 | # call the main function. 29 | main() -------------------------------------------------------------------------------- /chapter_05/q16.py: -------------------------------------------------------------------------------- 1 | # odd/even counter 2 | 3 | import random 4 | 5 | def main(): 6 | # lets set a counter/tracker for odd and even numbers 7 | total_odd_numbers=0 8 | total_even_numbers=0 9 | 10 | # program asks for 100 random numbers. So set a for loop. 11 | # change 100 to 5 to see if it is working correctly. 12 | for n in range(100): 13 | number=GenerateRandomNumbers() 14 | if number%2==0: 15 | total_even_numbers+=1 16 | elif number%2==1: 17 | total_odd_numbers+=1 18 | print("There are", total_even_numbers, "even numbers and", total_odd_numbers, "odd numbers in the list.") 19 | 20 | def GenerateRandomNumbers(): 21 | # do not forget to pass arguments to random.randint(). otherwise it will give error 22 | # like we passed 0,1000 23 | number=random.randint(0,1000) 24 | print(number) 25 | return number 26 | 27 | main() -------------------------------------------------------------------------------- /chapter_06/q03.py: -------------------------------------------------------------------------------- 1 | # line numbers 2 | 3 | def main(): 4 | 5 | # set an line indicator starting from 1. 6 | line_numbering=1 7 | 8 | # ask user to enter a file name. 9 | filename=input("Enter a file name to open: ") 10 | print() 11 | 12 | # open the file 13 | userfile=open(filename, 'r') 14 | 15 | # read every line and print with the line number 16 | for line in userfile: 17 | # lets print the line numbers with semi colon. 18 | # but it will not end with new line. so end="" 19 | print(line_numbering, ": ", sep="", end='') 20 | 21 | # print each number with stripping \n 22 | print(line.rstrip("\n")) 23 | 24 | # increase the line numbering by one. 25 | line_numbering+=1 26 | 27 | # close the file. 28 | userfile.close() 29 | 30 | # call the main function 31 | main() 32 | -------------------------------------------------------------------------------- /chapter_09/q01.py: -------------------------------------------------------------------------------- 1 | # course information 2 | 3 | def main(): 4 | 5 | # create dictionaries 6 | room_number={"CS101": 3004, "CS102": 4501, "CS103": 6755, 7 | "NT110": 1244, "CM241": 1411} 8 | instructors={"CS101": "Haynes", "CS102": "Alvarado", 9 | "CS103": "Rich", "NT110": "Burke", "CM241": "Lee"} 10 | times={"CS101": "8:00 a.m.", "CS102": "9:00 a.m.", 11 | "CS103": "10:00 a.m.", "NT110": "11:00 a.m.", "CM241": "1:00 p.m."} 12 | 13 | # get the course number 14 | course_number=input("Enter a course number: ") 15 | 16 | # display results 17 | display(room_number, instructors, times, course_number) 18 | 19 | def display(r, i, t, course): 20 | print() 21 | print("Room Number:", r[course]) 22 | print("Instructor:", i[course]) 23 | print("Meeting Time: :", t[course]) 24 | 25 | # call the main function 26 | main() -------------------------------------------------------------------------------- /chapter_12/q06.py: -------------------------------------------------------------------------------- 1 | # sum of numbers 2 | 3 | def main(): 4 | # set beginning point 5 | beg=1 6 | 7 | # get the data from the user 8 | end=int(input("Enter a positive integer: ")) 9 | print() 10 | 11 | # call the function 12 | total=sum_num(beg, end) 13 | 14 | # display the result. 15 | print("The total of the numbers from 1 up to", end, "equals to", total) 16 | 17 | def sum_num(beg, end): 18 | if beg<=end: 19 | return beg + sum_num(beg+1, end) 20 | else: 21 | return 0 22 | 23 | # alternative 24 | #=========================================================================== 25 | # # or 26 | # if beg1 return y+multiply(x-1,y) >>> in other words: x is "how many y's are to be added" 20 | # then reduce it by one every time the function works. That is why it is "x-1" 21 | def multiply(x,y): 22 | if x>1: 23 | return y + multiply(x-1,y) 24 | if x==1: 25 | return y 26 | 27 | # call the main function 28 | main() -------------------------------------------------------------------------------- /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/list_append.py: -------------------------------------------------------------------------------- 1 | # this program demonstrates how the append method 2 | # 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=="y" or again=="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() -------------------------------------------------------------------------------- /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 your string:") 8 | print() 9 | 10 | # test the string 11 | if user_string.isalnum(): 12 | print("The string is alphanumeric.") 13 | if user_string.isdigit(): 14 | print("The string contains only digits.") 15 | if user_string.isalpha(): 16 | print("The string contains only alphabetic characters.") 17 | if user_string.isspace(): 18 | print("The string contains only whitespace characters.") 19 | if user_string.islower(): 20 | print("The letters in the string are all lowercase.") 21 | if user_string.isupper(): 22 | print("The letters in the string are all uppercase.") 23 | 24 | # call the main function 25 | main() -------------------------------------------------------------------------------- /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("Please 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() -------------------------------------------------------------------------------- /chapter_10/q05.py: -------------------------------------------------------------------------------- 1 | # RetailItem Class 2 | 3 | class RetailItem: 4 | def __init__(self, descr, units, price): 5 | self.__descr=descr 6 | self.__units=units 7 | self.__price=price 8 | 9 | # mutator methods 10 | def set_descr(self, descr): 11 | self.__descr=descr 12 | 13 | def set_units(self, units): 14 | self.__units 15 | 16 | def set_price(self, price): 17 | self.__price 18 | 19 | # accessor methods 20 | def show_descr(self): 21 | return self.__descr 22 | 23 | def show_units(self): 24 | return self.__units 25 | 26 | def show_price(self): 27 | return self.__price 28 | 29 | # set string method 30 | 31 | def __str__(self): 32 | return "Description: " + self.__descr+ \ 33 | "\nUnits in Inventory: " + str(self.__units) + \ 34 | "\nPrice: $" + str(self.__price) -------------------------------------------------------------------------------- /chapter_05/q18.py: -------------------------------------------------------------------------------- 1 | # prime number list 2 | 3 | # prime numbers 4 | 5 | def main(): 6 | print("The prime numbers from 1 to 100 are listed below.") 7 | print() 8 | # first lets pass all numbers from 1 to 100 to our is_prime function. 9 | for num in range(2,101): 10 | if is_prime(num): 11 | print(num) 12 | 13 | def is_prime(num): 14 | # we create a for loop structure so we can divide our number 15 | # to each number that is less than it. 16 | status=True 17 | # we set status to be True until it could be falsified. If it can be divided by any number 18 | # less than itself, status=False. Check the code below. 19 | for i in range(2,num): 20 | if num%i==0: 21 | status=False 22 | return status 23 | 24 | main() 25 | 26 | # percentage is remainder option. If it is divided evenly by any number (except 1 and itself) 27 | # it is not prime number so status=False 28 | -------------------------------------------------------------------------------- /chapter_06/q02.py: -------------------------------------------------------------------------------- 1 | # file head display 2 | # for a shorter alternative check q02_1.py 3 | 4 | def main(): 5 | 6 | # ask user to enter a filename. 7 | filename=input("Enter the file name: ") 8 | 9 | # open that file name 10 | infile=open(filename, "r") 11 | 12 | # read the 5 lines from the file. 13 | line1=infile.readline() 14 | line2=infile.readline() 15 | line3=infile.readline() 16 | line4=infile.readline() 17 | line5=infile.readline() 18 | 19 | # strip the \n s from end. 20 | line1=line1.rstrip("\n") 21 | line2=line2.rstrip("\n") 22 | line3=line3.rstrip("\n") 23 | line4=line4.rstrip("\n") 24 | line5=line5.rstrip("\n") 25 | 26 | # print the contents 27 | print(line1) 28 | print(line2) 29 | print(line3) 30 | print(line4) 31 | print(line5) 32 | 33 | # close the file. 34 | infile.close() 35 | 36 | # call the main function 37 | main() -------------------------------------------------------------------------------- /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 5 | # for the size of the list 6 | 7 | NUM_EMPLOYEES=6 8 | 9 | def main(): 10 | # create a list to hold employee hours. 11 | hours=[0]*NUM_EMPLOYEES 12 | 13 | # get each employee's hours worked. 14 | for index in range(NUM_EMPLOYEES): 15 | print("Enter the hours worked by employee #", \ 16 | index+1, sep="", end="") 17 | hours[index]=float(input(": ")) 18 | 19 | # get the hourly pay rate. 20 | pay_rate=float(input("Enter the hourly pay rate: ")) 21 | print() 22 | 23 | # display each employee's gross pay. 24 | for index in range(NUM_EMPLOYEES): 25 | gross_pay=hours[index]*pay_rate 26 | print("Gross pay for employee #", index+1, " is $", format(gross_pay, ",.2f"), sep="") 27 | 28 | # call the main function 29 | main() -------------------------------------------------------------------------------- /chapter_05/q09.py: -------------------------------------------------------------------------------- 1 | # monthly sales tax 2 | 3 | # write constants 4 | STATE_TAX_RATE=0.05 5 | COUNTY_TAX_RATE=0.025 6 | 7 | def main(): 8 | # ask user to enter the total sales for the month 9 | total_sales=float(input("Enter the total sales for the month: ")) 10 | print() 11 | c_tax_total=CountyTaxCalculator(total_sales) 12 | s_tax_total=StateTaxCalculator(total_sales) 13 | TotalTaxCalculator(c_tax_total,s_tax_total) 14 | 15 | def CountyTaxCalculator(total_sales): 16 | county_tax=total_sales*COUNTY_TAX_RATE 17 | print("Your county sales tax is $", format(county_tax, ",.2f"), sep='') 18 | return county_tax 19 | def StateTaxCalculator(total_sales): 20 | state_tax=total_sales*STATE_TAX_RATE 21 | print("Your state sales tax is $", format(state_tax, ",.2f"), sep='') 22 | return state_tax 23 | def TotalTaxCalculator(a,b): 24 | total=a+b 25 | print("Your total sales tax is $", format(total, ",.2f"), sep='') 26 | 27 | main() -------------------------------------------------------------------------------- /chapter_05/retirement.py: -------------------------------------------------------------------------------- 1 | # the following is used as global constant 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: $", format(contrib, ",.2f"), sep='') 17 | 18 | # the show_bonus_contrib function accepts the 19 | # bonus amount as an argument and displays the 20 | # retirement contribution for that amount of pay 21 | 22 | def show_bonus_contrib(bonus): 23 | contrib=bonus*CONTRIBUTION_RATE 24 | print("Contribution for bonuses: $", format(contrib, ",.2f"), sep='') 25 | 26 | # call the main function 27 | main() -------------------------------------------------------------------------------- /chapter_08/q02.py: -------------------------------------------------------------------------------- 1 | # sum of digits in a string 2 | 3 | def main(): 4 | try: 5 | # get the numbers from user 6 | numbers=get_numbers() 7 | total=0 8 | 9 | # access each digit by index number. use len(numbers) 10 | index=0 11 | while index=2 and n_books<4: 13 | points=5 14 | print("You have been", points, "points awarded with your purchase of", n_books, "books.") 15 | elif n_books>=4 and n_books<6: 16 | points=15 17 | print("You have been", points, "points awarded with your purchase of", n_books, "books.") 18 | elif n_books>=6 and n_books<8: 19 | points=30 20 | print("You have been", points, "points awarded with your purchase of", n_books, "books.") 21 | elif n_books>=8: 22 | points=60 23 | print("You have been", points, "points awarded with your purchase of", n_books, "books.") 24 | else: 25 | print("ERROR: You entered an invalid entry!") 26 | 27 | -------------------------------------------------------------------------------- /chapter_03/q13.py: -------------------------------------------------------------------------------- 1 | # shipping charges 2 | 3 | # ask user to enter the weight of a package 4 | user_weight=float(input("Enter the weight of the package: ")) 5 | print() 6 | 7 | # create decision structure shipping charges 8 | if user_weight>0 and user_weight<=2: 9 | rate_per_pound=1.50 10 | charge=rate_per_pound*user_weight 11 | print("Your total shipping charge is $", format(charge, ",.2f"), sep='') 12 | elif user_weight>2 and user_weight<=6: 13 | rate_per_pound=3.00 14 | charge=rate_per_pound*user_weight 15 | print("Your total shipping charge is $", format(charge, ",.2f"), sep='') 16 | elif user_weight>6 and user_weight<=10: 17 | rate_per_pound=4.00 18 | charge=rate_per_pound*user_weight 19 | print("Your total shipping charge is $", format(charge, ",.2f"), sep='') 20 | elif user_weight>10: 21 | rate_per_pound=4.75 22 | charge=rate_per_pound*user_weight 23 | print("Your total shipping charge is $", format(charge, ",.2f"), sep='') 24 | else: 25 | print("ERROR: You entered an invalid number.") 26 | -------------------------------------------------------------------------------- /chapter_08/q05.py: -------------------------------------------------------------------------------- 1 | # alphabetic telephone number translator 2 | 3 | def main(): 4 | # create two lists for conversion. each index will match in two lists. 5 | # for example. a=2, b=2, c=2 6 | alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y''z'] 7 | number =[2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,9] 8 | 9 | # get the input from the user. 10 | phone = input('Enter a phone number in the format xxx-xxx-xxxx: ') # or you can add end .lower() to lowercase. 11 | 12 | # convert to lower case. 13 | phone=phone.lower() 14 | 15 | # go through each character in input 16 | index = 0 17 | while index 0: 22 | # total_hours 23 | hours= day_remainder//3600 24 | # remainder from hours 25 | hours_remainder = day_remainder%3600 26 | 27 | # if there are still seconds calculate minutes. 28 | if hours_remainder>0: 29 | minutes = hours_remainder//60 30 | minutes_remainder = hours_remainder%60 31 | seconds=minutes_remainder 32 | 33 | # display the result. 34 | print(f"There are {days} days, {hours} hours, {minutes} minutes, and {seconds} seconds in that {user_seconds} seconds that you entered.") 35 | 36 | -------------------------------------------------------------------------------- /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 | 30 | except ValueError: 31 | print("That item was not found in the list.") 32 | 33 | # call the main function 34 | main() 35 | -------------------------------------------------------------------------------- /chapter_06/read_running_times.py: -------------------------------------------------------------------------------- 1 | # this program gets the values from video_times.txt 2 | # 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 | run_time=float(line) 19 | 20 | # add 1 to the count variable. 21 | count+=1 22 | 23 | # display the time 24 | print("Video #", count, ": ", run_time, sep='') 25 | 26 | # add the time to total. 27 | total+=run_time 28 | 29 | # close the file. 30 | video_file.close() 31 | 32 | # display the total of the running times. 33 | print("The total running time is", total, "seconds.") 34 | 35 | # call the main function 36 | main() -------------------------------------------------------------------------------- /chapter_12/q03.py: -------------------------------------------------------------------------------- 1 | # recursive end 2 | 3 | def main(): 4 | # create asterisk and numinner variable. 5 | ast="*" 6 | num=1 7 | 8 | # ask user how many end 9 | end=int(input("How many end of asterisks: ")) 10 | print() 11 | 12 | # execute function 13 | print_asterisk(ast, num, end) 14 | 15 | # define function. 16 | # here is the algorithm: 17 | # if end>num >>>> print "*" nth times. (which is num in our case) 18 | # for example: for num=1: print "*" 1 times and go to second line (num=2) 19 | # then for num=2: print "*" 2 times and go to third line etc. etc. 20 | # and return same function with num increased by 1 for next line (num+1)th line 21 | 22 | # if end==num >>>> print "*" (end)th time. (final line) and do not 23 | # return anything. 24 | def print_asterisk(ast, num, end): 25 | if end>num: 26 | print(ast*num) # remember you can multiply the string. 27 | num+=1 28 | return print_asterisk(ast, num, end) 29 | elif end==num: 30 | print(ast*num) 31 | 32 | # call the main function 33 | main() -------------------------------------------------------------------------------- /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 | def __init__(self, bal): 9 | self.__balance=bal 10 | 11 | # the deposit method takes a deposit into the account 12 | def deposit(self, amount): 13 | self.__balance+=amount 14 | 15 | # the withdraw method withdraws an amount from the account. 16 | def withdraw(self, amount): 17 | if self.__balance>=amount: 18 | self.__balance-=amount 19 | else: 20 | print("ERROR: Insufficient Funds.") 21 | 22 | # the get balance method returns the account balance 23 | def get_balance(self): 24 | return self.__balance 25 | 26 | # the __str__ method returns a string 27 | # indicating the object's state. 28 | 29 | def __str__(self): 30 | return "The balance is $" + format(self.__balance, ",.2f") 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /chapter_10/pickle_cellphone.py: -------------------------------------------------------------------------------- 1 | # this program pickles CellPhone objects. 2 | import pickle 3 | import cellphone 4 | 5 | # constant for the file name. 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 the data from the user. 16 | while again.lower()=="y": 17 | # get the 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() -------------------------------------------------------------------------------- /chapter_03/q07.py: -------------------------------------------------------------------------------- 1 | # color mixer 2 | 3 | print("Red, blue, and yellow are primary colors.") 4 | print() 5 | 6 | # ask user to choose two primary colors to mix 7 | 8 | color1=input("Enter the primary color 1 (red,blue, or yellow): ") 9 | color2=input("Enter the primary color 2 (red,blue, or yellow): ") 10 | 11 | # create secondary colors. Remember the two colors could be inputed in two different 12 | # ways. Like color1=red color2=blue or color1=blue color2=red 13 | 14 | # purple 15 | if color1=="red" and color2=="blue": 16 | print("The secondary color is purple.") 17 | elif color1=="blue" and color2=="red": 18 | print("The secondary color is purple.") 19 | # orange 20 | elif color1=="red" and color2=="yellow": 21 | print("The secondary color is orange.") 22 | elif color1=="red" and color2=="yellow": 23 | print("The secondary color is orange.") 24 | # green 25 | elif color1=="blue" and color2=="yellow": 26 | print("The secondary color is green.") 27 | elif color1=="yellow" and color2=="blue": 28 | print("The secondary color is green.") 29 | # error message 30 | else: 31 | print("ERROR: You entered the primary colors wrong.") 32 | 33 | -------------------------------------------------------------------------------- /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 objects. 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 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 | 30 | def display_data(person): 31 | print("Name:", person["name"]) 32 | print("Age:", person["age"]) 33 | print("Weight:", person["weight"]) 34 | print() 35 | 36 | # call the main function 37 | main() -------------------------------------------------------------------------------- /chapter_10/q04.py: -------------------------------------------------------------------------------- 1 | # Employee Class 2 | 3 | class Employee: 4 | def __init__(self, name, id, dep, job): 5 | self.__name=name 6 | self.__id=id 7 | self.__dep=dep 8 | self.__job=job 9 | 10 | # mutator methods 11 | def set_name(self, name): 12 | self.__name=name 13 | 14 | def set_id(self, id): 15 | self.__id=id 16 | 17 | def set_dep(self, dep): 18 | self.__dep=dep 19 | 20 | def set_job(self, job): 21 | self.__job=job 22 | 23 | # accessor methods 24 | def show_name(self, name): 25 | return self.__name 26 | 27 | def show_id(self, id): 28 | return self.__id 29 | 30 | def show_dep(self, dep): 31 | return self.__dep 32 | 33 | def show_job(self, job): 34 | return self.__job 35 | 36 | # string method for showing 37 | def __str__(self): 38 | return "Name: " + self.__name + \ 39 | "\nID Number: " + str(self.__id) + \ 40 | "\nDepartment: " + self.__dep + \ 41 | "\nJob Title: " + self.__job -------------------------------------------------------------------------------- /chapter_08/q03.py: -------------------------------------------------------------------------------- 1 | # date printer 2 | # there is an alternative version using builtin library 3 | 4 | def main(): 5 | # get the date from the user. 6 | date=get_date() 7 | 8 | # convert date to like March 12, 2014 9 | literal_date=convert(date) 10 | 11 | print("The date is below.") 12 | print(literal_date) 13 | 14 | def get_date(): 15 | date=input("Enter the date as mm/dd/yyyy: ") 16 | return date 17 | 18 | def convert(date): 19 | # first separate the string. 20 | date_list=date.split("/") 21 | 22 | # create a list for months. 23 | months=["January", "February", "March", "April", "May", \ 24 | "June", "July", "August", "September", "October", \ 25 | "November", "December"] 26 | 27 | # lets concatenate each value. 28 | # if month is entered as 01 it should be January. But January's index is 0. 29 | # that is why int(date_list[0]-1) 30 | new_date=str(months[int(date_list[0])-1]) + " " + str(date_list[1]) + "," + " " + str(date_list[2]) 31 | return new_date 32 | 33 | # call the main function 34 | main() 35 | 36 | -------------------------------------------------------------------------------- /chapter_06/q06.py: -------------------------------------------------------------------------------- 1 | # average of numbers 2 | 3 | def main(): 4 | try: 5 | # open the file 6 | infile=open("numbers.txt", "r") 7 | 8 | # set an accumulator for number of files and total 9 | total_numbers=0.0 10 | total=0.0 11 | 12 | # read the file and calculate average 13 | for line in infile: 14 | line=float(line) 15 | total+=line 16 | total_numbers+=1 17 | 18 | # calculate the average 19 | average=total/total_numbers 20 | print("There are" ,int(total_numbers), "numbers in the . And their average is", average) 21 | 22 | # close the file 23 | infile.close() 24 | # in case there are 0 numbers in the file. it can't be divided by zero. 25 | except ZeroDivisionError: 26 | print("ERROR: There are no numbers in the file.") 27 | 28 | # in case there are non-numeric lines in the file. 29 | except ValueError: 30 | print("ERROR: There are non-numeric lines in the file.") 31 | 32 | 33 | # call the main function. 34 | main() -------------------------------------------------------------------------------- /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 | # open a file for writing. 9 | emp_file=open("employees.txt", "w") 10 | 11 | # get each employee's data and write it to 12 | # the file. 13 | for count in range(1,num_emps+1): 14 | # get the data for an employee 15 | print("Enter the data for employee #", count, sep="") 16 | name=input("Name: ") 17 | id_num=input("ID number: ") 18 | dept=input("Department: ") 19 | 20 | # write the data as a record to the file. 21 | emp_file.write(name+"\n") 22 | emp_file.write(id_num+"\n") 23 | emp_file.write(dept+"\n") 24 | 25 | # display a blank line. 26 | print() 27 | # close the file. 28 | emp_file.close() 29 | print("Employee records written to employees.txt") 30 | 31 | # call the main function 32 | main() -------------------------------------------------------------------------------- /chapter_12/q05.py: -------------------------------------------------------------------------------- 1 | # recursive list sum 2 | 3 | def main(): 4 | # create a sample list for our purposes. 5 | list=[12,18,24,36,63,57] 6 | 7 | # indicator for total 8 | total_counter=0 9 | 10 | # execute function 11 | total=get_total(list, 0, total_counter) 12 | 13 | print("The total of the numbers in the given list is", total) 14 | 15 | # define function. my algorithm here: 16 | # take first element of the list and add it the total. 17 | # then delete that element and pass the new list to the function. 18 | # keep on executing function until there is no element. 19 | 20 | def get_total(list, index, total_counter): 21 | while len(list)>0: # while there are elements on the list keep adding 22 | # add first item to the total 23 | total_counter+=list[index] 24 | # del first item after adding 25 | del list[index] 26 | # pass the new list to the function and return it 27 | return get_total(list, 0, total_counter) 28 | else: # when there is 0 element in the list. 29 | return total_counter 30 | # call the main function 31 | main() -------------------------------------------------------------------------------- /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.strip("\n") 22 | id_num=id_num.strip("\n") 23 | dept=dept.strip("\n") 24 | 25 | # display the records 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() -------------------------------------------------------------------------------- /chapter_03/q09.py: -------------------------------------------------------------------------------- 1 | # roulette wheel colors 2 | 3 | # ask user to enter a pocket number 4 | 5 | p_num=int(input("Enter a pocket number between 0 and 36: ")) 6 | 7 | # create decision structure carefully. 8 | print() 9 | if p_num==0: 10 | print("Pocket", p_num, "is green.") 11 | elif p_num>=1 and p_num<=10: 12 | if p_num%2==0: # this means if p_num is even number 13 | print("Pocket", p_num, "is black.") 14 | else: 15 | print("Pocket", p_num, "is red.") 16 | elif p_num>=11 and p_num<=18: 17 | if p_num%2==0: # this means if p_num is even number 18 | print("Pocket", p_num, "is red.") 19 | else: 20 | print("Pocket", p_num, "is black.") 21 | elif p_num>=19 and p_num<=28: 22 | if p_num%2==0: # this means if p_num is even number 23 | print("Pocket", p_num, "is black.") 24 | else: 25 | print("Pocket", p_num, "is red.") 26 | elif p_num>=29 and p_num<=36: 27 | if p_num%2==0: # this means if p_num is even number 28 | print("Pocket", p_num, "is red.") 29 | else: 30 | print("Pocket", p_num, "is black.") 31 | else: 32 | print("ERROR: You entered a number that is not within the range of 1-36.") 33 | 34 | -------------------------------------------------------------------------------- /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") # do not forget to string qty. 21 | 22 | # determine whether the user wants to add 23 | # another record to the file. 24 | print() 25 | print("Do you want to add another record?") 26 | another=input("Y= yes, anything else=no: ") 27 | 28 | # close the file. 29 | coffee_file.close() 30 | print("Data appended to coffee.txt") 31 | 32 | # call the main function 33 | main() 34 | -------------------------------------------------------------------------------- /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 from the user and 13 | # stores them in a list. The function returns a reference to the list. 14 | 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=="y" or again=="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 | # return the list 34 | return values 35 | 36 | # call the main function 37 | main() -------------------------------------------------------------------------------- /chapter_10/employee.py: -------------------------------------------------------------------------------- 1 | # Employee Class 2 | 3 | class Employee: 4 | def __init__(self, id, name, dep, job): # since id will be key. first argument will be id 5 | self.__id=id 6 | self.__name=name 7 | self.__dep=dep 8 | self.__job=job 9 | 10 | # mutator methods 11 | def set_id(self, id): 12 | self.__id=id 13 | 14 | def set_name(self, name): 15 | self.__name=name 16 | 17 | def set_dep(self, dep): 18 | self.__dep=dep 19 | 20 | def set_job(self, job): 21 | self.__job=job 22 | 23 | # accessor methods 24 | def show_id(self, id): 25 | return self.__id 26 | 27 | def show_name(self, name): 28 | return self.__name 29 | 30 | def show_dep(self, dep): 31 | return self.__dep 32 | 33 | def show_job(self, job): 34 | return self.__job 35 | 36 | # string method for showing 37 | def __str__(self): 38 | return "ID Number: " + str(self.__id) + \ 39 | "\nName: " + self.__name + \ 40 | "\nDepartment: " + self.__dep + \ 41 | "\nJob Title: " + self.__job -------------------------------------------------------------------------------- /chapter_07/q05.py: -------------------------------------------------------------------------------- 1 | # charge account validation 2 | 3 | def main(): 4 | file_numbers=ReadFile() 5 | user_number=GetUserNumber() 6 | print() 7 | status=CheckFile(file_numbers, user_number) 8 | 9 | def ReadFile(): 10 | # open file for reading 11 | myfile=open("charge_accounts.txt", "r") 12 | 13 | # read the lines in the file. 14 | file_numbers=(myfile.readlines()) 15 | 16 | # strip the \n from each element. Also convert into integer. 17 | index=0 18 | while indexuser_number: 26 | print("Too low, try again.") 27 | status=False 28 | elif ran_num. And their average is", average) 21 | 22 | # close the file 23 | infile.close() 24 | # in case there are 0 numbers in the file. it can't be divided by zero. 25 | except ZeroDivisionError: 26 | print("ERROR: There are no numbers in the file.") 27 | 28 | # in case there are non-numeric lines in the file. 29 | except ValueError: 30 | print("ERROR: There are non-numeric lines in the file.") 31 | # in case any exceptions are raised when the file is opened 32 | except IOError: 33 | print("No such file or directory:") 34 | 35 | # call the main function. 36 | main() -------------------------------------------------------------------------------- /chapter_10/q08.py: -------------------------------------------------------------------------------- 1 | # Trivia Game 2 | 3 | class Question: 4 | # took hours. **** If you have any counter within a class. Do not put under __init__ 5 | player_1=0 6 | player_2=0 7 | 8 | def __init__(self, question, answer, c_answer): 9 | self.question=question 10 | self.answer=answer 11 | self.c_answer=c_answer 12 | 13 | def test1(self): 14 | if self.c_answer.lower()==self.answer: 15 | print("Correct") 16 | print() 17 | Question.player_1+=1 18 | else: 19 | print("Wrong! The correct answer is", self.answer) 20 | print() 21 | 22 | def get_test1(self): 23 | return Question.player_1 24 | 25 | def test2(self): 26 | if self.c_answer.lower()==self.answer: 27 | print("Correct") 28 | print() 29 | Question.player_2+=1 30 | else: 31 | print("Wrong! The correct answer is", self.answer) 32 | print() 33 | 34 | def get_test2(self): 35 | return Question.player_2 36 | 37 | def __str__(self): 38 | return "Player 1: " + str(Question.player_1) + "\n" +\ 39 | "Player 2: " + str(Question.player_2) 40 | -------------------------------------------------------------------------------- /chapter_11/q03.py: -------------------------------------------------------------------------------- 1 | # Person and Customer classes 2 | 3 | class Person: 4 | def __init__(self, name, address, phone_num): 5 | self.__name=name 6 | self.__address=address 7 | self.__phone_num=phone_num 8 | 9 | # set accessor methods. 10 | def get_name(self): 11 | return self.__name 12 | 13 | def get_address(self): 14 | return self.__address 15 | 16 | def get_phone_num(self): 17 | return self.__phone_num 18 | 19 | # customer is a subclass of Person superclass 20 | class Customer(Person): 21 | def __init__(self, name, address, phone_num, cust_num, mail_list): 22 | 23 | # pass superclass' __init__ method. 24 | Person.__init__(self, name, address, phone_num) 25 | 26 | # initialize the data attributes of subclass 27 | self.__cust_num=cust_num 28 | self.__mail_list=mail_list 29 | 30 | # set accessor 31 | def get_cust_num(self): 32 | return self.__cust_num 33 | 34 | def get_mail_list(self): 35 | if self.__mail_list==1: 36 | status=True # to keep status of mailing list 37 | return "Yes" 38 | else: 39 | status=False 40 | return "No" --------------------------------------------------------------------------------