├── .gitignore ├── README.md ├── chapters ├── 10 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── bankaccount.py │ ├── bankaccount2.py │ ├── car.py │ ├── cellphone.py │ ├── coin.py │ ├── contact.py │ ├── customer.py │ └── servicequote.py ├── 11 │ ├── 03.py │ ├── 06.py │ ├── 08.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── accounts.py │ ├── animals.py │ └── vehicles.py ├── 13 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 12.py │ └── 13.py ├── 02 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 20.py │ ├── 21.py │ └── 22.py ├── 03 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ └── 08.py ├── 04 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ └── 20.py ├── 05 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 20.py │ ├── 21.py │ ├── 22.py │ ├── 23.py │ ├── 24.py │ ├── 25.py │ ├── 28.py │ ├── circle.py │ └── rectangle.py ├── 06 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── 18.py │ ├── 19.py │ ├── 20.py │ ├── 21.py │ ├── 22.py │ ├── 23.py │ ├── 24.py │ ├── 25.py │ ├── 26.py │ ├── 27.py │ ├── 28.py │ ├── 29.py │ ├── 30.py │ ├── coffee.txt │ ├── employees.txt │ ├── friends.txt │ ├── numbers.txt │ ├── philosophers.txt │ ├── sales.txt │ ├── sales_data.txt │ └── video_times.txt └── 07 │ ├── 01.py │ ├── 02.py │ ├── 03.py │ ├── 04.py │ ├── 05.py │ ├── 06.py │ ├── 07.py │ ├── 08.py │ ├── 09.py │ ├── 10.py │ ├── 11.py │ ├── 12.py │ ├── 13.py │ ├── 14.py │ ├── 15.py │ ├── 16.py │ ├── 17.py │ ├── cities.txt │ └── numbers.txt ├── homework ├── cashregister │ ├── cashregister.py │ ├── cashregister_program.py │ └── retailitem.py ├── email_address_book │ ├── email_address_book.py │ └── program.py ├── employee │ ├── employee.py │ ├── employee_program.py │ └── employee_program2.py ├── factorial.py ├── line_numbers │ ├── line_numbers.py │ └── presidents.txt ├── lo_shu_magic_square │ ├── lo_shu_magic_square.py │ └── lo_shu_magic_square_test.py ├── pet │ ├── pet.py │ └── pet_program.py ├── physics.py └── sets │ ├── set_file1.txt │ ├── set_file2.txt │ └── sets.py └── notes ├── 01.md ├── 02.md ├── 03.md ├── 04.md ├── 05.md ├── 06.md ├── 07.md ├── 10.md └── 11.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | __pycache__ 3 | *.dat -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # starting-out-with-python 2 | 3 | Programming exercises from [Starting Out with Python (3rd edition)](https://www.amazon.com/Starting-Python-Global-Tony-Gaddis/dp/1292065508/ref=sr_1_1?ie=UTF8&qid=1516599126&sr=8-1&keywords=starting+out+with+python+global) by Tony Gaddis. 4 | 5 | ## Usage 6 | 7 | I installed the latest version of Python (version 3.6). To use Python in script mode: 8 | 9 | ``` 10 | $ python3.6 file_to_run.py 11 | ``` -------------------------------------------------------------------------------- /chapters/02/01.py: -------------------------------------------------------------------------------- 1 | # Program 2-1 2 | 3 | print('Kate Austen') 4 | print('123 Full Circle Drive') 5 | print('Asheville, NC 28899') -------------------------------------------------------------------------------- /chapters/02/02.py: -------------------------------------------------------------------------------- 1 | # Program 2-2 2 | 3 | print("Kate Austen") 4 | print("123 Full Circle Drive") 5 | print("Asheville, NC 28899") -------------------------------------------------------------------------------- /chapters/02/03.py: -------------------------------------------------------------------------------- 1 | # Program 2-3 2 | 3 | print("Don't fear!") 4 | print("I'm here!") -------------------------------------------------------------------------------- /chapters/02/04.py: -------------------------------------------------------------------------------- 1 | # Program 2-4 2 | 3 | print('Your assignment is to read "Hamlet" by tomorrow.') -------------------------------------------------------------------------------- /chapters/02/05.py: -------------------------------------------------------------------------------- 1 | # Program 2-1 2 | 3 | # This program displays a person's 4 | # name and address. 5 | 6 | print('Kate Austen') 7 | print('123 Full Circle Drive') 8 | print('Asheville, NC 28899') -------------------------------------------------------------------------------- /chapters/02/06.py: -------------------------------------------------------------------------------- 1 | # Program 2-6 2 | 3 | print('Kate Austen') # Display the name. 4 | print('123 Full Circle Drive') # Display the address. 5 | print('Asheville, NC 28899') # Display the city, state, and ZIP. -------------------------------------------------------------------------------- /chapters/02/07.py: -------------------------------------------------------------------------------- 1 | # Program 2-7 2 | 3 | # This program demonstrates a variable. 4 | 5 | room = 503 6 | print('I am staying in room number') 7 | print(room) -------------------------------------------------------------------------------- /chapters/02/08.py: -------------------------------------------------------------------------------- 1 | # Program 2-8 2 | 3 | # Create two variables: top_speed and distance. 4 | top_speed = 160 5 | distance = 300 6 | 7 | # Display the values referenced by the variables. 8 | print('The top speed is') 9 | print(top_speed) 10 | print('The distance traveled is') 11 | print(Distance) -------------------------------------------------------------------------------- /chapters/02/09.py: -------------------------------------------------------------------------------- 1 | # Program 2-9 2 | 3 | # This program demonstrates a variable. 4 | 5 | room = 503 6 | print('I am staying in room number', room) -------------------------------------------------------------------------------- /chapters/02/10.py: -------------------------------------------------------------------------------- 1 | # Program 2-10 2 | 3 | # This program demonstrates variable reassignment. 4 | # Assign a value to the dollars variable. 5 | 6 | dollars = 2.75 7 | 8 | print('I have', dollars, 'in my account.') 9 | 10 | # Reassign dollars so it references 11 | # a different value. 12 | 13 | dollars = 99.95 14 | 15 | print('But now I have', dollars, 'in my account!') 16 | 17 | -------------------------------------------------------------------------------- /chapters/02/11.py: -------------------------------------------------------------------------------- 1 | # Program 2-11 2 | 3 | # Create variables to reference two strings. 4 | first_name = 'Kathryn' 5 | last_name = 'Marino' 6 | 7 | # Display the values referenced by the variables. 8 | print(first_name, last_name) -------------------------------------------------------------------------------- /chapters/02/12.py: -------------------------------------------------------------------------------- 1 | # Program 2-12 2 | 3 | # Get the user's first name. 4 | first_name = input('Enter your first name: ') 5 | 6 | # Get the user's last name. 7 | last_name = input('Enter your last name: ') 8 | 9 | # Print a greeting to the user. 10 | 11 | print('Hello', first_name, last_name) 12 | 13 | -------------------------------------------------------------------------------- /chapters/02/13.py: -------------------------------------------------------------------------------- 1 | # Program 2-13 2 | 3 | # Get the user's name, age, and income. 4 | 5 | name = input('What is your name? ') 6 | age = int(input('What is your age? ')) 7 | income = float(input('What is your income? ')) 8 | 9 | # Display the data 10 | print('Here is the data you entered:') 11 | print('Name:', name) 12 | print('Age:', age) 13 | print('Income:', income) -------------------------------------------------------------------------------- /chapters/02/14.py: -------------------------------------------------------------------------------- 1 | # Program 2-14 2 | 3 | # Assign a value to the salary variable. 4 | salary = 2500.0 5 | 6 | # Assign a value to the bonus variable. 7 | bonus = 1200.0 8 | 9 | # Calculate the total pay by adding salary 10 | # and bonus. Assign the result to pay. 11 | pay = salary + bonus 12 | 13 | # Display the pay. 14 | print('Your pay is', pay) -------------------------------------------------------------------------------- /chapters/02/15.py: -------------------------------------------------------------------------------- 1 | # Program 2-15 2 | 3 | # This program gets an item's original price and 4 | # calculates its sale price, with a 20% discount. 5 | 6 | # Get the item's original price. 7 | original_price = float(input('Enter the original price: ')) 8 | 9 | # Calculate the amount of the discount 10 | discount = original_price * 0.2 11 | 12 | # Calculate the sale price. 13 | sale_price = original_price - discount 14 | 15 | # Display the sale price. 16 | print('The sale price is', sale_price) 17 | 18 | -------------------------------------------------------------------------------- /chapters/02/16.py: -------------------------------------------------------------------------------- 1 | # Program 2-16 2 | 3 | # Get three test scores and assign them to the 4 | # test1, test2, and test3 variables 5 | 6 | test1 = float(input('Enter the first test score: ')) 7 | test2 = float(input('Enter the second test score: ')) 8 | test3 = float(input('Enter the third test score: ')) 9 | 10 | # Calculate the average of the three scores 11 | # and assign the result to the average variable. 12 | average = (test1 + test2 + test3) / 3.0 13 | 14 | # Display the average. 15 | print('The average score is', average) -------------------------------------------------------------------------------- /chapters/02/17.py: -------------------------------------------------------------------------------- 1 | # Program 2-17 2 | 3 | # Get a number of seconds from the user 4 | 5 | total_seconds = float(input('Enter the number of seconds: ')) 6 | 7 | # Get the number of hours. 8 | 9 | hours = total_seconds // 3600 10 | 11 | # Get the number of remaining minutes. 12 | minutes = (total_seconds // 60) % 60 13 | 14 | # Get the number of remaining seconds. 15 | seconds = total_seconds % 60 16 | 17 | # Display the results. 18 | 19 | print('Here is the time in hours, minutes, and seconds:') 20 | print('Hours:', hours) 21 | print('Minutes:', minutes) 22 | print('Seconds:', seconds) -------------------------------------------------------------------------------- /chapters/02/18.py: -------------------------------------------------------------------------------- 1 | # Program 2-18 2 | 3 | # Get the desired future value. 4 | future_value = float(input('Enter the desired future value: ')) 5 | 6 | # Get the annual interest rate. 7 | rate = float(input('Enter the annual interest rate: ')) 8 | 9 | # Get the number of years that the money will appreciate. 10 | years = int(input('Enter the number of years the money will grow: ')) 11 | 12 | # Calculate the amount needed to deposit. 13 | present_value = future_value / (1.0 + rate)**years 14 | 15 | #Display the amount needed to depost. 16 | print('You will need to deposit this amount:', present_value) -------------------------------------------------------------------------------- /chapters/02/19.py: -------------------------------------------------------------------------------- 1 | # Program 2-19 2 | 3 | # This program demonstrates how a floating-point 4 | # number is displayed with no formatting. 5 | 6 | amount_due = 5000.0 7 | monthly_payment = amount_due / 12.0 8 | print('The monthly payment is', monthly_payment) -------------------------------------------------------------------------------- /chapters/02/20.py: -------------------------------------------------------------------------------- 1 | # Program 2-20 2 | 3 | # This program demonstrates how a floating-point 4 | # number can be formatted. 5 | amount_due = 5000.0 6 | monthly_payment = amount_due / 12 7 | print('The monthly payment is', \ 8 | format(monthly_payment, '.2f')) -------------------------------------------------------------------------------- /chapters/02/21.py: -------------------------------------------------------------------------------- 1 | # Program 2-21 2 | 3 | # This program demonstrates how a floating-point 4 | # number can be displayed as currency. 5 | 6 | monthly_pay = 5000.0 7 | annual_pay = monthly_pay * 12 8 | 9 | print('Your annual pay is $', \ 10 | format(annual_pay, ',.2f'), \ 11 | sep='') -------------------------------------------------------------------------------- /chapters/02/22.py: -------------------------------------------------------------------------------- 1 | # Program 22-2 2 | 3 | # This program displays the following 4 | # floating-point numbers in a column 5 | # with their decimal points aligned. 6 | 7 | num1 = 127.899 8 | num2 = 3465.148 9 | num3 = 3.776 10 | num4 = 264.821 11 | num5 = 88.081 12 | num6 = 799.999 13 | 14 | # Display each number in a field of 7 spaces 15 | # with 2 decimal places. 16 | 17 | print(format(num1, '7.2f')) 18 | print(format(num2, '7.2f')) 19 | print(format(num3, '7.2f')) 20 | print(format(num4, '7.2f')) 21 | print(format(num5, '7.2f')) 22 | print(format(num6, '7.2f')) -------------------------------------------------------------------------------- /chapters/03/01.py: -------------------------------------------------------------------------------- 1 | # Program 3-1 2 | 3 | # This program gets three test scores and displays 4 | # their average. It congratulates the user if the 5 | # average is a high score. 6 | 7 | # The high score variable holds the value that is 8 | # considered a high score. 9 | 10 | high_score = 95 11 | 12 | # Get the three test scores. 13 | test1 = int(input('Enter the score for test 1: ')) 14 | test2 = int(input('Enter the score for test 2: ')) 15 | test3 = int(input('Enter the score for test 3: ')) 16 | 17 | # Calculate the average test score. 18 | average = (test1 + test2 + test3) / 3 19 | 20 | # Print the average 21 | print('The average score is', average) 22 | 23 | # If the average is a high score, 24 | # congratulate the user. 25 | 26 | if average >= high_score: 27 | print('Congratulations!') 28 | print('That is a great average!') 29 | 30 | -------------------------------------------------------------------------------- /chapters/03/02.py: -------------------------------------------------------------------------------- 1 | # Program 3-2 2 | 3 | # Variables to represent the base hours and 4 | # the overtime multiplier. 5 | base_hours = 40 # Base hours per week 6 | ot_multiplier = 1.5 # Overtime multiplier 7 | 8 | # Get the hours worked and the hourly pay rate. 9 | hours = float(input('Enter the number of hours worked: ')) 10 | pay_rate = float(input('Enter the hourly pay rate: ')) 11 | 12 | # Calculate and display the gross pay. 13 | if hours > base_hours: 14 | # Calculate the gross pay with overtime. 15 | # First, get the number of overtime hours worked. 16 | overtime_hours = hours - base_hours 17 | 18 | # Calculate the amount of overtime pay. 19 | overtime_pay = overtime_hours * pay_rate * ot_multiplier 20 | 21 | # Calculate the gross pay 22 | gross_pay = base_hours * pay_rate + overtime_pay 23 | else: 24 | # Calculate the gross pay without overtime. 25 | gross_pay = hours * pay_rate 26 | 27 | # Display the gross pay. 28 | print('The gross pay is $', format(gross_pay, ',.2f'), sep='') -------------------------------------------------------------------------------- /chapters/03/03.py: -------------------------------------------------------------------------------- 1 | # Program 3-3 2 | 3 | # This program compares two strings. 4 | # Get a password from the user. 5 | password = input('Enter the password: ') 6 | 7 | # Determine whether the correct password 8 | # was entered. 9 | if password == 'prospero': 10 | print('Password accepted.') 11 | else: 12 | print('Sorry, that is the wrong password.') -------------------------------------------------------------------------------- /chapters/03/04.py: -------------------------------------------------------------------------------- 1 | # Program 3-4 2 | 3 | # This program compares strings with the < operator. 4 | 5 | # Get two names from the user. 6 | name1 = input('Enter a name (last name first): ') 7 | name2 = input('Enter a name (last name first): ') 8 | 9 | # Display the names in alphabetical order. 10 | print('Here are the names, listed alphabetically.') 11 | 12 | if name1 < name2: 13 | print(name1) 14 | print(name2) 15 | else: 16 | print(name2) 17 | print(name1) -------------------------------------------------------------------------------- /chapters/03/05.py: -------------------------------------------------------------------------------- 1 | # Program 3-5 2 | 3 | # This program determines whether a bank customer 4 | # qualifies for a loan. 5 | 6 | min_salary = 30000.0 # The minimum annual salary 7 | min_years = 2 # The minimum years on the job 8 | 9 | # Get the customer's annual salary. 10 | salary = float(input('Enter your annual salary: ')) 11 | 12 | # Get the number of years on the current job. 13 | years_on_job = int(input('Enter the number of years employed: ')) 14 | 15 | # Determine whether the customer qualifies: 16 | if salary >= min_salary: 17 | if years_on_job >= min_years: 18 | print('You qualify for the loan.') 19 | else: 20 | print('You must have been employed' + 21 | ' for at least', min_years, 'years to qualify.') 22 | else: 23 | print('You must earn at least $', 24 | format(min_salary, ',.2f'), 25 | ' per year to qualify.', sep='') 26 | -------------------------------------------------------------------------------- /chapters/03/06.py: -------------------------------------------------------------------------------- 1 | # Program 3-6 2 | 3 | # This program gets a numeric test score from the 4 | # user and displays the corresponding letter grade. 5 | 6 | # Variables to represent the grade thresholds 7 | A_score = 90 8 | B_score = 80 9 | C_score = 70 10 | D_score = 60 11 | 12 | # Get a test score from the user. 13 | score = int(input('Enter your test score: ')) 14 | 15 | # Determine the grade. 16 | if score >= A_score: 17 | print('Grade A') 18 | else: 19 | if score >= B_score: 20 | print('Grade B') 21 | else: 22 | if score >= C_score: 23 | print('Grade C') 24 | else: 25 | if score >= D_score: 26 | print('Grade D') 27 | else: 28 | print('Grade F') -------------------------------------------------------------------------------- /chapters/03/07.py: -------------------------------------------------------------------------------- 1 | # Program 3-7 2 | 3 | # This program determines whether a bank customer 4 | # qualifies for a loan. 5 | 6 | min_salary = 30000.0 # The minimum annual salary 7 | min_years = 2 # The minimum years on the job 8 | 9 | # Get the customer's annual salary. 10 | salary = float(input('Enter your annual salary: ')) 11 | 12 | # Get the number of years on the current job. 13 | years_on_job = int(input('Enter the number of years employed: ')) 14 | 15 | # Determine whether the customer qualifies: 16 | 17 | if salary >= min_salary and years_on_job >= min_years: 18 | print('You qualify for the loan.') 19 | else: 20 | print('You do NOT qualify for the loan.') -------------------------------------------------------------------------------- /chapters/03/08.py: -------------------------------------------------------------------------------- 1 | # Program 3-8 2 | 3 | # This program determines whether a bank customer 4 | # qualifies for a loan. 5 | 6 | min_salary = 30000.0 # The minimum annual salary 7 | min_years = 2 # The minimum years on the job 8 | 9 | # Get the customer's annual salary. 10 | salary = float(input('Enter your annual salary: ')) 11 | 12 | # Get the number of years on the current job. 13 | years_on_job = int(input('Enter the number of years employed: ')) 14 | 15 | # Determine whether the customer qualifies: 16 | 17 | if salary >= min_salary or years_on_job >= min_years: 18 | print('You qualify for the loan.') 19 | else: 20 | print('You do NOT qualify for the loan.') -------------------------------------------------------------------------------- /chapters/04/01.py: -------------------------------------------------------------------------------- 1 | # Program 4-1 2 | # This program calculates sales commissions. 3 | 4 | # Create a variable to control the loop 5 | keep_going = 'y' 6 | 7 | # Calculate a series of commissions 8 | while keep_going == 'y': 9 | # Get a salesperson's sales and commission rate. 10 | sales = float(input('Enter the amount of sales: ')) 11 | comm_rate = float(input('Enter the commission rate: ')) 12 | 13 | # Calculate commission 14 | commission = sales * comm_rate 15 | 16 | # Display commission 17 | print('This commission is $', format(commission, ',.2f'), sep='') 18 | 19 | # See if the user wants to do another calculation 20 | keep_going = input('Do you want to calculate another ' + 21 | 'commission? (Enter y for yes): ') -------------------------------------------------------------------------------- /chapters/04/02.py: -------------------------------------------------------------------------------- 1 | # Program 4-2 2 | # This program assists a technician in the process 3 | # of checking a substance's temperature. 4 | 5 | # Create a variable to represent the maximum 6 | # temperature. 7 | max_temp = 102.5 8 | 9 | # Get temperature of substance 10 | temperature = float(input('Enter the substance\'s Celsius temperature: ')) 11 | 12 | # As long as necessary, instruct the user to 13 | # adjust the thermostat. 14 | while temperature > max_temp: 15 | print('The temperature is too high.\n' + 16 | 'Turn the thermostat down and wait\n' + 17 | '5 minutes. Then take the temperature\n' + 18 | 'again and enter it.\n' 19 | ) 20 | temperature = float(input('Enter the substance\'s Celsius temperature: ')) 21 | 22 | # Remind the user to check the temperature again 23 | # in 15 minutes. 24 | print('The temperature is acceptable.\n' + 25 | 'Check it again in 15 minutes.' 26 | ) -------------------------------------------------------------------------------- /chapters/04/03.py: -------------------------------------------------------------------------------- 1 | # Program 4-3 2 | # This program demonstrates an infinite loop. 3 | 4 | # Create a variable to represent the maximum 5 | # temperature. 6 | max_temp = 102.5 7 | 8 | # Get temperature of substance 9 | temperature = float(input('Enter the substance\'s Celsius temperature: ')) 10 | 11 | # As long as necessary, instruct the user to 12 | # adjust the thermostat. 13 | while temperature > max_temp: 14 | print('The temperature is too high.\n' + 15 | 'Turn the thermostat down and wait\n' + 16 | '5 minutes. Then take the temperature\n' + 17 | 'again and enter it.\n' 18 | ) 19 | # No way to stop the loop now 20 | # temperature = float(input('Enter the substance\'s Celsius temperature: ')) 21 | 22 | # Remind the user to check the temperature again 23 | # in 15 minutes. 24 | print('The temperature is acceptable.\n' + 25 | 'Check it again in 15 minutes.' 26 | ) -------------------------------------------------------------------------------- /chapters/04/04.py: -------------------------------------------------------------------------------- 1 | # Program 4-4 2 | # This program demonstrates a simple for loop 3 | 4 | print('I will display numbers 1 through 5.') 5 | 6 | for num in [1, 2, 3, 4, 5]: 7 | print(num) -------------------------------------------------------------------------------- /chapters/04/05.py: -------------------------------------------------------------------------------- 1 | # Program 4-5 2 | # Demonstrates simple for loop 3 | # that uses a list of numbers. 4 | 5 | print('I will display the odd numbers 1 through 9.') 6 | for num in [1, 3, 5, 7, 9]: 7 | print(num) -------------------------------------------------------------------------------- /chapters/04/06.py: -------------------------------------------------------------------------------- 1 | # Program 4-6 2 | # This loop demonstrates a simple for 3 | # loop that uses a list of strings. 4 | 5 | for name in ['Winken', 'Blinken', 'Nod']: 6 | print(name) -------------------------------------------------------------------------------- /chapters/04/07.py: -------------------------------------------------------------------------------- 1 | # Program 4-7 2 | # This program demonstrates how the range 3 | # function can be used with a for loop. 4 | 5 | # Print a message 5 times. 6 | for x in range(5): 7 | print('Hello world!') -------------------------------------------------------------------------------- /chapters/04/08.py: -------------------------------------------------------------------------------- 1 | # Program 4-8 2 | # This program uses a loop to display a 3 | # table showing the numbers 1 through 10 4 | # and their squares. 5 | 6 | # Print the table headings, 7 | print('Number\tSquare\n--------------') 8 | 9 | # Print the numbers 1 through 10 10 | # and their squares. 11 | for number in range(1, 11): 12 | square = number**2 13 | print(number, '\t', square) -------------------------------------------------------------------------------- /chapters/04/09.py: -------------------------------------------------------------------------------- 1 | # Program 4-9 2 | 3 | print('KPH\tMPH\n--------------') 4 | 5 | for kph in range(60, 131, 10): 6 | mph = format(kph * 0.6214, ',.1f') 7 | print(kph, '\t', mph) -------------------------------------------------------------------------------- /chapters/04/10.py: -------------------------------------------------------------------------------- 1 | # Program 4-10 2 | 3 | print('This program displays a list of numbers\n' + 4 | '(starting at 1) and their squares.') 5 | 6 | end = int(input('How high should I go? ')) 7 | 8 | print('\nNumber\tSquares\n---------------') 9 | 10 | for num in range(1, end + 1): 11 | square = num ** 2 12 | print(num, '\t', square) -------------------------------------------------------------------------------- /chapters/04/11.py: -------------------------------------------------------------------------------- 1 | # Program 4-11 2 | # This program uses a loop to display a 3 | # table of numbers and their squares. 4 | 5 | print('This program displays a list of numbers and their squares.') 6 | 7 | start = int(input('Start at: ')) 8 | end = int(input('End at: ')) 9 | 10 | print('\nNumber\tSquares\n---------------') 11 | 12 | for num in range(start, end + 1): 13 | square = num ** 2 14 | print(num, '\t', square) -------------------------------------------------------------------------------- /chapters/04/12.py: -------------------------------------------------------------------------------- 1 | # Program 4-12 2 | # This program calculates the sum of a series 3 | # of numbers entered by the user. 4 | 5 | # The maximum number 6 | max = 5 7 | 8 | # Initialize the accumulator 9 | total = 0 10 | 11 | # Explain the purpose of the program 12 | print('This program calculates the\nsum of', 13 | max, 'numbers you will enter.\n') 14 | 15 | # Get the numbers and accumulate them. 16 | for counter in range(max): 17 | number = int(input('Enter a number: ')) 18 | total += number 19 | 20 | # Display total 21 | print('Total:', total) -------------------------------------------------------------------------------- /chapters/04/13.py: -------------------------------------------------------------------------------- 1 | # Program 4-13 2 | 3 | # Get the first lot number. 4 | print('Enter the property lot number\nor enter 0 to end.') 5 | lot = int(input('Lot number: ')) 6 | 7 | # Continue processing as long as 8 | # the user does not enter lot number 0 9 | while lot != 0: 10 | # Get property value 11 | value = float(input('Property value: ')) 12 | 13 | # Calculate the property's tax. 14 | tax = value * 0.0065 15 | 16 | # Display the tax. 17 | print('Property tax: $', format(tax, ',.2f'), sep='') 18 | 19 | # Get the next lot number. 20 | print('Enter the property lot number\nor enter 0 to end.') 21 | lot = int(input('Lot number: ')) -------------------------------------------------------------------------------- /chapters/04/14.py: -------------------------------------------------------------------------------- 1 | # Program 4-14 2 | # Displays gross pay. 3 | 4 | # Get hours worked 5 | hours = int(input('Enter hours worked this week: ')) 6 | 7 | # Get hourly pay rate 8 | pay_rate = float(input('Enter pay rate: ')) 9 | 10 | # Calculate gross pay 11 | gross_pay = hours * pay_rate 12 | 13 | # Display gross pay 14 | print('Gross pay: $', format(gross_pay, ',.2f'), sep='') -------------------------------------------------------------------------------- /chapters/04/15.py: -------------------------------------------------------------------------------- 1 | # Program 4-15 2 | # Calculate retail price 3 | 4 | mark_up = 2.5 5 | another = 'y' # Control loop 6 | 7 | while another == 'y' or another == 'Y': 8 | # Get wholesale cost. 9 | wholesale = float(input('Enter the item\'s' + 10 | ' wholesale cost: ')) 11 | 12 | # Calculate retail price 13 | retail = wholesale * mark_up 14 | 15 | print('Retail price: $', format(retail, ',.2f'), sep='') 16 | 17 | # Again? 18 | another = input('Another item? (Enter y for yes): ') -------------------------------------------------------------------------------- /chapters/04/16.py: -------------------------------------------------------------------------------- 1 | # Program 4-16 2 | # Calculate retail price 3 | 4 | mark_up = 2.5 5 | another = 'y' # Control loop 6 | 7 | while another == 'y' or another == 'Y': 8 | # Get wholesale cost. 9 | wholesale = float(input('Enter the item\'s' + 10 | ' wholesale cost: ')) 11 | 12 | # Validate wholesale cost. 13 | while wholesale < 0: 14 | print('Error: Wholesale cost cannot be negative!') 15 | wholesale = float(input('Enter the item\'s' + 16 | ' wholesale cost: ')) 17 | 18 | # Calculate retail price 19 | retail = wholesale * mark_up 20 | 21 | print('Retail price: $', format(retail, ',.2f'), sep='') 22 | 23 | # Again? 24 | another = input('Another item? (Enter y for yes): ') -------------------------------------------------------------------------------- /chapters/04/17.py: -------------------------------------------------------------------------------- 1 | # Program 4-17 2 | # This program averages test scores. It asks the user for the 3 | # number of students and the number of test scores per student. 4 | 5 | # Get the number of students. 6 | num_students = int(input('How many students? ')) 7 | 8 | # Get the number of test scores per student 9 | num_test_scores = int(input('How many test scores per student? ')) 10 | 11 | for student in range(num_students): 12 | total = 0.0 13 | print('Student number', student + 1, '\n--------------') 14 | for test_num in range(num_test_scores): 15 | print('Test number', test_num + 1, end='') 16 | score = float(input(': ')) 17 | total += score 18 | 19 | average = format(total / num_test_scores, '.1f') 20 | 21 | print('Average for student number', student + 1, 'is:', average, '\n') -------------------------------------------------------------------------------- /chapters/04/18.py: -------------------------------------------------------------------------------- 1 | # Program 4-18 2 | # Rectangle pattern of asterisks. 3 | 4 | rows = 3 5 | cols = 3 6 | 7 | for r in range(rows): 8 | for c in range(cols): 9 | print('*', end='') 10 | print() -------------------------------------------------------------------------------- /chapters/04/19.py: -------------------------------------------------------------------------------- 1 | # Program 4-19 2 | # Triangle pattern of asterisks 3 | 4 | size = 8 5 | 6 | for r in range(size): 7 | for c in range(r + 1): 8 | print('*', end='') 9 | print() -------------------------------------------------------------------------------- /chapters/04/20.py: -------------------------------------------------------------------------------- 1 | # Program 4-20 2 | # Stair-step pattern 3 | 4 | steps = 5 5 | 6 | for r in range(steps): 7 | for c in range(r): 8 | print(' ', end='') 9 | print('#') -------------------------------------------------------------------------------- /chapters/05/01.py: -------------------------------------------------------------------------------- 1 | # Program 5-1 2 | # This program demonstrates a function. 3 | # First, we define a function named message. 4 | 5 | def message(): 6 | print('I am Arthur,') 7 | print('King of the Britons.') 8 | 9 | # Call the message function 10 | message() -------------------------------------------------------------------------------- /chapters/05/02.py: -------------------------------------------------------------------------------- 1 | # Program 5-2 2 | # This program has two functions. First we 3 | # define the main function. 4 | 5 | def main(): 6 | print('I have a message for you.') 7 | message() 8 | print('Goodbye!') 9 | 10 | # Next, we define the message function 11 | def message(): 12 | print('I am Arthur,') 13 | print('King of the Britons') 14 | 15 | # Call the main function. 16 | main() -------------------------------------------------------------------------------- /chapters/05/03.py: -------------------------------------------------------------------------------- 1 | # Program 5-3 2 | # This program displays step-by-step instructions 3 | # for disassembling an Acme dryer. 4 | 5 | # The main function performs the program's main logic. 6 | def main(): 7 | startup_message() 8 | 9 | input('Press Enter to see Step 1.') 10 | step1() 11 | 12 | input('Press Enter to see Step 2.') 13 | step2() 14 | 15 | input('Press Enter to see Step 3.') 16 | step3() 17 | 18 | input('Press Enter to see Step 4.') 19 | step4() 20 | 21 | def startup_message(): 22 | print('This program tells you how to') 23 | print('disassemble an ACME laundry dryer.') 24 | print('There are 4 steps in the process.') 25 | print() 26 | 27 | def step1(): 28 | print('Step 1: Unplug the dryer and move it away from the wall.') 29 | print() 30 | 31 | def step2(): 32 | print('Step 2: Remove the six screws from the back of the dryer.') 33 | print() 34 | 35 | def step3(): 36 | print('Step 3: Remove the back panel.') 37 | print() 38 | 39 | def step4(): 40 | print('Step 4: Pull the top of the dryer straight up.') 41 | print() 42 | 43 | main() -------------------------------------------------------------------------------- /chapters/05/04.py: -------------------------------------------------------------------------------- 1 | # Program 5-4 2 | # Local variable error demo. 3 | 4 | def main(): 5 | get_name() 6 | print('Hello', name) # Error 7 | 8 | def get_name(): 9 | name = input('Enter your name: ') 10 | 11 | main() -------------------------------------------------------------------------------- /chapters/05/05.py: -------------------------------------------------------------------------------- 1 | # Program 5-5 2 | # Demonstrates two functions that 3 | # have local variables with the same name. 4 | 5 | def main(): 6 | 7 | texas() 8 | california() 9 | 10 | def texas(): 11 | birds = 5000 12 | print('Texas has', birds, 'birds.') 13 | 14 | def california(): 15 | birds = 8000 16 | print('California has', birds, 'birds.') 17 | 18 | main() -------------------------------------------------------------------------------- /chapters/05/06.py: -------------------------------------------------------------------------------- 1 | # Program 5-6 2 | # Demonstrates arguments 3 | 4 | def main(): 5 | value = 5 6 | show_double(value) 7 | 8 | def show_double(number): 9 | result = number * 2 10 | print(result) 11 | 12 | main() -------------------------------------------------------------------------------- /chapters/05/07.py: -------------------------------------------------------------------------------- 1 | # Program 5-7 2 | # Converts cups to fluid ounces. 3 | 4 | def main(): 5 | intro() 6 | 7 | cups_needed = int(input('Enter the number of cups: ')) 8 | 9 | cups_to_ounces(cups_needed) 10 | 11 | def intro(): 12 | print('This program converts measurements in cups\n' + 13 | 'to fluid ounces. For your reference the\n' + 14 | 'formula is: 1 cup = 8 fluid ounces\n' 15 | ) 16 | 17 | def cups_to_ounces(cups): 18 | ounces = cups * 8 19 | print('That converts to', ounces, 'ounces.') 20 | 21 | main() -------------------------------------------------------------------------------- /chapters/05/08.py: -------------------------------------------------------------------------------- 1 | # Program 5-8 2 | # Demonstrates a function that accepts two arguments. 3 | 4 | def main(): 5 | print('The sum of 12 and 45 is') 6 | show_sum(12, 45) 7 | 8 | def show_sum(a, b): 9 | print(a + b) 10 | 11 | main() -------------------------------------------------------------------------------- /chapters/05/09.py: -------------------------------------------------------------------------------- 1 | # Program 5-9 2 | # Demonstrates passing two string 3 | # arguments to a function. 4 | 5 | def main(): 6 | first_name = input('First name: ') 7 | last_name = input('Last name: ') 8 | print('Your name reversed is') 9 | reverse_name(first_name, last_name) 10 | 11 | def reverse_name(first, last): 12 | print(last, ', ', first, sep='') 13 | 14 | main() -------------------------------------------------------------------------------- /chapters/05/10.py: -------------------------------------------------------------------------------- 1 | # Program 5-10 2 | # Demonstrates what happens when you 3 | # change the value of a parameter. 4 | 5 | def main(): 6 | value = 99 7 | print('The value is', value) 8 | change_me(value) 9 | print('Back in main the value is', value) 10 | 11 | def change_me(arg): 12 | print('I am changing the value.') 13 | arg = 0 14 | print('The value is now', arg) 15 | 16 | main() -------------------------------------------------------------------------------- /chapters/05/11.py: -------------------------------------------------------------------------------- 1 | # Program 5-11 2 | # This program demonstrates keyword arguments. 3 | 4 | def main(): 5 | show_interest(rate=0.01, periods=10, principal=10000.0) 6 | 7 | def show_interest(principal, rate, periods): 8 | interest = principal * rate * periods 9 | print('The simple interest will be $', \ 10 | format(interest, ',.2f'), \ 11 | sep='') 12 | 13 | main() -------------------------------------------------------------------------------- /chapters/05/12.py: -------------------------------------------------------------------------------- 1 | # Program 5-12 2 | # Demonstrates passing two string 3 | # arguments to a function using keyword arguments. 4 | 5 | def main(): 6 | first_name = input('First name: ') 7 | last_name = input('Last name: ') 8 | print('Your name reversed is') 9 | reverse_name(last=first_name, first=last_name) 10 | 11 | def reverse_name(first, last): 12 | print(last, ', ', first, sep='') 13 | 14 | main() -------------------------------------------------------------------------------- /chapters/05/13.py: -------------------------------------------------------------------------------- 1 | # Program 5-13 2 | 3 | # Global variable 4 | my_value = 10 5 | 6 | def show_value(): 7 | print(my_value) 8 | 9 | show_value() -------------------------------------------------------------------------------- /chapters/05/14.py: -------------------------------------------------------------------------------- 1 | # Program 5-14 2 | 3 | number = 0 4 | 5 | def main(): 6 | global number 7 | number = int(input('Enter a number: ')) 8 | show_number() 9 | 10 | def show_number(): 11 | print('The number is', number) 12 | 13 | main() -------------------------------------------------------------------------------- /chapters/05/15.py: -------------------------------------------------------------------------------- 1 | # Program 5-15 2 | 3 | CONTRIBUTION_RATE = 0.05 # global constant 4 | 5 | def main(): 6 | gross_pay = float(input('Enter gross pay: ')) 7 | bonus = float(input('Enter bonus: ')) 8 | show_pay_contrib(gross_pay) 9 | show_bonus_contrib(bonus) 10 | 11 | def show_pay_contrib(gross): 12 | contrib = gross * CONTRIBUTION_RATE 13 | print('Contribution for gross pay: $', \ 14 | format(contrib, ',.2f'), \ 15 | sep='') 16 | 17 | def show_bonus_contrib(bonus): 18 | contrib = bonus * CONTRIBUTION_RATE 19 | print('Contribution for bonuses: $', \ 20 | format(contrib, ',.2f'), \ 21 | sep='') 22 | 23 | main() -------------------------------------------------------------------------------- /chapters/05/16.py: -------------------------------------------------------------------------------- 1 | # Program 5-16 2 | 3 | import random 4 | 5 | def main(): 6 | 7 | number = random.randint(0, 100) 8 | print('The number is', number) 9 | 10 | main() -------------------------------------------------------------------------------- /chapters/05/17.py: -------------------------------------------------------------------------------- 1 | # Program 5-17 2 | 3 | import random 4 | 5 | def main(): 6 | 7 | for count in range(5): 8 | number = random.randint(0, 100) 9 | print('The number is', number) 10 | 11 | main() -------------------------------------------------------------------------------- /chapters/05/18.py: -------------------------------------------------------------------------------- 1 | # Program 5-18 2 | 3 | import random 4 | 5 | def main(): 6 | 7 | for count in range(5): 8 | print(random.randint(0, 100)) 9 | 10 | main() -------------------------------------------------------------------------------- /chapters/05/19.py: -------------------------------------------------------------------------------- 1 | # Program 5-19 2 | 3 | import random 4 | 5 | MIN = 1 6 | MAX = 6 7 | 8 | def main(): 9 | 10 | again = 'y' 11 | 12 | while again.lower() == 'y': 13 | print('Rolling the dice...') 14 | print('Their values are:') 15 | print(random.randint(MIN, MAX)) 16 | print(random.randint(MIN, MAX)) 17 | 18 | # go again? 19 | again = input('Roll again? (y = yes): ') 20 | 21 | main() -------------------------------------------------------------------------------- /chapters/05/20.py: -------------------------------------------------------------------------------- 1 | # Program 5-20 2 | # Simulates 10 tosses of a coin. 3 | 4 | import random 5 | 6 | HEADS = 1 7 | TAILS = 2 8 | TOSSES = 10 9 | 10 | def main(): 11 | for toss in range(TOSSES): 12 | if random.randint(HEADS, TAILS) == HEADS: 13 | print('Heads') 14 | else: 15 | print('Tails') 16 | 17 | main() -------------------------------------------------------------------------------- /chapters/05/21.py: -------------------------------------------------------------------------------- 1 | # Program 5-21 2 | 3 | def main(): 4 | first_age = int(input('Enter your age: ')) 5 | 6 | second_age = int(input('Enter your best friend\'s age: ')) 7 | 8 | total = sum(first_age, second_age) 9 | 10 | print('Together you are both', total, 'years old.') 11 | 12 | def sum(a, b): 13 | return a + b 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/05/22.py: -------------------------------------------------------------------------------- 1 | # Program 5-22 2 | # Calculates a retual item's 3 | # sale price. 4 | 5 | DISCOUNT_PERCENTAGE = 0.20 6 | 7 | def main(): 8 | reg_price = get_regular_price() 9 | 10 | sales_price = reg_price - discount(reg_price) 11 | 12 | print('The sale price is $', format(sales_price, ',.2f'), sep='') 13 | 14 | def get_regular_price(): 15 | price = float(input('Enter the item\'s regular price: ')) 16 | return price 17 | 18 | def discount(price): 19 | return price * DISCOUNT_PERCENTAGE 20 | 21 | main() -------------------------------------------------------------------------------- /chapters/05/23.py: -------------------------------------------------------------------------------- 1 | # Program 5-23 2 | 3 | def main(): 4 | 5 | sales = get_sales() 6 | 7 | advanced_pay = get_advanced_pay() 8 | 9 | comm_rate = determine_comm_rate(sales) 10 | 11 | pay = sales * comm_rate - advanced_pay 12 | 13 | print('The pay is $', format(pay, ',.2f'), sep='') 14 | 15 | if(pay < 0): 16 | print('The Salesperson must reimburse the company.') 17 | 18 | def get_sales(): 19 | monthly_sales = float(input('Enter monthly sales: ')) 20 | return monthly_sales 21 | 22 | def get_advanced_pay(): 23 | print('Enter the amount of advanced pay, or') 24 | print('enter 0 if no advanced pay was given.') 25 | advanced = float(input('Advanced pay: ')) 26 | 27 | return advanced 28 | 29 | def determine_comm_rate(sales): 30 | 31 | if sales < 10000.00: 32 | rate = 0.10 33 | elif sales >= 10000 and sales <= 14999.99: 34 | rate = 0.12 35 | elif sales >= 15000 and sales <= 17999.99: 36 | rate = 0.14 37 | elif sales >= 180000 and sales <= 21999.99: 38 | rate = 0.16 39 | else: 40 | rate = 0.18 41 | 42 | return rate 43 | 44 | main() -------------------------------------------------------------------------------- /chapters/05/24.py: -------------------------------------------------------------------------------- 1 | # Program 5-24 2 | 3 | import math 4 | 5 | def main(): 6 | number = float(input('Enter a number: ')) 7 | 8 | square_root = math.sqrt(number) 9 | 10 | print('The square root of', number, 'is', square_root) 11 | 12 | main() -------------------------------------------------------------------------------- /chapters/05/25.py: -------------------------------------------------------------------------------- 1 | # Program 5-25 2 | 3 | import math 4 | 5 | def main(): 6 | # Get the length of the triangle's two sides. 7 | a = float(input('Enter length of side A: ')) 8 | b = float(input('Enter length of side B: ')) 9 | 10 | # Calculate hypotenuse 11 | c = math.hypot(a, b) 12 | 13 | print('The length of the hypotenuse is', c) 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/05/28.py: -------------------------------------------------------------------------------- 1 | # Program 5-28 2 | 3 | import circle 4 | import rectangle 5 | 6 | AREA_CIRCLE_CHOICE = 1 7 | CIRCUMFERENCE_CHOICE = 2 8 | AREA_RECTANGLE_CHOICE = 3 9 | PERIMETER_RECTANGLE_CHOICE = 4 10 | QUIT_CHOICE = 5 11 | 12 | def main(): 13 | 14 | choice = 0 15 | 16 | while choice != QUIT_CHOICE: 17 | 18 | display_menu() 19 | 20 | choice = int(input('Enter your choice: ')) 21 | 22 | if choice == AREA_CIRCLE_CHOICE: 23 | radius = float(input('Enter the circle\'s radius: ')) 24 | print('The area is', circle.area(radius)) 25 | elif choice == CIRCUMFERENCE_CHOICE: 26 | radius = float(input('Enter the circle\'s radius: ')) 27 | print('The circumference is', \ 28 | circle.circumference(radius)) 29 | elif choice == AREA_RECTANGLE_CHOICE: 30 | width = float(input('Enter the rectangle\'s width: ')) 31 | height = float(input('Enter the rectangle\'s height: ')) 32 | print('The area is', \ 33 | rectangle.area(width, height)) 34 | elif choice == PERIMETER_RECTANGLE_CHOICE: 35 | width = float(input('Enter the rectangle\'s width: ')) 36 | height = float(input('Enter the rectangle\'s height: ')) 37 | print('The perimeter is', \ 38 | rectangle.perimeter(width, height)) 39 | elif choice == QUIT_CHOICE: 40 | print('Exiting the program...') 41 | else: 42 | print('Error: Invalid selection.') 43 | 44 | def display_menu(): 45 | print('MENU') 46 | print('1: Area of a circle') 47 | print('2: Circumference of a circle') 48 | print('3: Area of a rectangle') 49 | print('4: Perimeter of a rectangle') 50 | print('5: Quit') 51 | 52 | main() -------------------------------------------------------------------------------- /chapters/05/circle.py: -------------------------------------------------------------------------------- 1 | # Program 5-26 2 | 3 | # The circle module has functions that perform 4 | # calculations related to circles. 5 | 6 | import math 7 | 8 | def area(radius): 9 | return math.pi * radius**2 10 | 11 | def circumference(radius): 12 | return 2 * math.pi * radius 13 | 14 | -------------------------------------------------------------------------------- /chapters/05/rectangle.py: -------------------------------------------------------------------------------- 1 | # Program 5-27 2 | 3 | # The rectangle module has functions that perform 4 | # calculations related to rectangles. 5 | 6 | def area(width, length): 7 | return width * length 8 | 9 | def perimeter(width, length): 10 | return 2 * (width + length) 11 | 12 | -------------------------------------------------------------------------------- /chapters/06/01.py: -------------------------------------------------------------------------------- 1 | # Program 6-1 2 | # This program writes three lines of data 3 | # to a file. 4 | 5 | def main(): 6 | # Open a file 7 | outfile = open('philosophers.txt', 'w') 8 | 9 | # Write to the file 10 | outfile.write('John Lock\n') 11 | outfile.write('David Hume\n') 12 | outfile.write('Edmund Burke\n') 13 | 14 | # Close the file 15 | outfile.close() 16 | 17 | main() -------------------------------------------------------------------------------- /chapters/06/02.py: -------------------------------------------------------------------------------- 1 | # Program 6-2 2 | # Reads and displays the contents 3 | # of philosophers.txt. 4 | 5 | def main(): 6 | # Open a file 7 | infile = open('philosophers.txt', 'r') 8 | 9 | file_contents = infile.read() 10 | 11 | infile.close() 12 | 13 | print(file_contents) 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/06/03.py: -------------------------------------------------------------------------------- 1 | # Program 6-3 2 | # Reads the contents of philosophers.txt 3 | # one line at a time. 4 | 5 | def main(): 6 | 7 | infile = open('philosophers.txt', 'r') 8 | 9 | line1 = infile.readline() 10 | line2 = infile.readline() 11 | line3 = infile.readline() 12 | 13 | infile.close() 14 | 15 | print(line1) 16 | print(line2) 17 | print(line3) 18 | 19 | main() -------------------------------------------------------------------------------- /chapters/06/04.py: -------------------------------------------------------------------------------- 1 | # Program 6-4 2 | # Gets three names from the user 3 | # and writes them to a file. 4 | 5 | def main(): 6 | 7 | print('Enter three names of friends.\n') 8 | 9 | friend1 = input('Friend 1: ') 10 | friend2 = input('Friend 2: ') 11 | friend3 = input('Friend 3: ') 12 | 13 | outfile = open('friends.txt', 'w') 14 | 15 | outfile.write(friend1 + '\n') 16 | outfile.write(friend2 + '\n') 17 | outfile.write(friend3 + '\n') 18 | 19 | outfile.close() 20 | print('Three names were written to friends.txt.') 21 | 22 | main() -------------------------------------------------------------------------------- /chapters/06/05.py: -------------------------------------------------------------------------------- 1 | # Program 6-5 2 | # Reads the contents of philosophers.txt 3 | # one line at a time. Compare the output 4 | # to that of 6-3. 5 | 6 | def main(): 7 | 8 | infile = open('philosophers.txt', 'r') 9 | 10 | line1 = infile.readline() 11 | line2 = infile.readline() 12 | line3 = infile.readline() 13 | 14 | line1 = line1.rstrip('\n') 15 | line2 = line2.rstrip('\n') 16 | line3 = line3.rstrip('\n') 17 | 18 | infile.close() 19 | 20 | print(line1) 21 | print(line2) 22 | print(line3) 23 | 24 | main() -------------------------------------------------------------------------------- /chapters/06/06.py: -------------------------------------------------------------------------------- 1 | # Program 6-6 2 | # Demonstrates how numbers 3 | # must be converted to strings 4 | # before they are written to a 5 | # text file. 6 | 7 | def main(): 8 | 9 | outfile = open('numbers.txt', 'w') 10 | 11 | num1 = int(input('Number 1: ')) 12 | num2 = int(input('Number 2: ')) 13 | num3 = int(input('Number 3: ')) 14 | 15 | outfile.write(str(num1) + '\n') 16 | outfile.write(str(num2) + '\n') 17 | outfile.write(str(num3) + '\n') 18 | 19 | outfile.close() 20 | print('Data written to numbers.txt.') 21 | 22 | main() -------------------------------------------------------------------------------- /chapters/06/07.py: -------------------------------------------------------------------------------- 1 | # Program 6-7 2 | # Convert strings of number in a file 3 | # to integers. 4 | 5 | def main(): 6 | 7 | infile = open('numbers.txt', 'r') 8 | 9 | num1 = int(infile.readline()) 10 | num2 = int(infile.readline()) 11 | num3 = int(infile.readline()) 12 | 13 | infile.close() 14 | 15 | total = num1 + num2 + num3 16 | 17 | print('The numbers are:', num1, num2, num3) 18 | print('Their total is:', total) 19 | 20 | main() -------------------------------------------------------------------------------- /chapters/06/08.py: -------------------------------------------------------------------------------- 1 | # Program 6-8 2 | # Prompts the user for sales 3 | # amounts and writes those amounts 4 | # to the sales.txt file. 5 | 6 | def main(): 7 | 8 | num_days = int(input('For how many days do you have sales? ')) 9 | 10 | sales_file = open('sales.txt', 'w') 11 | 12 | for count in range(1, num_days + 1): 13 | sales = float(input('Sales for day #' + str(count) + ': ')) 14 | 15 | sales_file.write(str(sales) + '\n') 16 | 17 | sales_file.close() 18 | print('Data written to sales.txt') 19 | 20 | main() -------------------------------------------------------------------------------- /chapters/06/09.py: -------------------------------------------------------------------------------- 1 | # Program 6-9 2 | # Reads all values in the sales.txt file 3 | 4 | def main(): 5 | 6 | sales_file = open('sales.txt', 'r') 7 | 8 | line = sales_file.readline() 9 | 10 | while line != '': 11 | amount = float(line) 12 | 13 | print(format(amount, ',.2f')) 14 | 15 | line = sales_file.readline() 16 | 17 | sales_file.close() 18 | 19 | main() -------------------------------------------------------------------------------- /chapters/06/10.py: -------------------------------------------------------------------------------- 1 | # Program 6-10 2 | # Reads all values in the sales.txt file 3 | # using a for loop. 4 | 5 | def main(): 6 | 7 | sales_file = open('sales.txt', 'r') 8 | 9 | for line in sales_file: 10 | amount = float(line) 11 | print(format(amount, ',.2f')) 12 | 13 | sales_file.close() 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/06/11.py: -------------------------------------------------------------------------------- 1 | # Program 6-11 2 | # Saves a sequence of video 3 | # running times to video_times.txt. 4 | 5 | def main(): 6 | 7 | num_videos = int(input('How many videos are in the project? ')) 8 | 9 | video_file = open('video_times.txt', 'w') 10 | 11 | print('Enter the running times for each video.') 12 | for count in range(1, num_videos + 1): 13 | run_time = float(input('Video #' + str(count) + ': ')) 14 | video_file.write(str(run_time) + '\n') 15 | 16 | video_file.close() 17 | print('The times have been saved to video_times.txt') 18 | 19 | main() -------------------------------------------------------------------------------- /chapters/06/12.py: -------------------------------------------------------------------------------- 1 | # Program 6-12 2 | # Reads the values in video_times.txt 3 | # file and calculates their totals. 4 | 5 | def main(): 6 | 7 | video_file = open('video_times.txt', 'r') 8 | 9 | total = 0.0 10 | 11 | count = 0 12 | 13 | print('Here are the running times for each video:') 14 | 15 | for line in video_file: 16 | run_time = float(line) 17 | 18 | count += 1 19 | 20 | print('Video #', count, ': ', run_time, sep='') 21 | 22 | total += run_time 23 | 24 | video_file.close() 25 | 26 | print('The total running time is', total, 'seconds.') 27 | 28 | main() -------------------------------------------------------------------------------- /chapters/06/13.py: -------------------------------------------------------------------------------- 1 | # Program 6-13 2 | # Gets employee data from the user and 3 | # saves it as records in the employee.txt file. 4 | 5 | def main(): 6 | 7 | number_of_employees = int(input('How many employee records' + 8 | 'do you want to create? ')) 9 | 10 | employee_file = open('employees.txt', 'w') 11 | 12 | # Get each employee's data and 13 | # write it to employees.txt 14 | for count in range(1, number_of_employees + 1): 15 | print('Enter data for employee #', count, sep='') 16 | name = input('Name: ') 17 | id_num = input('ID number: ') 18 | dept = input('Department: ') 19 | 20 | employee_file.write(name + '\n') 21 | employee_file.write(id_num + '\n') 22 | employee_file.write(dept + '\n') 23 | 24 | print() 25 | 26 | employee_file.close() 27 | print('Employee records written to employees.txt') 28 | 29 | main() -------------------------------------------------------------------------------- /chapters/06/14.py: -------------------------------------------------------------------------------- 1 | # Program 6-14 2 | # Displays the records that are 3 | # in the employees.txt file. 4 | 5 | def main(): 6 | 7 | employee_file = open('employees.txt', 'r') 8 | 9 | name = employee_file.readline() 10 | 11 | while name != '': 12 | 13 | id_num = employee_file.readline() 14 | dept = employee_file.readline() 15 | 16 | # Strip the newlines from the fields. 17 | name = name.rstrip('\n') 18 | id_num = id_num.rstrip('\n') 19 | dept = dept.rstrip('\n') 20 | 21 | print('Name:', name) 22 | print('ID:', id_num) 23 | print('Department:', dept) 24 | 25 | name = employee_file.readline() 26 | 27 | employee_file.close() 28 | 29 | main() -------------------------------------------------------------------------------- /chapters/06/15.py: -------------------------------------------------------------------------------- 1 | # Program 6-15 2 | # Adds records to coffee.txt. 3 | 4 | def main(): 5 | 6 | another = 'y' 7 | 8 | coffee_file = open('coffee.txt', 'a') 9 | 10 | while another.lower() == 'y': 11 | print('Enter the following coffee data:') 12 | description = input('Description: ') 13 | quantity = int(input('Quantity (in pounds): ')) 14 | 15 | coffee_file.write(f'{description}\n') 16 | coffee_file.write(f'{str(quantity)}\n') 17 | 18 | another = input('Add another record? (y/n): ') 19 | 20 | coffee_file.close() 21 | print('Data appended to coffee.txt.') 22 | 23 | main() -------------------------------------------------------------------------------- /chapters/06/16.py: -------------------------------------------------------------------------------- 1 | # Program 6-16 2 | # Displays coffee.txt records. 3 | 4 | def main(): 5 | 6 | coffee_file = open('coffee.txt', 'r') 7 | 8 | description = coffee_file.readline() 9 | 10 | while description != '': 11 | 12 | quantity = float(coffee_file.readline()) 13 | 14 | description = description.rstrip('\n') 15 | 16 | print('Description:', description) 17 | print('Quantity:', quantity) 18 | 19 | description = coffee_file.readline() 20 | 21 | coffee_file.close() 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /chapters/06/17.py: -------------------------------------------------------------------------------- 1 | # Program 6-17 2 | # Search coffee.txt for records 3 | # matching a description. 4 | 5 | def main(): 6 | 7 | found = False 8 | 9 | search = input('Enter a description to search for: ') 10 | 11 | coffee_file = open('coffee.txt', 'r') 12 | 13 | description = coffee_file.readline() 14 | 15 | while description != '': 16 | 17 | quantity = float(coffee_file.readline()) 18 | 19 | description = description.rstrip('\n') 20 | 21 | # Determine whether this record 22 | # matches the search value: 23 | if description == search: 24 | print('Description:', description) 25 | print('Quantity:', quantity) 26 | print() 27 | found = True 28 | 29 | description = coffee_file.readline() 30 | 31 | coffee_file.close() 32 | 33 | if not found: 34 | print('No results found. :(') 35 | 36 | main() -------------------------------------------------------------------------------- /chapters/06/18.py: -------------------------------------------------------------------------------- 1 | # Program 6-18 2 | # Modify coffee.txt records. 3 | 4 | import os 5 | 6 | def main(): 7 | 8 | found = False 9 | 10 | search = input('Enter a description to search for: ') 11 | new_quantity = int(input('Enter the new quantity: ')) 12 | 13 | # Open the original file 14 | coffee_file = open('coffee.txt', 'r') 15 | 16 | # Create a temporary file 17 | temp_file = open('temp.txt', 'w') 18 | 19 | description = coffee_file.readline() 20 | 21 | while description != '': 22 | 23 | quantity = float(coffee_file.readline()) 24 | 25 | description = description.rstrip('\n') 26 | 27 | if description == search: 28 | temp_file.write(f'{description}\n') 29 | temp_file.write(f'{str(new_quantity)}\n') 30 | 31 | found = True 32 | else: 33 | temp_file.write(f'{description}\n') 34 | temp_file.write(f'{str(quantity)}\n') 35 | 36 | description = coffee_file.readline() 37 | 38 | coffee_file.close() 39 | temp_file.close() 40 | 41 | os.remove('coffee.txt') 42 | os.rename('temp.txt', 'coffee.txt') 43 | 44 | if found: 45 | print('Coffee.txt has been updated.') 46 | else: 47 | print('No results found! :(') 48 | 49 | main() -------------------------------------------------------------------------------- /chapters/06/19.py: -------------------------------------------------------------------------------- 1 | # Program 6-19 2 | # Delete records from coffee.txt 3 | 4 | import os 5 | 6 | def main(): 7 | 8 | found = False 9 | 10 | search = input('Which coffee do you want to delete? ') 11 | 12 | coffee_file = open('coffee.txt', 'r') 13 | 14 | temp_file = open('temp.txt', 'w') 15 | 16 | description = coffee_file.readline() 17 | 18 | while description != '': 19 | 20 | quantity = float(coffee_file.readline()) 21 | 22 | description = description.rstrip('\n') 23 | 24 | if description != search: 25 | temp_file.write(f'{description}\n') 26 | temp_file.write(f'{str(quantity)}\n') 27 | else: 28 | found = True 29 | 30 | description = coffee_file.readline() 31 | 32 | coffee_file.close() 33 | temp_file.close() 34 | 35 | os.remove('coffee.txt') 36 | os.rename('temp.txt', 'coffee.txt') 37 | 38 | if found: 39 | print('The file has been updated.') 40 | else: 41 | print('No records have been deleted.') 42 | 43 | main() -------------------------------------------------------------------------------- /chapters/06/20.py: -------------------------------------------------------------------------------- 1 | # Program 6-20 2 | # Dividing by 0. 3 | 4 | def main(): 5 | 6 | num1 = int(input('Number 1: ')) 7 | num2 = int(input('Number 2: ')) 8 | 9 | result = num1 / num2 10 | 11 | print(num1, 'divided by', num2, 'is', result) 12 | 13 | main() -------------------------------------------------------------------------------- /chapters/06/21.py: -------------------------------------------------------------------------------- 1 | # Program 6-21 2 | # Divide by 0, but handle exception 3 | # with an if statement. 4 | 5 | def main(): 6 | 7 | num1 = int(input('Number 1: ')) 8 | num2 = int(input('Number 2: ')) 9 | 10 | if num2 != 0: 11 | result = num1 / num2 12 | print(num1, 'divided by', num2, 'is', result) 13 | else: 14 | print('Cannot divide by 0.') 15 | 16 | main() -------------------------------------------------------------------------------- /chapters/06/22.py: -------------------------------------------------------------------------------- 1 | # Program 6-22 2 | # Calculate gross pay. 3 | 4 | def main(): 5 | hours = int(input('How many hours did you work? ')) 6 | 7 | pay_rate = float(input('Enter your hourly pay rate: ')) 8 | 9 | gross_pay = hours * pay_rate 10 | 11 | print(f"Gross pay: ${format(gross_pay, ',.2f')}") 12 | 13 | main() -------------------------------------------------------------------------------- /chapters/06/23.py: -------------------------------------------------------------------------------- 1 | # Program 6-23 2 | # Handles a ValueError exception. 3 | 4 | def main(): 5 | try: 6 | hours = int(input('How many hours did you work? ')) 7 | 8 | pay_rate = float(input('Enter your hourly pay rate: ')) 9 | 10 | gross_pay = hours * pay_rate 11 | 12 | print(f"Gross pay: ${format(gross_pay, ',.2f')}") 13 | except ValueError: 14 | print('ERROR: Hours worked and hourly pay rate must' + 15 | ' be valid numbers.') 16 | 17 | main() -------------------------------------------------------------------------------- /chapters/06/24.py: -------------------------------------------------------------------------------- 1 | # Program 6-24 2 | # Displays the contents of a file. 3 | 4 | def main(): 5 | 6 | filename = input('Enter a filename: ') 7 | 8 | infile = open(filename, 'r') 9 | 10 | contents = infile.read() 11 | 12 | print(contents) 13 | 14 | infile.close() 15 | 16 | main() -------------------------------------------------------------------------------- /chapters/06/25.py: -------------------------------------------------------------------------------- 1 | # Program 6-25 2 | # Handles exceptions when trying 3 | # to read from a file. 4 | 5 | def main(): 6 | 7 | filename = input('Enter a filename: ') 8 | 9 | try: 10 | infile = open(filename, 'r') 11 | 12 | contents = infile.read() 13 | 14 | print(contents) 15 | 16 | infile.close() 17 | except IOError: 18 | print(f'Failed to read file {filename}.') 19 | 20 | main() -------------------------------------------------------------------------------- /chapters/06/26.py: -------------------------------------------------------------------------------- 1 | # Program 6-26 2 | # Displays the total of the 3 | # amounts in sales_data.txt. 4 | 5 | def main(): 6 | 7 | total = 0.0 8 | 9 | filename = 'sales_data.txt' 10 | 11 | try: 12 | infile = open(filename, 'r') 13 | 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | infile.close() 19 | 20 | print('Total:', format(total, ',.2f')) 21 | 22 | except IOError: 23 | print(f'Failed to read file {filename}.') 24 | except ValueError: 25 | print(f'Non-numeric data found in file {filename}.') 26 | except: 27 | print('An error occurred.') 28 | 29 | main() -------------------------------------------------------------------------------- /chapters/06/27.py: -------------------------------------------------------------------------------- 1 | # Program 6-27 2 | # Displays the total of the 3 | # amounts in sales_data.txt. 4 | 5 | def main(): 6 | 7 | total = 0.0 8 | 9 | filename = 'sales_data.txt' 10 | 11 | try: 12 | infile = open(filename, 'r') 13 | 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | infile.close() 19 | 20 | print('Total:', format(total, ',.2f')) 21 | except: 22 | print('An error occurred.') 23 | 24 | main() -------------------------------------------------------------------------------- /chapters/06/28.py: -------------------------------------------------------------------------------- 1 | # Program 6-28 2 | # Handles a ValueError exception. 3 | 4 | def main(): 5 | try: 6 | hours = int(input('How many hours did you work? ')) 7 | 8 | pay_rate = float(input('Enter your hourly pay rate: ')) 9 | 10 | gross_pay = hours * pay_rate 11 | 12 | print(f"Gross pay: ${format(gross_pay, ',.2f')}") 13 | except ValueError as err: 14 | print(err) 15 | 16 | main() -------------------------------------------------------------------------------- /chapters/06/29.py: -------------------------------------------------------------------------------- 1 | # Program 6-29 2 | # Displays the total of the 3 | # amounts in sales_data.txt. 4 | 5 | def main(): 6 | 7 | total = 0.0 8 | 9 | filename = 'sales_data.txt' 10 | 11 | try: 12 | infile = open(filename, 'r') 13 | 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | infile.close() 19 | 20 | print('Total:', format(total, ',.2f')) 21 | except Exception as err: 22 | print(err) 23 | 24 | main() -------------------------------------------------------------------------------- /chapters/06/30.py: -------------------------------------------------------------------------------- 1 | # Program 6-30 2 | # Displays the total of the 3 | # amounts in sales_data.txt. 4 | 5 | def main(): 6 | 7 | total = 0.0 8 | 9 | filename = 'sales_data.txt' 10 | 11 | try: 12 | infile = open(filename, 'r') 13 | 14 | for line in infile: 15 | amount = float(line) 16 | total += amount 17 | 18 | infile.close() 19 | except Exception as err: 20 | print(err) 21 | else: 22 | print('Total:', format(total, ',.2f')) 23 | 24 | main() -------------------------------------------------------------------------------- /chapters/06/coffee.txt: -------------------------------------------------------------------------------- 1 | Sumatra Medium Roast 2 | 25.0 3 | -------------------------------------------------------------------------------- /chapters/06/employees.txt: -------------------------------------------------------------------------------- 1 | Kosloski, Matthew 2 | 1165156 3 | Web Development 4 | Lippert, Adam 5 | 1165157 6 | Information Technology 7 | Doe, John 8 | 1165158 9 | Marketing 10 | -------------------------------------------------------------------------------- /chapters/06/friends.txt: -------------------------------------------------------------------------------- 1 | Cameron 2 | Ian 3 | Joe 4 | -------------------------------------------------------------------------------- /chapters/06/numbers.txt: -------------------------------------------------------------------------------- 1 | 5 2 | 10 3 | 15 4 | -------------------------------------------------------------------------------- /chapters/06/philosophers.txt: -------------------------------------------------------------------------------- 1 | John Lock 2 | David Hume 3 | Edmund Burke 4 | -------------------------------------------------------------------------------- /chapters/06/sales.txt: -------------------------------------------------------------------------------- 1 | 500.0 2 | 200.0 3 | 675.0 4 | -------------------------------------------------------------------------------- /chapters/06/sales_data.txt: -------------------------------------------------------------------------------- 1 | 100.00 2 | 101.00 3 | 102.00 4 | 103.00 5 | 104.00 -------------------------------------------------------------------------------- /chapters/06/video_times.txt: -------------------------------------------------------------------------------- 1 | 5.0 2 | 6.0 3 | -------------------------------------------------------------------------------- /chapters/07/01.py: -------------------------------------------------------------------------------- 1 | # Program 7-1 2 | 3 | NUM_DAYS = 5 4 | 5 | def main(): 6 | 7 | # Create a list to hold the sales 8 | # for each day 9 | sales = [0] * NUM_DAYS 10 | 11 | index = 0 12 | 13 | print('Enter the sales for each day.') 14 | 15 | while index < NUM_DAYS: 16 | print('Day #', index + 1, ': ', sep='', end='') 17 | sales[index] = float(input()) 18 | index += 1 19 | 20 | print('Here are the values you entered:') 21 | for value in sales: 22 | print(value) 23 | 24 | main() -------------------------------------------------------------------------------- /chapters/07/02.py: -------------------------------------------------------------------------------- 1 | # Program 7-2 2 | # Demonstrates the `in` operator 3 | # used with a list. 4 | 5 | def main(): 6 | 7 | prod_nums = ['V467', 'F120', 'Z952', 'P913'] 8 | 9 | search = input('Enter a product number: ') 10 | 11 | if search in prod_nums: 12 | print(search, 'was found in the list.') 13 | else: 14 | print(search, 'was not found in the list.') 15 | 16 | main() -------------------------------------------------------------------------------- /chapters/07/03.py: -------------------------------------------------------------------------------- 1 | # Program 7-3 2 | # Demonstrates how the append 3 | # method can be used to add 4 | # items to a list. 5 | 6 | def main(): 7 | 8 | name_list = [] 9 | 10 | again = 'y' 11 | 12 | while again.lower() == 'y': 13 | 14 | name = input('Enter a name: ') 15 | 16 | name_list.append(name) 17 | 18 | again = input('Add another name? (y/n): ') 19 | print() 20 | 21 | print('Here are the names you entered:') 22 | 23 | for name in name_list: 24 | print(name) 25 | 26 | main() -------------------------------------------------------------------------------- /chapters/07/04.py: -------------------------------------------------------------------------------- 1 | # Program 7-4 2 | # Demonstrates how to get the 3 | # index of an item in a list and then 4 | # replace that item with a new one. 5 | 6 | def main(): 7 | 8 | food = ['Pizza', 'Burgers', 'Chips'] 9 | 10 | print('Here are the items in the food list:') 11 | print(food) 12 | 13 | item = input('Which item should I change? ') 14 | 15 | try: 16 | # index of the item to replace 17 | item_index = food.index(item) 18 | 19 | # value of new item 20 | new_item = input(f'Enter the new value to replace "{food[item_index]}": ') 21 | 22 | food[item_index] = new_item 23 | 24 | print('Here is the revised list:') 25 | print(food) 26 | except ValueError: 27 | print('The item was not found in the list.') 28 | 29 | main() -------------------------------------------------------------------------------- /chapters/07/05.py: -------------------------------------------------------------------------------- 1 | # Program 7-5 2 | # Demonstrates the insert method 3 | # on a list. 4 | 5 | def main(): 6 | 7 | names = ['Joe', 'Cameron', 'Ian', 'John', 'Robert'] 8 | 9 | print('My list of friends:') 10 | print(names) 11 | 12 | names.insert(0, 'Kody') 13 | 14 | print('My list after adding an element:') 15 | print(names) 16 | 17 | main() -------------------------------------------------------------------------------- /chapters/07/06.py: -------------------------------------------------------------------------------- 1 | # Program 7-6 2 | # Demonstrates the remove method 3 | # on a list. 4 | 5 | def main(): 6 | 7 | food = ['Pizza', 'burgers', 'chips'] 8 | 9 | print('Here are food items:') 10 | print(food) 11 | 12 | item = input('Which item should I remove? ') 13 | 14 | try: 15 | food.remove(item) 16 | 17 | print('Here is the revised list:') 18 | print(food) 19 | except ValueError: 20 | print('Item does not exist in lsit.') 21 | 22 | main() -------------------------------------------------------------------------------- /chapters/07/07.py: -------------------------------------------------------------------------------- 1 | # Program 7-7 2 | # Calculates the gross pay for each 3 | # barista. 4 | 5 | NUM_EMPLOYEES = 6 6 | 7 | def main(): 8 | hours = [0] * NUM_EMPLOYEES 9 | 10 | for index in range(NUM_EMPLOYEES): 11 | print('Enter the hours worked by employee ', \ 12 | index + 1, ': ', sep='', end='') 13 | hours[index] = float(input()) 14 | 15 | pay_rate = float(input('Enter the hourly pay rate: ')) 16 | 17 | for index in range(NUM_EMPLOYEES): 18 | gross_pay = hours[index] * pay_rate 19 | print('Gross pay for employee ', index + 1, ': $', \ 20 | format(gross_pay, ',.2f'), sep='') 21 | 22 | main() -------------------------------------------------------------------------------- /chapters/07/08.py: -------------------------------------------------------------------------------- 1 | # Program 7-8 2 | # Calculates the total of the values 3 | # in a list. 4 | 5 | def main(): 6 | numbers = [2, 4, 6, 8, 10] 7 | 8 | total = 0 9 | 10 | for value in numbers: 11 | total += value 12 | 13 | print('The total is', total) 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/07/09.py: -------------------------------------------------------------------------------- 1 | # Program 7-9 2 | # Calculates the average 3 | # of values in a list. 4 | 5 | def main(): 6 | scores = [2.5, 7.2, 9.1, 10.1, 7.2, 5.6] 7 | 8 | total = 0.0 9 | 10 | for score in scores: 11 | total += score 12 | 13 | average = total / len(scores) 14 | 15 | print('Average of scores is', average) 16 | 17 | main() -------------------------------------------------------------------------------- /chapters/07/10.py: -------------------------------------------------------------------------------- 1 | # Program 7-10 2 | # Uses a function to calculate 3 | # the total of values in a list. 4 | 5 | def main(): 6 | 7 | numbers = [2, 4, 5, 7, 9, 10] 8 | 9 | print('The total is', get_total(numbers)) 10 | 11 | def get_total(value_list): 12 | total = 0 13 | for num in value_list: 14 | total += num 15 | return total 16 | 17 | main() -------------------------------------------------------------------------------- /chapters/07/11.py: -------------------------------------------------------------------------------- 1 | # Program 7-11 2 | # Uses a function to create a list. 3 | # The function returns a reference to 4 | # the list. 5 | 6 | def main(): 7 | 8 | numbers = get_values() 9 | print('The numbers in the list are', numbers) 10 | 11 | def get_values(): 12 | values = [] 13 | 14 | again = 'y' 15 | 16 | while again.lower() == 'y': 17 | num = int(input('Enter a number: ')) 18 | values.append(num) 19 | 20 | again = input('Add another number? (y/n): ') 21 | print() 22 | 23 | return values 24 | 25 | main() -------------------------------------------------------------------------------- /chapters/07/12.py: -------------------------------------------------------------------------------- 1 | # Program 7-12 2 | # Gets a series of test scores and 3 | # calculates the average of the scores 4 | # with the lowest score dropped. 5 | 6 | def main(): 7 | 8 | scores = get_scores() 9 | 10 | total = get_total(scores) 11 | 12 | lowest = min(scores) 13 | 14 | total -= lowest 15 | 16 | average = total / (len(scores) - 1) 17 | 18 | print('The average, with the lowest score dropped, is', average) 19 | 20 | def get_scores(): 21 | 22 | scores = [] 23 | 24 | again = 'y' 25 | 26 | while again.lower() == 'y': 27 | score = float(input('Enter a test score: ')) 28 | scores.append(score) 29 | 30 | again = input('Add another score? (y/n): ') 31 | print() 32 | 33 | return scores 34 | 35 | def get_total(scores): 36 | total = 0 37 | for score in scores: 38 | total += score 39 | return total 40 | 41 | main() 42 | -------------------------------------------------------------------------------- /chapters/07/13.py: -------------------------------------------------------------------------------- 1 | # Program 7-13 2 | # Uses the writelines method to save 3 | # a list of strings to a file. 4 | 5 | def main(): 6 | 7 | cities = ['Boston', 'Chicago', 'New York'] 8 | 9 | outfile = open('cities.txt', 'w') 10 | 11 | for city in cities: 12 | outfile.write(f'{city}\n') 13 | 14 | outfile.close() 15 | 16 | main() -------------------------------------------------------------------------------- /chapters/07/14.py: -------------------------------------------------------------------------------- 1 | # Program 7-14 2 | # Reads a file's contents into a list. 3 | 4 | def main(): 5 | 6 | infile = open('cities.txt', 'r') 7 | 8 | # contents of cities.txt in a list 9 | cities = infile.readlines() 10 | 11 | infile.close() 12 | 13 | # removing terminating new line character 14 | index = 0 15 | while index < len(cities): 16 | cities[index] = cities[index].rstrip('\n') 17 | index += 1 18 | 19 | print(cities) 20 | 21 | main() -------------------------------------------------------------------------------- /chapters/07/15.py: -------------------------------------------------------------------------------- 1 | # Program 7-15 2 | # Saves a list of numbers to a txt file. 3 | 4 | def main(): 5 | 6 | numbers = [1, 2, 3, 4, 5] 7 | 8 | outfile = open('numbers.txt', 'w') 9 | 10 | for number in numbers: 11 | outfile.write(f'{str(number)}\n') 12 | 13 | outfile.close() 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/07/16.py: -------------------------------------------------------------------------------- 1 | # Program 7-16 2 | # Reads a file of numbers 3 | 4 | def main(): 5 | 6 | infile = open('numbers.txt', 'r') 7 | 8 | # contents of numbers.txt in a list 9 | numbers = infile.readlines() 10 | 11 | infile.close() 12 | 13 | # removing terminating new line character 14 | index = 0 15 | while index < len(numbers): 16 | numbers[index] = int(numbers[index]) 17 | index += 1 18 | 19 | print(numbers) 20 | 21 | main() -------------------------------------------------------------------------------- /chapters/07/17.py: -------------------------------------------------------------------------------- 1 | # Program 7-17 2 | # Assigns random numbers to 3 | # a two-dimensional list. 4 | 5 | import random 6 | 7 | ROWS = 3 8 | COLS = 4 9 | 10 | def main(): 11 | 12 | values = [ 13 | [0, 0, 0, 0], 14 | [0, 0, 0, 0], 15 | [0, 0, 0, 0] 16 | ] 17 | 18 | for row in range(ROWS): 19 | for col in range(COLS): 20 | values[row][col] = random.randint(1, 100) 21 | 22 | print(values) 23 | 24 | 25 | main() -------------------------------------------------------------------------------- /chapters/07/cities.txt: -------------------------------------------------------------------------------- 1 | Boston 2 | Chicago 3 | New York 4 | -------------------------------------------------------------------------------- /chapters/07/numbers.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | -------------------------------------------------------------------------------- /chapters/10/01.py: -------------------------------------------------------------------------------- 1 | # Program 10-1 2 | # The Coin class simulates a coin that 3 | # can be flipped. 4 | 5 | import random 6 | 7 | class Coin: 8 | 9 | def __init__(self): 10 | self.sideup = 'Heads' 11 | 12 | def toss(self): 13 | if random.randint(0, 1) == 0: 14 | self.sideup = 'Heads' 15 | else: 16 | self.sideup = 'Tails' 17 | 18 | def get_sideup(self): 19 | return self.sideup 20 | 21 | def main(): 22 | my_coin = Coin() 23 | 24 | print('This side is facing up:', my_coin.get_sideup()) 25 | 26 | print('I am tossing the coin...') 27 | my_coin.toss() 28 | 29 | print('This side is facing up:', my_coin.get_sideup()) 30 | 31 | main() -------------------------------------------------------------------------------- /chapters/10/02.py: -------------------------------------------------------------------------------- 1 | # Program 10-2 2 | # The Coin class simulates a coin that 3 | # can be flipped. 4 | 5 | import random 6 | 7 | class Coin: 8 | 9 | def __init__(self): 10 | self.sideup = 'Heads' 11 | 12 | def toss(self): 13 | if random.randint(0, 1) == 0: 14 | self.sideup = 'Heads' 15 | else: 16 | self.sideup = 'Tails' 17 | 18 | def get_sideup(self): 19 | return self.sideup 20 | 21 | def main(): 22 | my_coin = Coin() 23 | 24 | print('This side is facing up:', my_coin.get_sideup()) 25 | 26 | print('I am tossing the coin...') 27 | my_coin.toss() 28 | 29 | # I'm going to cheat and directly change the object's 30 | # sideup attribute. 31 | my_coin.sideup = 'Heads' 32 | 33 | print('This side is facing up:', my_coin.get_sideup()) 34 | 35 | main() -------------------------------------------------------------------------------- /chapters/10/03.py: -------------------------------------------------------------------------------- 1 | # Program 10-3 2 | # The Coin class simulates a coin that 3 | # can be flipped. 4 | 5 | import random 6 | 7 | class Coin: 8 | 9 | def __init__(self): 10 | self.__sideup = 'Heads' 11 | 12 | def toss(self): 13 | if random.randint(0, 1) == 0: 14 | self.__sideup = 'Heads' 15 | else: 16 | self.__sideup = 'Tails' 17 | 18 | def get_sideup(self): 19 | return self.__sideup 20 | 21 | def main(): 22 | my_coin = Coin() 23 | 24 | print('This side is facing up:', my_coin.get_sideup()) 25 | 26 | print('I am going to toss the coin ten times:') 27 | for toss in range(10): 28 | my_coin.toss() 29 | print('Toss', toss + 1, my_coin.get_sideup()) 30 | 31 | main() -------------------------------------------------------------------------------- /chapters/10/04.py: -------------------------------------------------------------------------------- 1 | # Program 10-4 2 | # This program imports the coin module and 3 | # creates an instance of the Coin class. 4 | 5 | import coin 6 | 7 | def main(): 8 | my_coin = coin.Coin() 9 | 10 | print('Side facing up:', my_coin.get_sideup()) 11 | 12 | # Toss the coin 13 | print('I am going to toss the coin ten times:') 14 | for toss in range(10): 15 | my_coin.toss() 16 | print('Toss', toss + 1, my_coin.get_sideup()) 17 | 18 | main() -------------------------------------------------------------------------------- /chapters/10/05.py: -------------------------------------------------------------------------------- 1 | # Program 10-5 2 | # This program demonstrates the BankAccount class. 3 | 4 | import bankaccount 5 | 6 | def main(): 7 | 8 | # Get the starting balance. 9 | start_bal = float(input('Enter your starting balance: ')) 10 | 11 | # Create a BankAccount object 12 | savings = bankaccount.BankAccount(start_bal) 13 | 14 | # Deposit paycheck 15 | pay = float(input('How much were you paid this week? ')) 16 | print('I will deposit that amount into your account.') 17 | savings.deposit(pay) 18 | 19 | # Display balance after deposit 20 | print('Your account balance is $', 21 | format(savings.get_balance(), ',.2f'), 22 | sep='') 23 | 24 | # Get the amount to withdraw. 25 | cash = float(input('How much would you like to withdraw? ')) 26 | print('I will withdraw that from your account.') 27 | savings.withdraw(cash) 28 | 29 | # Display balance after withdraw 30 | print('Your account balance is $', 31 | format(savings.get_balance(), ',.2f'), 32 | sep='') 33 | 34 | main() -------------------------------------------------------------------------------- /chapters/10/06.py: -------------------------------------------------------------------------------- 1 | # Program 10-6 2 | # This program demonstrates the BankAccount class. 3 | 4 | import bankaccount2 5 | 6 | def main(): 7 | 8 | # Get the starting balance. 9 | start_bal = float(input('Enter your starting balance: ')) 10 | 11 | # Create a BankAccount object 12 | savings = bankaccount2.BankAccount(start_bal) 13 | 14 | # Deposit paycheck 15 | pay = float(input('How much were you paid this week? ')) 16 | print('I will deposit that amount into your account.') 17 | savings.deposit(pay) 18 | 19 | # Display balance after deposit 20 | print(savings) 21 | 22 | # Get the amount to withdraw. 23 | cash = float(input('How much would you like to withdraw? ')) 24 | print('I will withdraw that from your account.') 25 | savings.withdraw(cash) 26 | 27 | # Display balance after withdraw 28 | print(savings) 29 | 30 | main() -------------------------------------------------------------------------------- /chapters/10/07.py: -------------------------------------------------------------------------------- 1 | # This program imports the simulation module 2 | # and creates three instances of the Coin class. 3 | 4 | import coin 5 | 6 | def main(): 7 | coin1 = coin.Coin() 8 | coin2 = coin.Coin() 9 | coin3 = coin.Coin() 10 | 11 | print('I have three coins with these sides up:') 12 | print(coin1.get_sideup()) 13 | print(coin2.get_sideup()) 14 | print(coin3.get_sideup()) 15 | print() 16 | 17 | print('I am tossing all three coins...') 18 | coin1.toss() 19 | coin2.toss() 20 | coin3.toss() 21 | print() 22 | 23 | print('Now here are the sides that are up:') 24 | print(coin1.get_sideup()) 25 | print(coin2.get_sideup()) 26 | print(coin3.get_sideup()) 27 | print() 28 | 29 | main() -------------------------------------------------------------------------------- /chapters/10/08.py: -------------------------------------------------------------------------------- 1 | # Program 10-8 2 | # This program tests the CellPhone class. 3 | 4 | import cellphone 5 | 6 | def main(): 7 | manufacturer = input('Enter the manufacturer: ') 8 | model = input('Enter the model number: ') 9 | retail = float(input('Enter the retail price: ')) 10 | 11 | phone = cellphone.CellPhone(manufacturer, model, retail) 12 | 13 | print('Here is the data that you entered:') 14 | print('Manufacturer:', phone.get_manufact()) 15 | print('Model:', phone.get_model()) 16 | print('Retail price:', phone.get_retail_price()) 17 | 18 | main() -------------------------------------------------------------------------------- /chapters/10/09.py: -------------------------------------------------------------------------------- 1 | # Program 10-9 2 | # The program creates three CellPhone objects and 3 | # stores them in a list. 4 | 5 | from cellphone import CellPhone 6 | 7 | def main(): 8 | # Get a list of CellPhone objects 9 | phones = make_list() 10 | 11 | # Display the data in the list. 12 | print('Here is the data you entered:') 13 | display_list(phones) 14 | 15 | def make_list(): 16 | phone_list = [] 17 | 18 | print('Enter data for three phones.') 19 | for count in range (1, 4): 20 | # Get the phone data. 21 | print('Phone number ' + str(count) + ':') 22 | manufacturer = input('Manufacturer: ') 23 | model = input('Model: ') 24 | price = float(input('Retail price: ')) 25 | print() 26 | 27 | phone = CellPhone(manufacturer, model, price) 28 | 29 | phone_list.append(phone) 30 | 31 | return phone_list 32 | 33 | def display_list(phone_list): 34 | for phone in phone_list: 35 | print(phone.get_manufact()) 36 | print(phone.get_model()) 37 | print(phone.get_retail_price()) 38 | print() 39 | 40 | main() 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /chapters/10/10.py: -------------------------------------------------------------------------------- 1 | # This program passes a Coin object as 2 | # an argument to a function. 3 | import coin 4 | 5 | def main(): 6 | 7 | my_coin = coin.Coin() 8 | 9 | print(my_coin.get_sideup()) 10 | 11 | flip(my_coin) 12 | 13 | print(my_coin.get_sideup()) 14 | 15 | def flip(coin): 16 | coin.toss() 17 | 18 | main() 19 | 20 | -------------------------------------------------------------------------------- /chapters/10/11.py: -------------------------------------------------------------------------------- 1 | # Program 10-11 2 | # This program pickles CellPhone objects. 3 | 4 | import pickle 5 | import cellphone 6 | 7 | # Constant for the filename. 8 | FILENAME = 'cellphones.dat' 9 | 10 | def main(): 11 | 12 | again = 'y' 13 | 14 | # Open a file 15 | output_file = open(FILENAME, 'wb') 16 | 17 | # Get data from the user 18 | while again.lower() == 'y': 19 | # Get cellphone data 20 | man = input('Enter the manufacturer: ') 21 | mod = input('Enter the model number: ') 22 | retail = float(input('Enter the retail price: ')) 23 | 24 | phone = cellphone.CellPhone(man, mod, retail) 25 | 26 | # Pickle the object and write it to the file 27 | pickle.dump(phone, output_file) 28 | 29 | again = input('Enter more phone data? (y/n): ') 30 | 31 | # Close the file 32 | output_file.close() 33 | print('Data was written to', FILENAME) 34 | 35 | main() -------------------------------------------------------------------------------- /chapters/10/12.py: -------------------------------------------------------------------------------- 1 | # Program 10-12 2 | # This program unpickles CellPhone objects. 3 | 4 | import pickle 5 | import cellphone 6 | 7 | FILENAME = 'cellphones.dat' 8 | 9 | def main(): 10 | end_of_file = False 11 | 12 | input_file = open(FILENAME, 'rb') 13 | 14 | # Open the file. 15 | while not end_of_file: 16 | try: 17 | # Unpickle the next object. 18 | phone = pickle.load(input_file) 19 | 20 | # Display the cell phone data 21 | display_data(phone) 22 | 23 | except EOFError: 24 | # Set the flag to indicate the end 25 | # of the file has been reached. 26 | end_of_file = True 27 | 28 | # Close the file. 29 | input_file.close() 30 | 31 | def display_data(phone): 32 | print('Here is the data that you entered:') 33 | print('Manufacturer:', phone.get_manufact()) 34 | print('Model:', phone.get_model()) 35 | print('Retail price: $', format(phone.get_retail_price(), ',.2f'), sep='') 36 | 37 | main() -------------------------------------------------------------------------------- /chapters/10/13.py: -------------------------------------------------------------------------------- 1 | # Program 10-13 2 | # This program manages Contacts. 3 | 4 | import contact 5 | import pickle 6 | 7 | # Global constants for menu choices 8 | LOOK_UP = 1 9 | ADD = 2 10 | CHANGE = 3 11 | DELETE = 4 12 | QUIT = 5 13 | 14 | # Global constant for the filename 15 | FILENAME = 'contacts.dat' 16 | 17 | def main(): 18 | # Load the existing contact dictionary and 19 | # assign it to mycontacts. 20 | mycontacts = load_contacts() 21 | 22 | # Initialize a variable for the user's choice. 23 | choice = 0 24 | 25 | # Process menu selections until the user 26 | # wants to quit the program 27 | while choice != QUIT: 28 | 29 | choice = get_menu_choice() 30 | 31 | if choice == LOOK_UP: 32 | look_up(mycontacts) 33 | elif choice == ADD: 34 | add(mycontacts) 35 | elif choice == CHANGE: 36 | change(mycontacts) 37 | elif choice == DELETE: 38 | delete(mycontacts) 39 | 40 | # Save the mycontacts dictionary to a file. 41 | save_contacts(mycontacts) 42 | 43 | def load_contacts(): 44 | try: 45 | # Open the contacts.dat file. 46 | input_file = open(FILENAME, 'rb') 47 | 48 | # Unpickle the dictionary. 49 | contact_dct = pickle.load(input_file) 50 | 51 | # Close the phone_inventory.dat file. 52 | input_file.close() 53 | except IOError: 54 | # Could not open the file, 55 | # so create an empty dictionary. 56 | contact_dct = {} 57 | 58 | return contact_dct 59 | 60 | def get_menu_choice(): 61 | print() 62 | print('Menu') 63 | print('---------------------------') 64 | print('1. Look up a contact') 65 | print('2. Add a new contact') 66 | print('3. Change an existing contact') 67 | print('4. Delete a contact') 68 | print('5. Quit the program') 69 | print() 70 | 71 | # Get the user's choice. 72 | choice = int(input('Enter your choice: ')) 73 | 74 | # Validate the choice. 75 | while choice < LOOK_UP or choice > QUIT: 76 | choice = int(input('Enter a valid choice: ')) 77 | 78 | return choice 79 | 80 | # Looks up an item in the 81 | # specified dictionary. 82 | def look_up(mycontacts): 83 | name = input('Enter a name: ') 84 | 85 | print(mycontacts.get(name, 'That name is not found.')) 86 | 87 | def add(mycontacts): 88 | name = input('Name: ') 89 | phone = input('Phone: ') 90 | email = input('Email: ') 91 | 92 | # Create a Contact object named entry. 93 | entry = contact.Contact(name, phone, email) 94 | 95 | # If the name does not exist in the dictionary, 96 | # add it as a key with the entry object as the 97 | # associated value. 98 | if name not in mycontacts: 99 | mycontacts[name] = entry 100 | print('The entry has been added') 101 | else: 102 | print('That name already exists.') 103 | 104 | 105 | # Changes an existing entry 106 | # in the specified dictionary 107 | 108 | def change(mycontacts): 109 | name = input('Enter a name: ') 110 | 111 | if name in mycontacts: 112 | phone = input('Enter the new phone number: ') 113 | email = input('Enter the new email address: ') 114 | 115 | entry = contact.Contact(name, phone, email) 116 | 117 | mycontacts[name] = entry 118 | print('Information updated.') 119 | else: 120 | print('That name is not found') 121 | 122 | # Deletes an entry from 123 | # the specified dictionary 124 | 125 | def delete(mycontacts): 126 | name = input('Enter a name: ') 127 | 128 | # If name found, delete entry 129 | if name in mycontacts: 130 | del mycontacts[name] 131 | print('Entry deleted.') 132 | else: 133 | print('That name is not found.') 134 | 135 | # Pickles the specified object 136 | # and saves it to the contacts file. 137 | def save_contacts(mycontacts): 138 | # Open the file for writing 139 | output_file = open(FILENAME, 'wb') 140 | 141 | # Pickle the dictionary and save it. 142 | pickle.dump(mycontacts, output_file) 143 | 144 | # Close the file 145 | output_file.close() 146 | 147 | main() -------------------------------------------------------------------------------- /chapters/10/bankaccount.py: -------------------------------------------------------------------------------- 1 | 2 | class BankAccount: 3 | 4 | def __init__(self, bal): 5 | self.__balance = bal 6 | 7 | def deposit(self, amount): 8 | self.__balance += amount 9 | 10 | def withdraw(self, amount): 11 | if self.__balance >= amount: 12 | self.__balance -= amount 13 | else: 14 | print('Error: Insufficient funds') 15 | 16 | def get_balance(self): 17 | return self.__balance 18 | -------------------------------------------------------------------------------- /chapters/10/bankaccount2.py: -------------------------------------------------------------------------------- 1 | 2 | class BankAccount: 3 | 4 | def __init__(self, bal): 5 | self.__balance = bal 6 | 7 | def deposit(self, amount): 8 | self.__balance += amount 9 | 10 | def withdraw(self, amount): 11 | if self.__balance >= amount: 12 | self.__balance -= amount 13 | else: 14 | print('Error: Insufficient funds') 15 | 16 | def get_balance(self): 17 | return self.__balance 18 | 19 | def __str__(self): 20 | return 'Your account balance is $' + format(self.__balance, ',.2f') 21 | -------------------------------------------------------------------------------- /chapters/10/car.py: -------------------------------------------------------------------------------- 1 | class Car: 2 | def __init__(self, make, model, year): 3 | self.__make = make 4 | self.__model = model 5 | self.__year = year 6 | 7 | def set_make(self, make): 8 | self.__make = make 9 | 10 | def set_model(self, model): 11 | self.__model = model 12 | 13 | def set_year(self, year): 14 | self.__year = year 15 | 16 | def get_make(self): 17 | return self.__make 18 | 19 | def get_model(self): 20 | return self.__model 21 | 22 | def get_year(self): 23 | return self.__year -------------------------------------------------------------------------------- /chapters/10/cellphone.py: -------------------------------------------------------------------------------- 1 | # The CellPhone class holds data about a cell phone. 2 | 3 | class CellPhone: 4 | 5 | def __init__(self, manufact, model, price): 6 | self.__manufact = manufact 7 | self.__model = model 8 | self.__retail_price = price 9 | 10 | def set_manufact(self, manufact): 11 | self.__manufact = manufact 12 | 13 | def set_model(self, model): 14 | self.__model = model 15 | 16 | def set_retail_price(self, price): 17 | self.__retail_price = price 18 | 19 | def get_manufact(self): 20 | return self.__manufact 21 | 22 | def get_model(self): 23 | return self.__model 24 | 25 | def get_retail_price(self): 26 | return self.__retail_price -------------------------------------------------------------------------------- /chapters/10/coin.py: -------------------------------------------------------------------------------- 1 | # The Coin class simulates a coin that 2 | # can be flipped. 3 | 4 | import random 5 | 6 | class Coin: 7 | 8 | def __init__(self): 9 | self.__sideup = 'Heads' 10 | 11 | def toss(self): 12 | if random.randint(0, 1) == 0: 13 | self.__sideup = 'Heads' 14 | else: 15 | self.__sideup = 'Tails' 16 | 17 | def get_sideup(self): 18 | return self.__sideup -------------------------------------------------------------------------------- /chapters/10/contact.py: -------------------------------------------------------------------------------- 1 | class Contact: 2 | def __init__(self, name, phone, email): 3 | self.__name = name 4 | self.__phone = phone 5 | self.__email = email 6 | 7 | def set_name(self, name): 8 | self.__name = name 9 | 10 | def set_phone(self, phone): 11 | self.__phone = phone 12 | 13 | def set_email(self, email): 14 | self.__email = email 15 | 16 | def get_name(self): 17 | return self.__name 18 | 19 | def get_phone(self): 20 | return self.__phone 21 | 22 | def get_email(self): 23 | return self.__email 24 | 25 | def __str__(self): 26 | return 'Name: ' + self.__name + \ 27 | '\nPhone: ' + self.__phone + \ 28 | '\nEmail: ' + self.__email 29 | 30 | -------------------------------------------------------------------------------- /chapters/10/customer.py: -------------------------------------------------------------------------------- 1 | class Customer: 2 | def __init__(self, name, address, phone): 3 | self.__name = name 4 | self.__address = address 5 | self.__phone = phone 6 | 7 | def set_name(self, name): 8 | self.__name = name 9 | 10 | def set_address(self, address): 11 | self.__address = address 12 | 13 | def set_phone(self, phone): 14 | self.__phone = phone 15 | 16 | def get_name(self): 17 | return self.__name 18 | 19 | def get_address(self): 20 | return self.__address 21 | 22 | def get_phone(self): 23 | return self.__phone -------------------------------------------------------------------------------- /chapters/10/servicequote.py: -------------------------------------------------------------------------------- 1 | TAX_RATE = 0.05 2 | 3 | class ServiceQuote: 4 | def __init__(self, parts_charges, labor_charges): 5 | self.__parts_charges = parts_charges 6 | self.__labor_charges = labor_charges 7 | 8 | def set_parts_charges(self, parts_charges): 9 | self.__parts_charges = parts_charges 10 | 11 | def set_labor_charges(self, set_labor_charges): 12 | self.__set_labor_charges = set_labor_charges 13 | 14 | def get_parts_charges(self): 15 | return self.__parts_charges 16 | 17 | def get_labor_charges(self): 18 | return self.__labor_charges 19 | 20 | def get_sales_tax(self): 21 | return __parts_charges * TAX_RATE 22 | 23 | def get_total_charges(self): 24 | return __parts_charges + __labor_charges + \ 25 | (__parts_charges * TAX_RATE) -------------------------------------------------------------------------------- /chapters/11/03.py: -------------------------------------------------------------------------------- 1 | # Program 11-3 2 | # Demonstrates the Car class. 3 | 4 | import vehicles 5 | 6 | def main(): 7 | used_car = vehicles.Car('Audi', 2007, 12500, 21500.00, 4) 8 | 9 | print('Make:', used_car.get_make()) 10 | print('Model:', used_car.get_model()) 11 | print('Mileage:', used_car.get_mileage()) 12 | print('Price:', used_car.get_price()) 13 | print('Doors:', used_car.get_doors()) 14 | 15 | main() -------------------------------------------------------------------------------- /chapters/11/06.py: -------------------------------------------------------------------------------- 1 | # Program 11-6 2 | # Creates a Car object, a Truck object, 3 | # and an SUV object. 4 | 5 | import vehicles 6 | 7 | def main(): 8 | 9 | car = vehicles.Car('BMW', 2001, 70000, 15000.0, 4) 10 | truck = vehicles.Truck('Toyota', 2002, 40000, 12000.0, '4WD') 11 | suv = vehicles.SUV('Volvo', 2000, 30000, 18500.0, 5) 12 | 13 | print('USED CAR INVENTORY') 14 | print('====================') 15 | 16 | print('The following car is in inventory:') 17 | print('Make:', car.get_make()) 18 | print('Model:', car.get_model()) 19 | print('Mileage:', car.get_mileage()) 20 | print('Price:', car.get_price()) 21 | print('Doors:', car.get_doors()) 22 | print() 23 | 24 | print('The following pickup truck is in inventory:') 25 | print('Make:', truck.get_make()) 26 | print('Model:', truck.get_model()) 27 | print('Mileage:', truck.get_mileage()) 28 | print('Price:', truck.get_price()) 29 | print('Drive type:', truck.get_drive_type()) 30 | print() 31 | 32 | print('The following SUV is in inventory:') 33 | print('Make:', suv.get_make()) 34 | print('Model:', suv.get_model()) 35 | print('Mileage:', suv.get_mileage()) 36 | print('Price:', suv.get_price()) 37 | print('Passanger Capacity:', suv.get_pass_cap()) 38 | print() 39 | 40 | main() -------------------------------------------------------------------------------- /chapters/11/08.py: -------------------------------------------------------------------------------- 1 | # Program 11-8 2 | # Creates an instance of SavingsAccount 3 | # class and an instance of the CD account. 4 | 5 | import accounts 6 | 7 | def main(): 8 | 9 | print('Enter the following data for a savings account.') 10 | acct_num = input('Account number: ') 11 | int_rate = float(input('Interest rate: ')) 12 | balance = float(input('Balance: ')) 13 | 14 | savings = accounts.SavingsAccount(acct_num, int_rate, balance) 15 | 16 | print('Enter the following info for a CD:') 17 | acct_num = input('Account number: ') 18 | int_rate = float(input('Interest rate: ')) 19 | balance = float(input('Balance: ')) 20 | maturity = input('Maturity date:') 21 | 22 | cd = accounts.CD(acct_num, int_rate, balance, maturity) 23 | 24 | print('Here is the data you entered:') 25 | 26 | print() 27 | 28 | print('Savings Account') 29 | print('---------------') 30 | print('Account number:', savings.get_account_num()) 31 | print('Interest rate:', savings.get_interest_rate()) 32 | print('Balance: $', format(savings.get_balance(), ',.2f'), sep='') 33 | 34 | print() 35 | 36 | print('CD') 37 | print('---------------') 38 | print('Account number:', cd.get_account_num()) 39 | print('Interest rate:', cd.get_interest_rate()) 40 | print('Balance: $', format(cd.get_balance(), ',.2f'), sep='') 41 | print('Maturity date:', cd.get_maturity_date()) 42 | 43 | main() -------------------------------------------------------------------------------- /chapters/11/10.py: -------------------------------------------------------------------------------- 1 | # Program 11-10 2 | # Demonstrates polymorphism 3 | 4 | import animals 5 | 6 | def main(): 7 | 8 | mammal = animals.Mammal('regular animal') 9 | dog = animals.Dog() 10 | cat = animals.Cat() 11 | 12 | # Display information about each one. 13 | print('Here are some animals and' 14 | + 'the sounds they make.') 15 | print('--------------------------------') 16 | show_mammal_info(mammal) 17 | print() 18 | show_mammal_info(dog) 19 | print() 20 | show_mammal_info(cat) 21 | 22 | def show_mammal_info(creature): 23 | creature.show_species() 24 | creature.make_sound() 25 | 26 | main() -------------------------------------------------------------------------------- /chapters/11/11.py: -------------------------------------------------------------------------------- 1 | # Program 11-11 2 | 3 | def main(): 4 | 5 | show_mammal_info('I am a string') 6 | 7 | def show_mammal_info(creature): 8 | creature.show_species() 9 | creature.make_sound() 10 | 11 | main() -------------------------------------------------------------------------------- /chapters/11/12.py: -------------------------------------------------------------------------------- 1 | # Program 11-12 2 | 3 | import animals 4 | 5 | def main(): 6 | 7 | mammal = animals.Mammal('regular animal') 8 | dog = animals.Dog() 9 | cat = animals.Cat() 10 | 11 | # Display information about each one. 12 | print('Here are some animals and' 13 | + 'the sounds they make.') 14 | print('--------------------------------') 15 | show_mammal_info(mammal) 16 | print() 17 | show_mammal_info(dog) 18 | print() 19 | show_mammal_info(cat) 20 | print() 21 | show_mammal_info('I am a string') 22 | 23 | def show_mammal_info(creature): 24 | if isinstance(creature, animals.Mammal): 25 | creature.show_species() 26 | creature.make_sound() 27 | else: 28 | print('That is not a Mammal!') 29 | 30 | main() -------------------------------------------------------------------------------- /chapters/11/accounts.py: -------------------------------------------------------------------------------- 1 | # Program 11-7 2 | class SavingsAccount: 3 | 4 | def __init__(self, account_num, int_rate, bal): 5 | self.__account_num = account_num 6 | self.__interest_rate = int_rate 7 | self.__balance = bal 8 | 9 | def set_account_num(self, account_num): 10 | self.__account_num = account_num 11 | 12 | def set_interest_rate(self, interest_rate): 13 | self.__interest_rate = interest_rate 14 | 15 | def set_balance(self, balance): 16 | self.__balance = balance 17 | 18 | def get_account_num(self): 19 | return self.__account_num 20 | 21 | def get_interest_rate(self): 22 | return self.__interest_rate 23 | 24 | def get_balance(self): 25 | return self.__balance 26 | 27 | class CD(SavingsAccount): 28 | 29 | def __init__(self, account_num, int_rate, bal, mat_date): 30 | SavingsAccount.__init__(self, account_num, int_rate, bal) 31 | self.__maturity_date = mat_date 32 | 33 | def set_maturity_date(maturity_date): 34 | self.__maturity_date = maturity_date 35 | 36 | def get_maturity_date(self): 37 | return self.__maturity_date 38 | 39 | -------------------------------------------------------------------------------- /chapters/11/animals.py: -------------------------------------------------------------------------------- 1 | class Mammal: 2 | 3 | def __init__(self, species): 4 | self.__species = species 5 | 6 | def show_species(self): 7 | print(f'I am a {self.species}.') 8 | 9 | def make_sound(self): 10 | print('Grrrrr') 11 | 12 | class Dog(Mammal): 13 | 14 | def __init__(self): 15 | Mammal.__init__(self, 'Dog') 16 | 17 | def make_sound(self): 18 | print('Woof! Woof!') 19 | 20 | class Cat(Mammal): 21 | 22 | def __init__(self): 23 | Mammal.__init__(self, 'Cat') 24 | 25 | def make_sound(self): 26 | print('Meow') -------------------------------------------------------------------------------- /chapters/11/vehicles.py: -------------------------------------------------------------------------------- 1 | 2 | # Program 11-1 3 | class Automobile: 4 | 5 | def __init__(self, make, model, mileage, price): 6 | self.__make = make 7 | self.__model = model 8 | self.__mileage = mileage 9 | self.__price = price 10 | 11 | def set_make(self, make): 12 | self.__make = make 13 | 14 | def set_model(self, model): 15 | self.__model = model 16 | 17 | def set_mileage(self, mileage): 18 | self.__mileage = mileage 19 | 20 | def set_price(self, price): 21 | self.__price = price 22 | 23 | def get_make(self): 24 | return self.__make 25 | 26 | def get_model(self): 27 | return self.__model 28 | 29 | def get_mileage(self): 30 | return self.__mileage 31 | 32 | def get_price(self): 33 | return self.__price 34 | 35 | # Program 11-2 36 | class Car(Automobile): 37 | 38 | def __init__(self, make, model, mileage, price, doors): 39 | # Calling the superclass's __init__ method and passing 40 | # the required arguments. Note that we also have 41 | # to pass self as an argument. 42 | Automobile.__init__(self, make, model, mileage, price) 43 | 44 | # Initializing custom attribute 45 | self.__doors = doors 46 | 47 | def set_doors(self, doors): 48 | self.__doors = doors 49 | 50 | def get_doors(self): 51 | return self.__doors 52 | 53 | # Program 11-4 54 | class Truck(Automobile): 55 | 56 | def __init__(self, make, model, mileage, price, drive_type): 57 | 58 | Automobile.__init__(self, make, model, mileage, price) 59 | 60 | self.__drive_type = drive_type 61 | 62 | def set_drive_type(self, drive_type): 63 | self.__drive_type = drive_type 64 | 65 | def get_drive_type(self): 66 | return self.__drive_type 67 | 68 | # Program 11-5 69 | 70 | class SUV(Automobile): 71 | 72 | def __init__(self, make, model, mileage, price, pass_cap): 73 | 74 | Automobile.__init__(self, make, model, mileage, price) 75 | 76 | self.__pass_cap = pass_cap 77 | 78 | def set_pass_cap(self, pass_cap): 79 | self.__pass_cap = pass_cap 80 | 81 | def get_pass_cap(self): 82 | return self.__pass_cap 83 | -------------------------------------------------------------------------------- /chapters/13/01.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 | tkinter.mainloop() 9 | 10 | main() -------------------------------------------------------------------------------- /chapters/13/02.py: -------------------------------------------------------------------------------- 1 | # This program displays an empty window. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | 7 | def __init__(self): 8 | # Create the main window widget. 9 | self.main_window = tkinter.Tk() 10 | 11 | # Enter the tkinter main loop. 12 | tkinter.mainloop() 13 | 14 | my_gui = MyGUI() -------------------------------------------------------------------------------- /chapters/13/03.py: -------------------------------------------------------------------------------- 1 | # This program displays a label with text. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | 7 | def __init__(self): 8 | 9 | self.main_window = tkinter.Tk() 10 | 11 | # Creates a label widget containing the 12 | # text "Hello world!" 13 | self.label = tkinter.Label(self.main_window, text='Hello world!') 14 | 15 | # Determines where a widget should be 16 | # positioned and makes the widget visible 17 | # when the window is displayed. 18 | self.label.pack() 19 | 20 | tkinter.mainloop() 21 | 22 | my_gui = MyGUI() -------------------------------------------------------------------------------- /chapters/13/04.py: -------------------------------------------------------------------------------- 1 | # This program displays a label with text. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | 7 | def __init__(self): 8 | 9 | self.main_window = tkinter.Tk() 10 | 11 | # Creates a label widget containing the 12 | # text "Hello world!" 13 | self.label1 = tkinter.Label(self.main_window, text='Hello world!') 14 | self.label2 = tkinter.Label(self.main_window, text='This is a GUI program.') 15 | 16 | # Determines where a widget should be 17 | # positioned and makes the widget visible 18 | # when the window is displayed. 19 | self.label1.pack() 20 | self.label2.pack() 21 | 22 | tkinter.mainloop() 23 | 24 | my_gui = MyGUI() -------------------------------------------------------------------------------- /chapters/13/05.py: -------------------------------------------------------------------------------- 1 | # This program displays a label with text. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | 7 | def __init__(self): 8 | 9 | self.main_window = tkinter.Tk() 10 | 11 | # Creates a label widget containing the 12 | # text "Hello world!" 13 | self.label1 = tkinter.Label(self.main_window, text='Hello world!') 14 | self.label2 = tkinter.Label(self.main_window, text='This is a GUI program.') 15 | 16 | # Determines where a widget should be 17 | # positioned and makes the widget visible 18 | # when the window is displayed. 19 | # 20 | # valid values for "side": 21 | # top, bottom, left, right 22 | self.label1.pack(side='left') 23 | self.label2.pack(side='left') 24 | 25 | tkinter.mainloop() 26 | 27 | my_gui = MyGUI() -------------------------------------------------------------------------------- /chapters/13/06.py: -------------------------------------------------------------------------------- 1 | # This program creates labels in two different frames. 2 | 3 | import tkinter 4 | 5 | class MyGUI: 6 | 7 | def __init__(self): 8 | 9 | self.main_window = tkinter.Tk() 10 | 11 | # Create two frames, one for the top 12 | # of the window, and one for the bottom. 13 | self.top_frame = tkinter.Frame(self.main_window) 14 | self.bottom_frame = tkinter.Frame(self.main_window) 15 | 16 | self.label1 = tkinter.Label(self.top_frame, text='Winken') 17 | self.label2 = tkinter.Label(self.top_frame, text='Blinken') 18 | self.label3 = tkinter.Label(self.top_frame, text='Nod') 19 | 20 | self.label1.pack(side='top') 21 | self.label2.pack(side='top') 22 | self.label3.pack(side='top') 23 | 24 | self.label4 = tkinter.Label(self.bottom_frame, text='Winken') 25 | self.label5 = tkinter.Label(self.bottom_frame, text='Blinken') 26 | self.label6 = tkinter.Label(self.bottom_frame, text='Nod') 27 | 28 | self.label4.pack(side='left') 29 | self.label5.pack(side='left') 30 | self.label6.pack(side='left') 31 | 32 | self.top_frame.pack() 33 | self.bottom_frame.pack() 34 | 35 | tkinter.mainloop() 36 | 37 | my_gui = MyGUI() 38 | 39 | -------------------------------------------------------------------------------- /chapters/13/07.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a Button widget. 2 | 3 | import tkinter 4 | import tkinter.messagebox 5 | 6 | class MyGUI: 7 | 8 | def __init__(self): 9 | 10 | self.main_window = tkinter.Tk() 11 | 12 | self.my_button = tkinter.Button( 13 | self.main_window, \ 14 | text='Click me!', \ 15 | command=self.do_something 16 | ) 17 | 18 | self.my_button.pack() 19 | 20 | tkinter.mainloop() 21 | 22 | def do_something(self): 23 | print('Doing something...') 24 | tkinter.messagebox.showinfo( 25 | 'Response', \ 26 | 'Thanks for clicking the button!' \ 27 | ) 28 | 29 | my_gui = MyGUI() 30 | 31 | -------------------------------------------------------------------------------- /chapters/13/08.py: -------------------------------------------------------------------------------- 1 | # This program demonstrates a Quit button. 2 | 3 | import tkinter 4 | import tkinter.messagebox 5 | 6 | class MyGUI: 7 | 8 | def __init__(self): 9 | 10 | self.main_window = tkinter.Tk() 11 | 12 | self.my_button = tkinter.Button( 13 | self.main_window, \ 14 | text='Click me!', \ 15 | command=self.do_something 16 | ) 17 | 18 | self.quit_button = tkinter.Button( 19 | self.main_window, \ 20 | text = 'Quit', \ 21 | command=self.main_window.destroy 22 | ) 23 | 24 | self.my_button.pack() 25 | self.quit_button.pack() 26 | 27 | tkinter.mainloop() 28 | 29 | def do_something(self): 30 | print('Doing something...') 31 | tkinter.messagebox.showinfo( 32 | 'Response', \ 33 | 'Thanks for clicking the button!' \ 34 | ) 35 | 36 | my_gui = MyGUI() 37 | 38 | -------------------------------------------------------------------------------- /chapters/13/09.py: -------------------------------------------------------------------------------- 1 | # This program converts distances in kilometers 2 | # to miltes. The result is displayed in an info 3 | # dialog box. 4 | 5 | import tkinter 6 | import tkinter.messagebox 7 | 8 | class MyGUI: 9 | 10 | def __init__(self): 11 | 12 | self.main_window = tkinter.Tk() 13 | 14 | self.top_frame = tkinter.Frame(self.main_window) 15 | self.bottom_frame = tkinter.Frame(self.main_window) 16 | 17 | self.prompt_label = tkinter.Label( 18 | self.top_frame, \ 19 | text='Enter a distance in kilometers:' 20 | ) 21 | 22 | self.kilo_entry = tkinter.Entry( 23 | self.top_frame, \ 24 | width=10 25 | ) 26 | 27 | self.prompt_label.pack(side='left') 28 | self.kilo_entry.pack(side='left') 29 | 30 | self.calc_button = tkinter.Button( 31 | self.bottom_frame, \ 32 | text='Convert', \ 33 | command=self.convert 34 | ) 35 | 36 | self.quit_button = tkinter.Button( 37 | self.bottom_frame, \ 38 | text='Quit', \ 39 | command=self.main_window.destroy 40 | ) 41 | 42 | self.calc_button.pack(side='left') 43 | self.quit_button.pack(side='left') 44 | 45 | self.top_frame.pack() 46 | self.bottom_frame.pack() 47 | 48 | tkinter.mainloop() 49 | 50 | def convert(self): 51 | # Get the value entered by the user into 52 | # the kilo_entry widget. 53 | kilo = float(self.kilo_entry.get()) 54 | 55 | miles = kilo * 0.6214 56 | 57 | tkinter.messagebox.showinfo( 58 | 'Results', \ 59 | str(kilo) + ' kilometers is equal to ' + \ 60 | str(miles) + ' miles.' 61 | ) 62 | 63 | my_gui = MyGUI() 64 | 65 | -------------------------------------------------------------------------------- /chapters/13/10.py: -------------------------------------------------------------------------------- 1 | # This program converts distances in kilometers 2 | # to miltes. The result is displayed in an info 3 | # dialog box. 4 | 5 | import tkinter 6 | import tkinter.messagebox 7 | 8 | class MyGUI: 9 | 10 | def __init__(self): 11 | 12 | self.main_window = tkinter.Tk() 13 | 14 | self.top_frame = tkinter.Frame(self.main_window) 15 | self.mid_frame = tkinter.Frame(self.main_window) 16 | self.bottom_frame = tkinter.Frame(self.main_window) 17 | 18 | self.prompt_label = tkinter.Label( 19 | self.top_frame, \ 20 | text='Enter a distance in kilometers:' 21 | ) 22 | 23 | self.kilo_entry = tkinter.Entry( 24 | self.top_frame, \ 25 | width=10 26 | ) 27 | 28 | self.prompt_label.pack(side='left') 29 | self.kilo_entry.pack(side='left') 30 | 31 | self.descr_label = tkinter.Label( 32 | self.mid_frame, \ 33 | text='Converted to miles:' 34 | ) 35 | 36 | # We need a StringVar object to associate with 37 | # an output label. Use the object's set method 38 | # to store a string of blank characters. 39 | self.value = tkinter.StringVar() 40 | 41 | # Any value in self.value will be 42 | # displayed in this label 43 | self.miles_label = tkinter.Label( 44 | self.mid_frame, \ 45 | textvariable=self.value 46 | ) 47 | 48 | self.descr_label.pack(side='left') 49 | self.miles_label.pack(side='left') 50 | 51 | self.calc_button = tkinter.Button( 52 | self.bottom_frame, \ 53 | text='Convert', \ 54 | command=self.convert 55 | ) 56 | 57 | self.quit_button = tkinter.Button( 58 | self.bottom_frame, \ 59 | text='Quit', \ 60 | command=self.main_window.destroy 61 | ) 62 | 63 | self.calc_button.pack(side='left') 64 | self.quit_button.pack(side='left') 65 | 66 | # Pack the frames. 67 | self.top_frame.pack() 68 | self.mid_frame.pack() 69 | self.bottom_frame.pack() 70 | 71 | tkinter.mainloop() 72 | 73 | def convert(self): 74 | # Get the value entered by the user into 75 | # the kilo_entry widget. 76 | kilo = float(self.kilo_entry.get()) 77 | 78 | miles = kilo * 0.6214 79 | 80 | self.value.set(miles) 81 | 82 | my_gui = MyGUI() 83 | 84 | -------------------------------------------------------------------------------- /chapters/13/12.py: -------------------------------------------------------------------------------- 1 | # Demonstrates Radiobutton. 2 | 3 | import tkinter 4 | import tkinter.messagebox 5 | 6 | class MyGUI: 7 | 8 | def __init__(self): 9 | 10 | self.main_window = tkinter.Tk() 11 | 12 | self.top_frame = tkinter.Frame(self.main_window) 13 | self.bottom_frame = tkinter.Frame(self.main_window) 14 | 15 | self.radio_var = tkinter.IntVar() 16 | self.radio_var.set(1) 17 | 18 | self.rb1 = tkinter.Radiobutton( 19 | self.top_frame, \ 20 | text='Option 1', \ 21 | variable=self.radio_var, \ 22 | value=1 23 | ) 24 | 25 | self.rb2 = tkinter.Radiobutton( 26 | self.top_frame, \ 27 | text='Option 2', \ 28 | variable=self.radio_var, \ 29 | value=2 30 | ) 31 | 32 | self.rb3 = tkinter.Radiobutton( 33 | self.top_frame, \ 34 | text='Option 3', \ 35 | variable=self.radio_var, \ 36 | value=3 37 | ) 38 | 39 | self.rb1.pack() 40 | self.rb2.pack() 41 | self.rb3.pack() 42 | 43 | self.ok_button = tkinter.Button( 44 | self.bottom_frame, \ 45 | text='OK', \ 46 | command=self.show_choice 47 | ) 48 | 49 | self.quit_button = tkinter.Button( 50 | self.bottom_frame, \ 51 | text='Quit', \ 52 | command=self.main_window.destroy 53 | ) 54 | 55 | self.ok_button.pack(side='left') 56 | self.quit_button.pack(side='left') 57 | 58 | self.top_frame.pack() 59 | self.bottom_frame.pack() 60 | 61 | tkinter.mainloop() 62 | 63 | def show_choice(self): 64 | tkinter.messagebox.showinfo( 65 | 'Selection', \ 66 | 'You selected option ' + \ 67 | str(self.radio_var.get()) 68 | ) 69 | 70 | my_gui = MyGUI() 71 | 72 | -------------------------------------------------------------------------------- /chapters/13/13.py: -------------------------------------------------------------------------------- 1 | # Demonstrates Radiobutton. 2 | 3 | import tkinter 4 | import tkinter.messagebox 5 | 6 | class MyGUI: 7 | 8 | def __init__(self): 9 | 10 | self.main_window = tkinter.Tk() 11 | 12 | self.top_frame = tkinter.Frame() 13 | self.bottom_frame = tkinter.Frame() 14 | 15 | self.cb_var1 = tkinter.IntVar() 16 | self.cb_var2 = tkinter.IntVar() 17 | self.cb_var3 = tkinter.IntVar() 18 | 19 | self.cb_var1.set(0) 20 | self.cb_var2.set(0) 21 | self.cb_var3.set(0) 22 | 23 | self.cb1 = tkinter.Checkbutton( 24 | self.top_frame, \ 25 | text='Option 1', \ 26 | variable=self.cb_var1 27 | ) 28 | 29 | self.cb2 = tkinter.Checkbutton( 30 | self.top_frame, \ 31 | text='Option 2', \ 32 | variable=self.cb_var2 33 | ) 34 | 35 | self.cb3 = tkinter.Checkbutton( 36 | self.top_frame, \ 37 | text='Option 3', \ 38 | variable=self.cb_var3 39 | ) 40 | 41 | self.cb1.pack() 42 | self.cb2.pack() 43 | self.cb3.pack() 44 | 45 | self.ok_button = tkinter.Button( 46 | self.bottom_frame, \ 47 | text='OK', \ 48 | command=self.show_choice 49 | ) 50 | 51 | self.quit_button = tkinter.Button( 52 | self.bottom_frame, \ 53 | text='Quit', \ 54 | command=self.main_window.destroy 55 | ) 56 | 57 | self.ok_button.pack(side='left') 58 | self.quit_button.pack(side='left') 59 | 60 | self.top_frame.pack() 61 | self.bottom_frame.pack() 62 | 63 | tkinter.mainloop() 64 | 65 | def show_choice(self): 66 | self.message = 'You selected:\n' 67 | 68 | if self.cb_var1.get() == 1: 69 | self.message += '1\n' 70 | if self.cb_var2.get() == 1: 71 | self.message += '2\n' 72 | if self.cb_var3.get() == 1: 73 | self.message += '3\n' 74 | 75 | tkinter.messagebox.showinfo('Selection', self.message) 76 | 77 | my_gui = MyGUI() 78 | 79 | -------------------------------------------------------------------------------- /homework/cashregister/cashregister.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 10-7 (Cash Reg) 3 | # CPSC 3310-01 SP2018 4 | 5 | class CashRegister(): 6 | 7 | def __init__(self): 8 | self.retail_items = [] 9 | 10 | def purchase_item(self, retail_item): 11 | self.retail_items.append(retail_item) 12 | 13 | def get_total(self): 14 | total = 0 15 | for retail_item in self.retail_items: 16 | total += retail_item.get_price() 17 | return total 18 | 19 | def show_items(self): 20 | 21 | output = f'\nThere are {self.get_quantity()} items in the register.' 22 | 23 | output += '\n' + self.make_row('Description:', 'Quantity:', 'Price:') + '\n' 24 | for retail_item in self.retail_items: 25 | desc = retail_item.get_description() 26 | quantity = str(retail_item.get_inventory_quantity()) 27 | price = str(retail_item.get_price()) 28 | 29 | output += self.make_row(desc, quantity, price) 30 | output += '\n' 31 | return output 32 | 33 | def clear(self): 34 | self.retail_items = [] 35 | 36 | def get_quantity(self): 37 | return len(self.retail_items) 38 | 39 | def make_row(self, *args): 40 | output = '' 41 | for arg in args: 42 | output += arg.ljust(20) 43 | return output 44 | 45 | -------------------------------------------------------------------------------- /homework/cashregister/cashregister_program.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise Cash Reg 3 | # CPSC 3310-01 SP2018 4 | 5 | from cashregister import CashRegister 6 | from retailitem import RetailItem 7 | 8 | def main(): 9 | 10 | def input_retail_item(): 11 | description = input('Retail item description: ') 12 | inventory_quantity = int(input('Retail item inventory quantity: ')) 13 | price = float(input('Retail item price: ')) 14 | 15 | return description, inventory_quantity, price 16 | 17 | def purchase_item(description, inventory_quantity, price): 18 | register.purchase_item(RetailItem(description, inventory_quantity, price)) 19 | 20 | another = 'y' 21 | register = CashRegister() 22 | 23 | print(( 24 | '\nThis program is a cash register simulator. You\n' + 25 | 'will first be prompted to type a description,\n' + 26 | 'inventory quantity, and a price for a retail\n' + 27 | 'item. You can continue to add as many products\n' + 28 | 'as necessary. When you are finished, the items\n' + 29 | 'in the register, along with the total price of\n' + 30 | 'all the items, will be displayed.\n' 31 | )) 32 | 33 | while another.lower() == 'y': 34 | description, inventory_quantity, price = input_retail_item() 35 | purchase_item(description, inventory_quantity, price) 36 | another = input('Purchase another item? (y/n): ') 37 | 38 | print(register.show_items() + '\n') 39 | print('Total price: $', format(register.get_total(), ',.2f'), sep='') 40 | 41 | 42 | main() -------------------------------------------------------------------------------- /homework/cashregister/retailitem.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 10-5 (Cash Reg) 3 | # CPSC 3310-01 SP2018 4 | 5 | class RetailItem(): 6 | 7 | def __init__(self, description, inventory_quantity, price): 8 | self.description = description 9 | self.inventory_quantity = inventory_quantity 10 | self.price = price 11 | 12 | def get_description(self): 13 | return self.description 14 | 15 | def get_inventory_quantity(self): 16 | return self.inventory_quantity 17 | 18 | def get_price(self): 19 | return self.price -------------------------------------------------------------------------------- /homework/email_address_book/email_address_book.py: -------------------------------------------------------------------------------- 1 | import pickle 2 | import os.path 3 | 4 | class EmailAddressBook(): 5 | 6 | 7 | def __init__(self, file_name): 8 | self.__file_name = file_name 9 | 10 | self.__book = {} 11 | 12 | # Read from binary if it exists 13 | if self.file_exists(): 14 | self.read_binary() 15 | 16 | ''' 17 | Adds a new email to the book dictionary, 18 | where the key is the firstname and lastname 19 | separated by an underscore and the value is 20 | the email address. If the key exists, return 21 | an error string, else, add the email to the 22 | dictionary and return the new entry as a tuple. 23 | 24 | @param first_name {str} First name of person 25 | @param last_name {str} Last name of person 26 | @return {tuple|str} 27 | ''' 28 | def create(self, first_name, last_name, email): 29 | key = f'{first_name}_{last_name}' 30 | 31 | if not key in self.__book: 32 | self.__book[key] = email 33 | return (key, self.__book[key]) 34 | else: 35 | return False 36 | 37 | ''' 38 | Tries to get the email that is associated 39 | with the key: {first_name}_{last_name}. If 40 | the key exists, return the entry as a tuple. 41 | If the key does not exist and an exception 42 | is raised, return an error string. 43 | 44 | @param first_name {str} First name of person 45 | @param last_name {str} Last name of person 46 | @return {tuple|str} 47 | ''' 48 | def read(self, first_name, last_name): 49 | key = f'{first_name}_{last_name}' 50 | 51 | try: 52 | return (key, self.__book[key]) 53 | except KeyError: 54 | return False 55 | 56 | ''' 57 | Update the email associated with the key: 58 | {first_name}_{last_} and return the updated 59 | entry as a tuple. 60 | 61 | @param first_name {str} First name of person 62 | @param last_name {str} Last name of person 63 | @return {tuple} 64 | ''' 65 | def update(self, first_name, last_name, email): 66 | key = f'{first_name}_{last_name}' 67 | if key in self.__book: 68 | self.__book[key] = email 69 | return (key, self.__book[key]) 70 | else: 71 | return False 72 | 73 | ''' 74 | Deletes the email associated with the 75 | first name and last name. If there 76 | is no email associated with the name, 77 | return an error string. 78 | 79 | @param first_name {str} First name of person 80 | @param last_name {str} Last name of person 81 | @return {tuple} 82 | ''' 83 | def delete(self, first_name, last_name): 84 | key = f'{first_name}_{last_name}' 85 | 86 | try: 87 | del self.__book[key] 88 | return True 89 | except KeyError: 90 | return False 91 | 92 | 93 | ''' 94 | Returns the contents of the email address book. 95 | ''' 96 | def get_book(self): 97 | return self.__book 98 | 99 | ''' 100 | Tries to read from binary file and save data 101 | to self.__book. Raises exceptions if the file 102 | doesn't exist or an error occurs while reading 103 | from the file. 104 | ''' 105 | def read_binary(self): 106 | try: 107 | with open(self.__file_name, 'rb') as input_file: 108 | self.__book = pickle.load(input_file) 109 | except FileNotFoundError: 110 | print(f'{self.__file_name} does not exist.') 111 | except IOError: 112 | print(f'An error occurred while trying to read from {self.__file_name}') 113 | 114 | ''' 115 | Tries to save self.__book to a binary file. Rases 116 | an exception if it is unable to write to the file. 117 | ''' 118 | def write_binary(self): 119 | try: 120 | with open(self.__file_name, 'wb') as output_file: 121 | pickle.dump(self.__book, output_file) 122 | except IOError: 123 | print(f'An error occurred while trying to write to {self.__file_name}') 124 | 125 | ''' 126 | Returns a boolean indicating if self.__file_name 127 | exits within the directory. 128 | 129 | @return {bool} 130 | ''' 131 | def file_exists(self): 132 | return os.path.isfile(self.__file_name) 133 | -------------------------------------------------------------------------------- /homework/email_address_book/program.py: -------------------------------------------------------------------------------- 1 | from email_address_book import EmailAddressBook 2 | 3 | def main(): 4 | 5 | def create_ordered_list(items): 6 | output = '' 7 | for item in items: 8 | current_index = items.index(item) 9 | 10 | output += str(current_index) 11 | output += '. ' 12 | output += item 13 | # Don't append a newline after the last list item 14 | output += ('' if current_index == (len(items)) else '\n') 15 | return output 16 | 17 | # Views 18 | MAIN_VIEW = 'MainView' 19 | CREATE_ADDRESS_VIEW = 'CreateAddressView' 20 | LOOKUP_ADDRESS_VIEW = 'LookUpAddressView' 21 | UPDATE_ADDRESS_VIEW = 'UpdateAddressView' 22 | DELETE_ADDRESS_VIEW = 'DeleteAddressView' 23 | View_ALL_ADDRESSES_VIEW = 'ViewAllAddressesView' 24 | 25 | # Events 26 | USER_CHOICE_EVENT = 'user_choice' 27 | 28 | class Model(): 29 | 30 | def __init__(self): 31 | self.__book = EmailAddressBook('db.dat') 32 | 33 | def create(self, first_name, last_name, email): 34 | return self.__book.create(first_name, last_name, email) 35 | 36 | def read(self, first_name, last_name): 37 | return self.__book.read(first_name, last_name) 38 | 39 | def update(self, first_name, last_name, email): 40 | return self.__book.update(first_name, last_name, email) 41 | 42 | def delete(self, first_name, last_name): 43 | return self.__book.delete(first_name, last_name) 44 | 45 | def write(self): 46 | self.__book.write_binary() 47 | 48 | def get(self): 49 | return self.__book.get_book() 50 | 51 | class BaseView(): 52 | 53 | def __init__(self, name, controller): 54 | self.__name = name 55 | self.__controller = controller 56 | self.__choices = ['Exit Program'] 57 | 58 | def get_name(self): 59 | return self.__name 60 | 61 | def get_controller(self): 62 | return self.__controller 63 | 64 | def set_choices(self, choices): 65 | self.__choices += choices 66 | 67 | def get_choices(self): 68 | return create_ordered_list(self.__choices) 69 | 70 | def send_data_to_controller(self, event, payload): 71 | data = { 72 | 'origin': self.__name, 73 | 'event': event, 74 | 'payload': payload 75 | } 76 | self.__controller.on_receive_data_from_view(data) 77 | 78 | def handle_choice(self, choice): 79 | payload = {'choice': choice} 80 | self.send_data_to_controller(USER_CHOICE_EVENT, payload) 81 | if choice == 0: 82 | print('Data saved to binary.') 83 | 84 | def choice_prompt(self): 85 | choice = -1 86 | minimum = 0 87 | maximum = len(self.__choices) - 1 88 | 89 | while not (choice >= minimum and choice <= maximum): 90 | try: 91 | choice = int(input('> ')) 92 | except ValueError as e: 93 | print(f'Please enter an integer between {minimum} and {maximum}.') 94 | 95 | self.handle_choice(choice) 96 | 97 | def name_prompt(self): 98 | first_name = input('First Name: ') 99 | last_name = input('Last Name: ') 100 | return first_name, last_name 101 | 102 | def email_prompt(self): 103 | return input('Email Address: ') 104 | 105 | class MainView(BaseView): 106 | 107 | def __init__(self, name, controller): 108 | super().__init__(name, controller) 109 | 110 | self.set_choices([ 111 | 'Create New Address', 112 | 'Look Up Address', 113 | 'Update Address', 114 | 'Delete Address', 115 | 'View All Addresses' 116 | ]) 117 | 118 | def render(self): 119 | print() 120 | print() 121 | print('Email Address Book') 122 | print('This application allows you to view\nand store email addresses' + 123 | ' belonging to people.') 124 | print() 125 | print(self.get_choices()) 126 | print() 127 | self.choice_prompt() 128 | 129 | class CreateAddressView(BaseView): 130 | 131 | def __init__(self, name, controller): 132 | super().__init__(name, controller) 133 | 134 | def render(self): 135 | print() 136 | print() 137 | print('Create new email address:') 138 | print() 139 | 140 | first_name, last_name = self.name_prompt() 141 | email = self.email_prompt() 142 | 143 | results = (self.get_controller() 144 | .create_email_address(first_name, last_name, email)) 145 | 146 | print() 147 | if results: 148 | print(f'Email {email} belonging to {first_name} {last_name}' + 149 | ' has been added to the book.') 150 | else: 151 | print(f'There is already an email associated with {first_name} {last_name}.') 152 | 153 | self.get_controller().render_main_view() 154 | 155 | class LookUpAddressView(BaseView): 156 | 157 | def __init__(self, name, controller): 158 | super().__init__(name, controller) 159 | 160 | def render(self): 161 | print() 162 | print() 163 | print('Look up an existing address:') 164 | print() 165 | first_name, last_name = self.name_prompt() 166 | 167 | results = (self.get_controller() 168 | .look_up_email_address(first_name, last_name)) 169 | 170 | print() 171 | if results: 172 | print(f'The email belonging to {first_name} {last_name} is {results[1]}.') 173 | else: 174 | print(f'There is no email associated with {first_name} {last_name}.') 175 | 176 | self.get_controller().render_main_view() 177 | 178 | class UpdateAddressView(BaseView): 179 | 180 | def __init__(self, name, controller): 181 | super().__init__(name, controller) 182 | 183 | def render(self): 184 | print() 185 | print() 186 | print('Update an existing email address:') 187 | print() 188 | first_name, last_name = self.name_prompt() 189 | email = self.email_prompt() 190 | 191 | results = (self.get_controller() 192 | .update_email_address(first_name, last_name, email)) 193 | 194 | print() 195 | if results: 196 | print(f'The Email belonging to {first_name} {last_name}' + 197 | ' has been updated.') 198 | else: 199 | print(f'There is no email associated with {first_name} {last_name}.') 200 | 201 | self.get_controller().render_main_view() 202 | 203 | class DeleteAddressView(BaseView): 204 | 205 | def __init__(self, name, controller): 206 | super().__init__(name, controller) 207 | 208 | def render(self): 209 | print() 210 | print() 211 | print('Delete an email address:') 212 | print() 213 | first_name, last_name = self.name_prompt() 214 | 215 | results = (self.get_controller() 216 | .delete_email_address(first_name, last_name)) 217 | 218 | print() 219 | if results: 220 | print(f'{first_name} {last_name} has been added removed from the book.') 221 | else: 222 | print(f'There is no email associated with {first_name} {last_name}.') 223 | 224 | self.get_controller().render_main_view() 225 | 226 | class ViewAllAddressesView(BaseView): 227 | 228 | def __init__(self, name, controller): 229 | super().__init__(name, controller) 230 | 231 | def render(self): 232 | print() 233 | print() 234 | print('Emails inside the address book:') 235 | print() 236 | 237 | results = self.get_controller().get_email_addresses() 238 | 239 | print() 240 | if len(results) > 0: 241 | print('{:<30} {:<30}'.format('Full Name', 'Email Address')) 242 | print() 243 | for full_name, email in results.items(): 244 | print('{:<30} {:<30}'.format(full_name.replace('_', ' '), email)) 245 | else: 246 | print('The email address book is empty.') 247 | 248 | self.get_controller().render_main_view() 249 | 250 | class Controller(): 251 | 252 | def __init__(self, model): 253 | self.__model = model 254 | 255 | # Instantiate views 256 | self.__main_view = MainView(MAIN_VIEW, self) 257 | self.__create_address_view = CreateAddressView(CREATE_ADDRESS_VIEW, self) 258 | self.__lookup_address_view = LookUpAddressView(LOOKUP_ADDRESS_VIEW, self) 259 | self.__update_address_view = UpdateAddressView(UPDATE_ADDRESS_VIEW, self) 260 | self.__delete_address_view = DeleteAddressView(DELETE_ADDRESS_VIEW, self) 261 | self.__view_all_addresses_view = ViewAllAddressesView(View_ALL_ADDRESSES_VIEW, self) 262 | 263 | # Kickstart app by rendering main view 264 | self.__main_view.render() 265 | 266 | def on_receive_data_from_view(self, data): 267 | origin = data['origin'] 268 | 269 | if origin == MAIN_VIEW: 270 | self.handle_data_from_main_view(data) 271 | 272 | def handle_data_from_main_view(self, data): 273 | event = data['event'] 274 | payload = data['payload'] 275 | 276 | if event == USER_CHOICE_EVENT: 277 | choice = payload['choice'] 278 | 279 | if choice == 0: 280 | # Write to binary before exit 281 | self.__model.write() 282 | elif choice == 1: 283 | self.__create_address_view.render() 284 | elif choice == 2: 285 | self.__lookup_address_view.render() 286 | elif choice == 3: 287 | self.__update_address_view.render() 288 | elif choice == 4: 289 | self.__delete_address_view.render() 290 | elif choice == 5: 291 | self.__view_all_addresses_view.render() 292 | 293 | def create_email_address(self, first_name, last_name, email): 294 | return self.__model.create(first_name, last_name, email) 295 | 296 | def look_up_email_address(self, first_name, last_name): 297 | return self.__model.read(first_name, last_name) 298 | 299 | def update_email_address(self, first_name, last_name, email): 300 | return self.__model.update(first_name, last_name, email) 301 | 302 | def delete_email_address(self, first_name, last_name): 303 | return self.__model.delete(first_name, last_name) 304 | 305 | def get_email_addresses(self): 306 | return self.__model.get() 307 | 308 | def render_main_view(self): 309 | self.__main_view.render() 310 | 311 | controller = Controller(Model()) 312 | 313 | if __name__ == '__main__': 314 | main() -------------------------------------------------------------------------------- /homework/employee/employee.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 11-1, 11-2 3 | # CPSC 3310-01 SP2018 4 | 5 | class Employee: 6 | 7 | employee_type = 0 8 | employee_type_str = 'Employee' 9 | 10 | def __init__(self, name, number): 11 | self.__name = name 12 | self.__number = number 13 | 14 | def get_name(self): 15 | return self.__name 16 | 17 | def get_number(self): 18 | return self.__number 19 | 20 | def set_name(self, name): 21 | self.__name = name 22 | 23 | def set_number(self, number): 24 | self.__number = number 25 | 26 | class ProductionWorker(Employee): 27 | 28 | employee_type = 1 29 | employee_type_str = 'ProductionWorker' 30 | 31 | def __init__(self, name, number, shift, hourly_pay_rate): 32 | Employee.__init__(self, name, number) 33 | 34 | self.__shift = shift 35 | self.__hourly_pay_rate = hourly_pay_rate 36 | 37 | def get_shift(self): 38 | return self.__shift 39 | 40 | def get_hourly_pay_rate(self): 41 | return self.__hourly_pay_rate 42 | 43 | def set_shift(self, shift): 44 | self.__shift = shift 45 | 46 | def set_hourly_pay_rate(self, hourly_pay_rate): 47 | self.__hourly_pay_rate = hourly_pay_rate 48 | 49 | class ShiftSupervisor(Employee): 50 | 51 | employee_type = 2 52 | employee_type_str = 'ShiftSupervisor' 53 | 54 | def __init__(self, name, number, annual_salary, annual_production_bonus): 55 | Employee.__init__(self, name, number) 56 | 57 | self.__annual_salary = annual_salary 58 | self.__annual_production_bonus = annual_production_bonus 59 | 60 | def get_annual_salary(self): 61 | return self.__annual_salary 62 | 63 | def get_annual_production_bonus(self): 64 | return self.__annual_production_bonus 65 | 66 | def set_annual_salary(self, annual_salary): 67 | self.__annual_salary = annual_salary 68 | 69 | def set_annual_production_bonus(self, annual_production_bonus): 70 | self.__annual_production_bonus = annual_production_bonus 71 | 72 | -------------------------------------------------------------------------------- /homework/employee/employee_program.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 11-1, 11-2 3 | # CPSC 3310-01 SP2018 4 | 5 | from employee import Employee, ProductionWorker, ShiftSupervisor 6 | 7 | def main(): 8 | 9 | another = 'y' 10 | 11 | print_greeting() 12 | 13 | while another.lower() == 'y': 14 | 15 | # 0 = Employee, 1 = ProductionWorker, 2 = ShiftSupervisor 16 | choice = get_choice() 17 | 18 | print(f'\nEnter in the following fields\nto create a new "{get_employee_type_str(choice)}":\n') 19 | 20 | name, number = get_employee_name_number() 21 | 22 | # ProductionWorker (employee_type is 1) 23 | if choice == ProductionWorker.employee_type: 24 | production_worker_actions(name, number, ProductionWorker.employee_type_str) 25 | # ShiftSupervisor (employee_type is 2) 26 | elif choice == ShiftSupervisor.employee_type: 27 | shift_supervisor_actions(name, number, ShiftSupervisor.employee_type_str) 28 | 29 | # Employee (employee_type is 0) 30 | else: 31 | employee_actions(name, number, Employee.employee_type_str) 32 | 33 | print() 34 | another = input('Add another employee? (y/n): ') 35 | 36 | def get_employee_name_number(): 37 | name = get_valid_input( 38 | 'Employee name: ', 39 | 'str', 40 | lambda val: len(val) > 0, 41 | 'Please enter in the employee\'s name!' 42 | ) 43 | 44 | number = get_valid_input( 45 | 'Employee number: ', 46 | 'int', 47 | lambda val: val > 0, 48 | 'Employee number must be greater than 0!' 49 | ) 50 | 51 | return name, number 52 | 53 | def employee_actions(name, number, type_str): 54 | obj = Employee(name, number) 55 | print() 56 | print_generic_employee_info(obj, type_str) 57 | 58 | def shift_supervisor_actions(name, number, type_str): 59 | annual_salary, annual_production_bonus = get_shift_supervisor_attributes() 60 | obj = ShiftSupervisor(name, number, annual_salary, annual_production_bonus) 61 | print_shift_supervisor_info(obj, type_str) 62 | 63 | def production_worker_actions(name, number, type_str): 64 | shift, hourly_pay_rate = get_production_worker_attributes() 65 | obj = ProductionWorker(name, number, shift, hourly_pay_rate) 66 | print_production_worker_info(obj, type_str) 67 | 68 | 69 | def print_shift_supervisor_info(obj, type_str): 70 | print() 71 | print_generic_employee_info(obj, type_str) 72 | print_table_of_contents([ 73 | ['Employee annual salary', f'${format_money(obj.get_annual_salary())}'], 74 | ['Employee annual bonus', f'${format_money(obj.get_annual_production_bonus())}'] 75 | ]) 76 | 77 | def print_production_worker_info(obj, type_str): 78 | print() 79 | print_generic_employee_info(obj, type_str) 80 | print_table_of_contents([ 81 | ['Employee shift', obj.get_shift()], 82 | ['Employee hourly pay', f'${format_money(obj.get_hourly_pay_rate())}'] 83 | ]) 84 | 85 | def print_generic_employee_info(employee, employee_type_str): 86 | print(f'Info for new {employee_type_str}, {employee.get_name()}:') 87 | print_table_of_contents([ 88 | ['Employee name', employee.get_name()], 89 | ['Employee number', employee.get_number()] 90 | ]) 91 | 92 | def get_employee_type_str(employee_type): 93 | for cls in [Employee, ProductionWorker, ShiftSupervisor]: 94 | if employee_type == cls.employee_type: 95 | employee_type_str = cls.employee_type_str 96 | return employee_type_str 97 | 98 | def get_choice(): 99 | choice = get_valid_input( 100 | 'Type of employee to create (0, 1, or 2): ', 101 | 'int', 102 | lambda val: val >= 0 and val <= 2, 103 | 'Please enter either 0, 1, or 2.' 104 | ) 105 | return choice 106 | 107 | def get_shift_supervisor_attributes(): 108 | annual_salary = get_valid_input( 109 | 'Employee annual salary: ', 110 | 'float', 111 | lambda val: val > 0, 112 | 'Salary must be greater than 0!' 113 | ) 114 | annual_production_bonus = get_valid_input( 115 | 'Employee bonus: ', 116 | 'float', 117 | lambda val: val > 0, 118 | 'The bonus must be greater than 0!' 119 | ) 120 | return annual_salary, annual_production_bonus 121 | 122 | def get_production_worker_attributes(): 123 | shift = get_valid_input( 124 | 'Employee shift: ', 125 | 'int', 126 | lambda val: val == 1 or val == 2, 127 | 'The shift must be either 1 or 2.' 128 | ) 129 | hourly_pay_rate = get_valid_input( 130 | 'Employee hourly pay: ', 131 | 'float', 132 | lambda val: val > 0, 133 | 'Hourly pay must be greater than 0!' 134 | ) 135 | return shift, hourly_pay_rate 136 | 137 | def print_greeting(): 138 | print('\nThis program allows you to create\nthe following types of employees:\n') 139 | print_table_of_contents([ 140 | ['Employee', Employee.employee_type], 141 | ['ProductionWorker', ProductionWorker.employee_type], 142 | ['ShiftSupervisor', ShiftSupervisor.employee_type] 143 | ]) 144 | print() 145 | 146 | def format_money(integer): 147 | return format(integer, ',.2f') 148 | 149 | def print_table_of_contents(lists, delimeter = '.', max_width = 30): 150 | for list in lists: 151 | label, value = list[0], list[1] 152 | print(f'{label:{delimeter}<{max_width}}{value}') 153 | 154 | def get_valid_input(input_label, input_type, is_valid, error_message): 155 | while True: 156 | try: 157 | if input_type == 'float': 158 | val = float(input(input_label)) 159 | elif input_type == 'int': 160 | val = int(input(input_label)) 161 | else: 162 | val = input(input_label) 163 | if is_valid(val): 164 | return val 165 | else: 166 | print(error_message) 167 | except ValueError: 168 | print(error_message) 169 | 170 | main() 171 | -------------------------------------------------------------------------------- /homework/employee/employee_program2.py: -------------------------------------------------------------------------------- 1 | from employee import Employee, ProductionWorker, ShiftSupervisor 2 | 3 | class Utils: 4 | 5 | @staticmethod 6 | def get_valid_input(input_label, input_type, is_valid, error_message): 7 | while True: 8 | try: 9 | if input_type == 'float': 10 | val = float(input(input_label)) 11 | elif input_type == 'int': 12 | val = int(input(input_label)) 13 | else: 14 | val = input(input_label) 15 | if is_valid(val): 16 | return val 17 | else: 18 | print(error_message) 19 | except ValueError: 20 | print(error_message) 21 | 22 | class ProgramItem: 23 | 24 | def __init__(self, the_attrs, the_class): 25 | self.__attrs = the_attrs 26 | self.__Class = the_class 27 | self.__instance = None 28 | 29 | def instantiate(self): 30 | self.__instance = self.__Class(**self.get_inputs()) 31 | 32 | def get_inputs(self): 33 | attr_values = {} 34 | for attr in self.__attrs: 35 | input_id, input_label, input_type = attr['input_id'], \ 36 | attr['input_label'], attr['input_type'] 37 | attr_values[input_id] = input(f'{input_label}: ') 38 | 39 | if input_type == 'float': 40 | attr_values[input_id] = float(attr_values[input_id]) 41 | elif input_type == 'int': 42 | attr_values[input_id] = int(attr_values[input_id]) 43 | 44 | return attr_values 45 | 46 | def get_output_list(self): 47 | output = [] 48 | for attr in self.__attrs: 49 | output.append({ 50 | 'label': attr['output_label'], 51 | 'value': getattr(self.__instance, attr['accessor'])() 52 | }) 53 | return output 54 | 55 | def print_output(self): 56 | for dict in self.get_output_list(): 57 | label, value = dict['label'], dict['value'] 58 | print(f'{label}: {value}') 59 | 60 | def __str__(self): 61 | return self.__Class.employee_type_str 62 | 63 | class Program: 64 | 65 | def __init__(self, base_attrs, items): 66 | 67 | self.__base_attrs = base_attrs 68 | self.__items = items 69 | self.__program_items = [] 70 | 71 | for item in items: 72 | self.__program_items.append( 73 | ProgramItem(self.__base_attrs + item['attrs'], item['class']) 74 | ) 75 | 76 | self.start() 77 | 78 | def get_choice(self): 79 | return Utils.get_valid_input( 80 | 'Type of employee to create (0, 1, or 2): ', 81 | 'int', 82 | lambda val: val >= 0 and val <= 2, 83 | 'Please enter 0, 1, or 2.' 84 | ) 85 | 86 | def instantiate_item(self, index): 87 | self.__program_items[index].instantiate() 88 | 89 | def print_item_output(self, index): 90 | self.__program_items[index].print_output() 91 | 92 | def use_item(self, index): 93 | print(f'\nCreate a(an) {self.__program_items[index]}:') 94 | self.instantiate_item(index) 95 | print() 96 | self.print_item_output(index) 97 | 98 | def start(self): 99 | another = 'y' 100 | 101 | while another.lower() == 'y': 102 | self.use_item(self.get_choice()) 103 | another = input('Add another employee (y/n): ') 104 | 105 | def main(): 106 | 107 | program = Program([{ 108 | 'input_id': 'name', 109 | 'input_label': 'Employee name', 110 | 'input_type': 'str', 111 | 'accessor': 'get_name', 112 | 'output_label': 'Name' 113 | }, 114 | { 115 | 'input_id': 'number', 116 | 'input_label': 'Employee number', 117 | 'input_type': 'int', 118 | 'accessor': 'get_number', 119 | 'output_label': 'Number' 120 | }], 121 | [{ 122 | 'class': Employee, 123 | 'attrs': [] 124 | }, 125 | { 126 | 'class': ProductionWorker, 127 | 'attrs': [{ 128 | 'input_id': 'shift', 129 | 'input_label': 'Employee shift (1 or 2)', 130 | 'input_type': 'int', 131 | 'accessor': 'get_shift', 132 | 'output_label': 'Shift' 133 | }, 134 | { 135 | 'input_id': 'hourly_pay_rate', 136 | 'input_label': 'Employee hourly rate', 137 | 'input_type': 'float', 138 | 'accessor': 'get_hourly_pay_rate', 139 | 'output_label': 'Hourly rate' 140 | }] 141 | }, 142 | { 143 | 'class': ShiftSupervisor, 144 | 'attrs': [{ 145 | 'input_id': 'annual_salary', 146 | 'input_label': 'Employee annual salary', 147 | 'input_type': 'float', 148 | 'accessor': 'get_annual_salary', 149 | 'output_label': 'Annual salary' 150 | }, 151 | { 152 | 'input_id': 'annual_production_bonus', 153 | 'input_label': 'Employee bonus', 154 | 'input_type': 'float', 155 | 'accessor': 'get_annual_production_bonus', 156 | 'output_label': 'Bonus' 157 | }] 158 | }]) 159 | 160 | main() -------------------------------------------------------------------------------- /homework/factorial.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 4-11 3 | # CPSC 3310-01 SP2018 4 | 5 | num = int(input('Enter a number >= 0 for factorial: ')) 6 | 7 | while num != -1: 8 | 9 | # Calculate and display factorial if number is >= 0 10 | if num >= 0: 11 | factorial = 1 12 | for i in range(1, num + 1): 13 | factorial *= i 14 | 15 | print('Factorial of', num, 'is', factorial) 16 | print() 17 | 18 | # Go again? 19 | print('Enter a number >= 0 for factorial ') 20 | num = int(input('or enter -1 to exit: ')) -------------------------------------------------------------------------------- /homework/line_numbers/line_numbers.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 6-3 3 | # CPSC 3310-01 SP2018 4 | 5 | def main(): 6 | 7 | filename = input('Name of the file: ') 8 | 9 | try: 10 | 11 | infile = open(filename, 'r') 12 | 13 | result = '' 14 | current_line = 1 15 | 16 | for line in infile: 17 | result += f'{current_line}: {line}' 18 | current_line += 1 19 | 20 | infile.close() 21 | 22 | except IOError: 23 | print(f'Failed to read file {filename}. :(') 24 | else: 25 | print(f'Contents of {filename}:\n') 26 | print(result) 27 | 28 | main() -------------------------------------------------------------------------------- /homework/line_numbers/presidents.txt: -------------------------------------------------------------------------------- 1 | George Washington 2 | John Adams 3 | Thomas Jefferson 4 | James Madison 5 | James Monroe -------------------------------------------------------------------------------- /homework/lo_shu_magic_square/lo_shu_magic_square.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 7-11 3 | # CPSC 3310-01 SP2018 4 | 5 | ''' 6 | Requirements for a Magic Square: 7 | 8 | - Each cell must contain a unique integer 9 | between 1 and n^2, where n is the number 10 | of cells on each side. 11 | - The sum of all rows, cols, and diagonals 12 | must be equal to the magic constant: n(n^2 + 1)/2 13 | 14 | ''' 15 | 16 | from functools import reduce 17 | 18 | class Error(Exception): 19 | '''Base class for exceptions in this module.''' 20 | pass 21 | 22 | class SquareSizeError(Error): 23 | '''Raised when the square argument provided to 24 | is_magic_square is a list with an unequal size 25 | (length of rows not equal to length of cols). 26 | ''' 27 | def __init__(self, message): 28 | self.message = message 29 | 30 | def main(): 31 | 32 | valid_square = [ 33 | [8, 1, 6], 34 | [3, 5, 7], 35 | [4, 9, 2] 36 | ] 37 | 38 | invalid_square = [ 39 | [9, 4, 1], 40 | [4, 7, 5], 41 | [6, 8, 3] 42 | ] 43 | 44 | print(stringify_square(valid_square)) 45 | print(is_lo_shu_magic_square(valid_square)) 46 | print() 47 | print(stringify_square(invalid_square)) 48 | print(is_lo_shu_magic_square(invalid_square)) 49 | 50 | ''' 51 | Print an appropriate message that 52 | is predicated on the provided square 53 | being a Lo Shu Magic. 54 | 55 | @param {list} square 56 | @param {bool} 57 | ''' 58 | def is_lo_shu_magic_square(square): 59 | try: 60 | size = get_square_size(square) 61 | except SquareSizeError as e: 62 | print(e) 63 | else: 64 | 65 | magic_const = get_magic_const(size) 66 | 67 | if is_magic(square, size, magic_const): 68 | return 'The list is a Lo Shu Magic Square.' 69 | else: 70 | return 'The list is NOT a Lo Shu Magic Square.' 71 | 72 | ''' 73 | Returns the magic constant for a 74 | particular square size. 75 | 76 | @param size {list} 77 | @return {int} 78 | ''' 79 | def get_magic_const(size): 80 | return size * (size**2 + 1)/2 81 | 82 | ''' 83 | If the provided square parameter is 84 | a Lo Shu Magic Square. 85 | 86 | @param square {list} 87 | @param size {int} 88 | @param magic_const {int} 89 | @return {bool} 90 | ''' 91 | def is_magic(square, size, magic_const): 92 | return has_valid_cells(square, size) and \ 93 | has_magic_rows(square, size, magic_const) and \ 94 | has_magic_cols(square, size, magic_const) and \ 95 | has_magic_left_diagonal(square, size, magic_const) and \ 96 | has_magic_right_diagonal(square, size, magic_const) 97 | 98 | ''' 99 | Get the size of the square. The size 100 | is the quantity of both rows and cols. 101 | If the number of rows does not match 102 | the quantity of cols in each row, an 103 | exception is raised. 104 | 105 | @param square {list} 106 | @return num_rows {int} 107 | ''' 108 | def get_square_size(square): 109 | num_rows = len(square) 110 | cols = list(map(len, square)) 111 | 112 | if [num_rows] * num_rows == cols: 113 | return num_rows 114 | else: 115 | raise SquareSizeError(('The list is not a square. Make sure the' 116 | ' quantity of rows is equal to the quantity of columns.')) 117 | 118 | ''' 119 | Check if each column in each 120 | row has a unique int between 1 and 121 | n^2, where n is square size (e.g., 3). 122 | 123 | @param square {list} 124 | @param size {int} 125 | @return status {bool} 126 | ''' 127 | def has_valid_cells(square, size): 128 | maximum = size**2 # maximum int permitted in cell 129 | current = 1 # current int we are checking (1-n^2) 130 | occurences = 0 # occurences of current int 131 | status = True 132 | 133 | while current <= maximum and status == True: 134 | for row in range(size): 135 | for col in range(size): 136 | if square[row][col] == current: 137 | occurences += 1 138 | 139 | if occurences <= 1: 140 | # Zero or one occurance of the current int. 141 | # So far, the square is unique. Move on 142 | # to the next int. 143 | current += 1 144 | occurences = 0 145 | else: 146 | # Short circuit. If there are more than 147 | # 1 occurences of an int, the square is 148 | # not unique. 149 | status = False 150 | 151 | return status 152 | 153 | ''' 154 | Checks if the rows in the square 155 | are all equal to the magic constant. 156 | 157 | @param square {list} 158 | @param size {int} 159 | @param magic_const {int} 160 | @return {bool} 161 | ''' 162 | def has_magic_rows(square, size, magic_const): 163 | row_sums = [] 164 | for row in range(size): 165 | row_sums.append(0) 166 | for col in range(size): 167 | row_sums[row] += square[row][col] 168 | return sum_list_items(row_sums) == magic_const * size 169 | 170 | ''' 171 | Checks if the cols in the square 172 | are all equal to the magic constant. 173 | 174 | @param square {list} 175 | @param size {int} 176 | @param magic_const {int} 177 | @return {bool} 178 | ''' 179 | def has_magic_cols(square, size, magic_const): 180 | col_sums = [] 181 | for col in range(size): 182 | col_sums.append(0) 183 | for row in range(size): 184 | col_sums[col] += square[row][col] 185 | return sum_list_items(col_sums) == magic_const * size 186 | 187 | ''' 188 | Checks if the cols in the 189 | left diagram add up to the magic constant. 190 | 191 | Left diagonal: [0][0], [1][1], [2][2] 192 | 193 | @param square {list} 194 | @param size {int} 195 | @param magic_const {int} 196 | @return {bool} 197 | ''' 198 | def has_magic_left_diagonal(square, size, magic_const): 199 | col_sums = [] 200 | for i in range(size): 201 | col_sums.append(square[i][i]) 202 | return sum_list_items(col_sums) == magic_const 203 | 204 | ''' 205 | Checks if the cols in the 206 | right diagram add up to the magic constant. 207 | 208 | Right diagonal: [0][2], [1][1], [2][0] 209 | 210 | @param square {list} 211 | @param size {int} 212 | @param magic_const {int} 213 | @return {bool} 214 | ''' 215 | def has_magic_right_diagonal(square, size, magic_const): 216 | col_sums = [] 217 | for i in range(size): 218 | col_sums.append(square[i][(size - 1) - i]) 219 | return sum_list_items(col_sums) == magic_const 220 | 221 | ''' 222 | Returns a string representation 223 | of the square to be printed, etc. 224 | 225 | @param square {list} 226 | @return output {str} 227 | ''' 228 | def stringify_square(square): 229 | size = get_square_size(square) 230 | 231 | output = '' 232 | for row in range(size): 233 | for col in range(size): 234 | output += '' if col == 0 else ' ' 235 | output += str(square[row][col]) 236 | output += '\n' if row != size - 1 else '' 237 | return output 238 | 239 | ''' 240 | Takes a list and reduces it to a single value 241 | by summing the items. 242 | 243 | @param {list} 244 | @return {any} 245 | ''' 246 | def sum_list_items(list): 247 | return reduce(lambda x, y: x + y, list) 248 | 249 | if __name__ == '__main__': 250 | main() -------------------------------------------------------------------------------- /homework/lo_shu_magic_square/lo_shu_magic_square_test.py: -------------------------------------------------------------------------------- 1 | import lo_shu_magic_square 2 | 3 | def main(): 4 | 5 | test('sum_list_items()', lo_shu_magic_square.sum_list_items([2, 2]), 4) 6 | 7 | test('stringify_square()', lo_shu_magic_square.stringify_square([[0,0,0],[0,0,0],[0,0,0]]), '0 0 0\n0 0 0\n0 0 0') 8 | 9 | test('has_magic_right_diagonal()', lo_shu_magic_square.has_magic_right_diagonal([ 10 | [0, 0, 5], 11 | [0, 5, 0], 12 | [5, 0, 0] 13 | ], 3, 15), True) 14 | 15 | test('has_magic_left_diagonal()', lo_shu_magic_square.has_magic_left_diagonal([ 16 | [5, 0, 0], 17 | [0, 5, 0], 18 | [0, 0, 5] 19 | ], 3, 15), True) 20 | 21 | test('has_magic_cols()', lo_shu_magic_square.has_magic_cols([ 22 | [1, 11, 3], 23 | [6, 2, 2], 24 | [8, 2, 10] 25 | ], 3, 15), True) 26 | 27 | test('has_magic_rows()', lo_shu_magic_square.has_magic_rows([ 28 | [9, 3, 3], 29 | [13, 2, 0], 30 | [1, 4, 10] 31 | ], 3, 15), True) 32 | 33 | test('has_valid_cells()', lo_shu_magic_square.has_valid_cells([ 34 | [1, 2, 3], 35 | [4, 5, 6], 36 | [7, 8, 9] 37 | ], 3), True) 38 | 39 | test('get_square_size()', lo_shu_magic_square.get_square_size([[0,0,0],[0,0,0],[0,0,0]]), 3) 40 | 41 | test('get_magic_const()', lo_shu_magic_square.get_magic_const(3), 15) 42 | 43 | test('is_magic()', lo_shu_magic_square.is_magic([ 44 | [4, 9, 2], 45 | [3, 5, 7], 46 | [8, 1, 6] 47 | ], 3, 15), True) 48 | 49 | def test(assertion, actual, expected): 50 | if actual == expected: 51 | print(f'(PASS) {assertion}') 52 | else: 53 | print(f'(X) {assertion}') 54 | 55 | if __name__ == '__main__': 56 | main() 57 | -------------------------------------------------------------------------------- /homework/pet/pet.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 10-1 3 | # CPSC 3310-01 SP2018 4 | 5 | class Pet: 6 | 7 | def __init__(self, name, animal_type, age): 8 | self.__name = name 9 | self.__animal_type = animal_type 10 | self.__age = age 11 | 12 | def set_name(self, name): 13 | self.__name = name 14 | 15 | def set_animal_type(self, animal_type): 16 | self.__animal_type = animal_type 17 | 18 | def set_age(self, age): 19 | self.__age = age 20 | 21 | def get_name(self): 22 | return self.__name 23 | 24 | def get_animal_type(self): 25 | return self.__animal_type 26 | 27 | def get_age(self): 28 | return self.__age 29 | 30 | def __str__(self): 31 | return ('Name: ' + self.__name + '\nType: ' 32 | + self.__animal_type + '\nAge: ' + self.__age) -------------------------------------------------------------------------------- /homework/pet/pet_program.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 10-1 3 | # CPSC 3310-01 SP2018 4 | 5 | from pet import Pet 6 | 7 | def main(): 8 | 9 | again = 'y' 10 | 11 | while again.lower() == 'y': 12 | pet_name = input('Pet name: ') 13 | pet_type = input('Pet type: ') 14 | pet_age = input('Pet age: ') 15 | 16 | the_pet = Pet(pet_name, pet_type, pet_age) 17 | 18 | print() 19 | print(the_pet) 20 | 21 | again = input('Again? (y/n): ') 22 | 23 | main() -------------------------------------------------------------------------------- /homework/physics.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 5 3 | # CPSC 3310-01 SP2018 4 | 5 | ANOTHER = 'y' 6 | 7 | DEBUG = False 8 | 9 | TIME_UNIT = 'Seconds' 10 | MASS_UNIT = 'Kilograms' 11 | DISTANCE_UNIT = 'Meters' 12 | VELOCITY_UNIT = 'm/s' 13 | KINETIC_ENERGY_UNIT = 'Joules' 14 | GRAVITY = 9.8 15 | 16 | def main(): 17 | '''Main program function. Ask the user for the time, 18 | in seconds, that the object was dropped as well as for 19 | the mass of the object, in kilograms. Display the results. 20 | Then, ask the user if they would like to go again. 21 | ''' 22 | 23 | print('\nYou will be prompted to enter in a time', 24 | 'in seconds, \nin which an object fell and ' 25 | 'the mass, in kilograms,\nof the object. After, ' 26 | 'you will be provided with the \nfollowing calculations: ' 27 | 'distance, velocity, and kin-\netic energy.\n') 28 | 29 | another = 'y' 30 | 31 | while another.lower() == ANOTHER: 32 | 33 | drop_physics(get_time(), get_mass()) 34 | 35 | another = input('Another? (y/n): ') 36 | 37 | def get_time(): 38 | '''Prompts the user to enter a time, in seconds, 39 | and returns the result as a float. 40 | 41 | Returns: 42 | time (float): time in seconds 43 | ''' 44 | 45 | time = float(input('Time in seconds object was dropped: ')) 46 | 47 | return time 48 | 49 | def get_mass(): 50 | '''Prompts the user to enter the mass of an object, 51 | in kilograms, and returns the result as a float. 52 | 53 | Returns: 54 | mass (float): mass in kilograms 55 | ''' 56 | 57 | mass = float(input('Object mass in kilograms: ')) 58 | 59 | return mass 60 | 61 | def drop_physics(time, mass): 62 | '''Calculate falling distance, velocity, and kinetic energy 63 | from the provided time and mass inputs. Then, output 64 | the time, mass, distance, velocity, and kinetic energy. 65 | 66 | Args: 67 | time (float): Time, in seconds, object was dropped 68 | mass (float): Mass, in kilograms, of the object 69 | 70 | Returns: void 71 | ''' 72 | 73 | falling_distance = get_falling_distance(time) 74 | velocity = get_velocity(falling_distance, time) 75 | kinetic_energy = get_kinetic_energy(mass, velocity) 76 | 77 | print() 78 | 79 | print_items([ 80 | {'label': 'Time', 'value': time, 'unit': TIME_UNIT}, 81 | {'label': 'Mass', 'value': mass, 'unit': MASS_UNIT}, 82 | {'label': 'Distance', 'value': falling_distance, 'unit': DISTANCE_UNIT}, 83 | {'label': 'Velocity', 'value': velocity, 'unit': VELOCITY_UNIT}, 84 | {'label': 'Kinetic energy', 'value': kinetic_energy, 'unit': KINETIC_ENERGY_UNIT} 85 | ]) 86 | 87 | print() 88 | 89 | def get_falling_distance(time): 90 | '''Calculates the distance, in meters, 91 | that an object falls based on the time, 92 | in seconds, it was dropped. 93 | 94 | Uses the formula: distance = 1/2*9.8*time^2 95 | 96 | Args: 97 | time (int): Amount of time in seconds 98 | that the object has fallen. 99 | 100 | Returns: 101 | distance (float): distance in meters rounded to the hundreds 102 | place. 103 | ''' 104 | distance = 0.5 * GRAVITY * (float(time)**2) 105 | 106 | return distance 107 | 108 | def get_velocity(distance, time): 109 | '''Calculates the velocity, or how quickly the object 110 | moves, by dividing the distance traveled by the amount 111 | of time it took to travel the distance. 112 | 113 | Uses the formula: distance / time 114 | 115 | Args: 116 | distance (float): distance in meters rounded 117 | to the hundreds place. 118 | time (int): distance traveled in seconds. 119 | 120 | Returns: 121 | velocity (float): velocity in meters per second rounded to the 122 | hundreds place. 123 | 124 | ''' 125 | 126 | velocity = distance / time 127 | 128 | return round_hundredths(velocity) 129 | 130 | def get_kinetic_energy(mass, velocity): 131 | '''Calculates the kinetic energy of an object, in joules. 132 | 133 | Uses the formula: 1/2*mass*velocity^2 134 | 135 | 136 | Args: 137 | mass (float): Mass of the object in kilograms 138 | velocity (float): Velocity of the moving object 139 | in meters per second. 140 | 141 | Returns: 142 | kinetic_energy (float): Kinetic energy in joules 143 | rounded to the hundreds place. 144 | 145 | ''' 146 | 147 | kinetic_energy = 0.5 * mass * velocity**2 148 | 149 | return round_hundredths(kinetic_energy) 150 | 151 | def left_adjust_str(str): 152 | '''Aligns a text string to the left. 153 | 154 | Args: 155 | str (str): String to align 156 | 157 | Returns: 158 | str: Aligned string 159 | ''' 160 | 161 | return str.ljust(25, ' ') 162 | 163 | def format_item(label, value, unit): 164 | '''Concatenates label, value, and unit and 165 | formats the value to a floating point number rounded 166 | to the hundreds place. Also, the label is aligned to 167 | the left. 168 | 169 | Args: 170 | label (str): The label of the item (e.g., Time, Mass, etc.) 171 | value (float): The numerical value of the item 172 | unit (str): The units of the numerical value (e.g., Seconds, Joules, etc.) 173 | 174 | Returns: 175 | str: Formatted item 176 | 177 | ''' 178 | return '%s %.2f %s' % (left_adjust_str(label), value, unit) 179 | 180 | def print_items(dicts): 181 | '''Takes a list of dictionaries to loop over and print. 182 | 183 | Args: 184 | dicts (list -> dicts): A list of dictionaries describing 185 | the item to print. The dictionary should have the following 186 | keys: label, value, unit. 187 | 188 | Returns: void 189 | 190 | ''' 191 | for dict in dicts: 192 | print(format_item(dict['label'], dict['value'], dict['unit'])) 193 | 194 | def round_hundredths(num): 195 | '''Takes a number and rounds it to the hundredths place. 196 | 197 | Args: 198 | num (int|float): Number to round 199 | 200 | Returns: 201 | float: Rounded number 202 | 203 | ''' 204 | return round(num, 2) 205 | 206 | main() -------------------------------------------------------------------------------- /homework/sets/set_file1.txt: -------------------------------------------------------------------------------- 1 | I am proud to be an American -------------------------------------------------------------------------------- /homework/sets/set_file2.txt: -------------------------------------------------------------------------------- 1 | I am proud to be a Jamaican -------------------------------------------------------------------------------- /homework/sets/sets.py: -------------------------------------------------------------------------------- 1 | # Matthew Kosloski 2 | # Exercise 9-6 3 | # CPSC 3310-01 SP2018 4 | 5 | def main(): 6 | # Get input text of first file and create set containing 7 | # its unique words 8 | input_name = input('Enter the name of the first input file: ') 9 | file1 = open(input_name, 'r') 10 | text1 = file1.read() 11 | file1.close() 12 | words1 = text1.split() 13 | set1 = set(words1) 14 | 15 | # Get input text of second file and create set containing its 16 | # unique words 17 | input_name = input('Enter the name of the second input file: ') 18 | file2 = open(input_name , 'r') 19 | text2 = file2.read() 20 | file2.close() 21 | words2 = text2.split() 22 | set2 = set(words2) 23 | 24 | # Obtain the union of the sets and print the items in it 25 | union = set1.union(set2) 26 | print('These are the unique words that are ' \ 27 | 'contained in both files:') 28 | for item in union: 29 | print(item) 30 | print() 31 | 32 | # Obtain the intersection of the sets and print the items in it 33 | intersection = set1.intersection(set2) 34 | print('These are the words that appear in both files:') 35 | for item in intersection: 36 | print(item) 37 | print() 38 | 39 | # Obtain the difference between set1 and set2 and 40 | # print the items in it 41 | difference1 = set1.difference(set2) 42 | print('These are the words that appear in the first file' \ 43 | ' but do not appear in the second file:') 44 | for item in difference1: 45 | print(item) 46 | print() 47 | 48 | # Obtain the difference between set2 and set1 and 49 | # print the items in it 50 | difference2 = set2.difference(set1) 51 | print('These are the words that appear in the second file' \ 52 | ' but do not appear in the first file:') 53 | for item in difference2: 54 | print(item) 55 | print() 56 | 57 | # Obtain the symmetric difference between set1 and set2 58 | # and print the items in it 59 | sym_diff = set1.symmetric_difference(set2) 60 | print('These are the words that appear in the first' \ 61 | ' file or the second file but do not appear in' \ 62 | ' the both files:') 63 | for item in sym_diff: 64 | print(item) 65 | print() 66 | 67 | main() 68 | 69 | -------------------------------------------------------------------------------- /notes/01.md: -------------------------------------------------------------------------------- 1 | # Chapter 1: Introduction to Computers and Programming 2 | 3 | ## 1.2 Hardware and Software 4 | 5 | ### Hardware 6 | 7 | **Hardware**— All of the physical devices, or components, that a computer is made of. 8 | 9 | ### Parts of a typical computer system: 10 | 11 | - Central Processing Unit (CPU) 12 | - Main memory 13 | - Secondary storage devices 14 | - Input devices (e.g., mouse, keyboard, camera, etc.) 15 | - Output devices (e.g., monitors, printers, speakers, etc.) 16 | 17 | ### The CPU 18 | 19 | **Central processing unit (CPU)**— The component of the computer that actually runs programs and software. 20 | 21 | Early CPUs were big and made of vacuum tubes and switches. Today's CPUs are small chips known as _microprocessors_. 22 | 23 | ### Main memory 24 | 25 | **Main Memory**— A chip where the computer stores a program while the program is running, as well as the data that the program is working with. 26 | 27 | For instance, when writing documents in word processors, both are stored on main memory, commonly known as _random-access memory_, or _RAM_. 28 | 29 | Data is stored at random locations in main memory, and the CPU can quickly access it. 30 | 31 | RAM is _volatile_, which means data is stored temporarily and is lost when power is no longer supplied to it. 32 | 33 | ### Secondary storage 34 | 35 | **Secondary storage**— A type of non-volatile memory that holds data for long periods of time, even when there is no power to the computer. 36 | 37 | Programs are stored in secondary memory and are then loaded onto main memory at the request of the CPU. 38 | 39 | A _disk drive_ is a common type of secondary storage that stores data by magnetically encoding it onto a spinning circular disk. 40 | 41 | A _solid-state drive_ is a type of secondary storage with no moving parts and is quicker than disk drives. 42 | 43 | _USB_ drives are small, inexpensive, reliable, devices that plug into the computer's universal serial bus (USB) port and store data in _flash memory_. 44 | 45 | Optical devices such as compact discs (CDs) and digital versatile discs (DVDs) encode data on the surface as a series of pits. 46 | 47 | ### Input devices 48 | 49 | _Input_ is any data the computer collects from people and other devices. 50 | 51 | ### Output devices 52 | 53 | _Output_ is any data the computer produces for people or for other devices (e.g., sales report, list of names, graphical image). 54 | 55 | ### Software 56 | 57 | Everything the computer does is under control of software, either system software or application software. 58 | 59 | ### System software 60 | 61 | **System software**— Programs that control and manage the basic operations of a computer. 62 | 63 | Types of system software: 64 | -Operating systems: An _operating system_ is the most fundamental set of programs on a computer that manages connected devices, controls hardware, and permits the reading and writing of data. 65 | -Utility programs: A _utility program_ performs a specialized task that enhances the computer's operation or safeguards. 66 | -Software development tools: Programs used to create, modify, and test software such as assemblers and compilers. 67 | 68 | ### Application software 69 | 70 | **Application software**— Programs that make a computer useful for everyday tasks. such as Microsoft Word, Google Chrome, and Call of Duty. 71 | 72 | ## 1.3 How Computers Store Data 73 | 74 | Data is stored using a _binary numbering system_ that uses two digits: 0 and 1. 75 | 76 | A computer's memory is divided into tiny _bytes_, which are divided into smaller units called _bits_, or _binary digit_. 77 | 78 | Bits are tiny electrical components that can hold a positive or negative charge. 79 | 80 | When a piece of data is stored in a byte, the computer sets eight bits to an on/off pattern like: 81 | 82 | |off|on|off|off|on|on|off|on| 83 | |-|-|-|-|-|-|-|-| 84 | |0|1|0|0|1|1|0|1| 85 | 86 | ### Storing Numbers 87 | 88 | The binary number system is base-2 (since it contains two digits in the system). Each bit in a byte is assigned to a number, starting with 0, from right to left: 89 | 90 | |2^7|2^6|2^5|2^4|2^3|2^2|2^1|2^0| 91 | |-|-|-|-|-|-|-|-| 92 | |1|0|0|1|1|1|0|1| 93 | 94 | To determine the value of a binary number you simply add up the position values of all the 1s, therefore, the above binary number is 157 in base-10. 95 | 96 | The maxiumum value that can be stored in a byte is 255 (when all bits are storing a 1); however, 256 digits can be represented by a byte (0-255). 97 | 98 | If you need to store a number larger than 255, use another byte. The maximum value that can be stored in two bytes is 65,535. 99 | 100 | ### Storing Characters 101 | 102 | Characters are stored in memory by being first converted to numerical codes. Such numerical codes are then stored in memory as a binary number. 103 | 104 | The _American Standard Code for Information Interchange_ (ASCII) stores 128 numerical codes representing English letters, various punctuation marks, etc. For example, the ASCII numerical code for uppercase A is 65. It is then stored in memory like so: 105 | 106 | |2^7|2^6|2^5|2^4|2^3|2^2|2^1|2^0| 107 | |-|-|-|-|-|-|-|-| 108 | |0|1|0|0|0|0|0|1| 109 | 110 | `2^0 + 2^6 = 65` 111 | 112 | Since ASCII is limited to 128 characters, another character set was needed. To remedy this, the Unicode character set was created in the 1990s. _Unicode_ is compatible with ASCII, but can also represent characters for many of the languages in the world. Unicode stores characters in 2 bytes. 113 | 114 | ### Advanced Number Storage 115 | 116 | Negative numbers and real numbers cannot be represented using the simple binary numbering technique we discussed. 117 | 118 | Negative numbers are encode using _two's complement_, and real numbers are encoded in _floating-point notation_. 119 | 120 | ### Other Types of Data 121 | 122 | Computers are _digital_ devices, or devices that use binary numbers. 123 | 124 | Computers can store images using binary data by converting each pixel or _picture element_ to a numerical code that represents the pixel's color. The numberical code is then stored in memory as a binary number. 125 | 126 | Audio is broken down into smaller pieces known as _samples_, and each sample is converted to a binary number and stored in memory. A quality audio file is divided into more than 44,000 samples per second. 127 | 128 | ## 1.4 How a Program Works 129 | 130 | A CPU can perform simple operations on pieces of data with the assistance of a program, which lists instructions for the CPU. For a CPU to carry out an instruction, it must be written in _machine language_. 131 | 132 | A machine language instruction exists for every operation that a CPU is capable of performing (e.g., addition, subtraction, etc.). This is called an _instruction set_. 133 | 134 | Each brand of microprocessor has its own unique instruction set, which is only understood by microprocessors of the same brand. 135 | 136 | Programs are stored on secondary storage devices, and when the CPU needs to execute it, the program is loaded into the RAM. 137 | 138 | When a CPU executes the instructions in a program, it engages in the _fetch-decode-execute cycle_: 139 | - **Fetch** The first step of the cycle is to fetch the next instruction from memory into the CPU. 140 | - **Decode** The previously fetched command is then decoded to determine which operation should be performed by the CPU. 141 | - **Execute** The appropriate operation is executed. 142 | 143 | ### From Machine Language to Assembly Language 144 | 145 | Since CPUs only understand machine language, and programming in such a language is tedious, _assembly language_ was created. 146 | 147 | Assembly language is a low-level computer programming language that is the closest a programming language gets to machine language. 148 | 149 | Assembly uses short words, or _mnemonics_ in place of binary instructions. 150 | 151 | Since CPUs have different instruction sets, there are different versions of Assembly for processors. 152 | 153 | Assembly language must eventually be converted to binary for the CPU to execute the instructions. This is done by an _assembler_. 154 | 155 | ### High-level Languages 156 | 157 | _High-level languages_ allow you to create powerful and complex programs without knowing how the CPU operates and without writing large numbers of low-level instructions. 158 | 159 | ### Key Words, Operators, and Syntax: An Overview 160 | 161 | Each high-level language has its own set of predefined words that the programmer must use to write a program. Such words are known as _reserved words_. 162 | 163 | Examples of reserved words in Python: 164 | - and 165 | - global 166 | - return 167 | 168 | All programming languages have _operators_ which perform operations on _operands_. 169 | 170 | `3 + 4` 171 | 172 | In the above _statement_, '3' and '4' are operands and '+' is an operator. 173 | 174 | Languages also have _syntax_, which is a set of rules that must be strictly followed when writing programs. 175 | 176 | ### Compilers and Interpreters 177 | 178 | High-level languages are converted to machine language through the use of _compilers_ and _interpreters_. 179 | 180 | A compiler is a program that translates a high-level language program into a separate machine language program. 181 | 182 | An interpreter is a program that translates each high-level instruction and immediately executes it. 183 | 184 | Sometimes code contains a mistake, or _syntax error_, from misspelled key words, to the incorrect usage of an operator. 185 | 186 | ## 1.5 Using Python 187 | 188 | ### Python Interpreter 189 | 190 | You can use the interpreter in two modes: interactive mode and script mode. In _interactive mode_, the interpreter waits for you to type Python statements on the keyboard and then executes it. In _script mode_, the interpreter reads the contents of a file, or _Python program_, and executes each statement as it reads from the file. 191 | 192 | ### Interactive Mode 193 | 194 | Interactive mode can be initialized by navigating to the shell and typing 'python.' 195 | 196 | The '>>>' indicates that the interpreter is waiting for you to type a Python statement. 197 | 198 | ### Writing Python Programs and Running Them in Script Mode 199 | 200 | Interactive mode is used for testing code. The statements you enter aren't saved; the results simply are displayed on a screen. 201 | 202 | If you want to save a set of Python statements as a program, you save them in a '.py' file and execute the file using the interpeter from the shell. This is using the interpreter in script mode. 203 | 204 | To run a file, simply: 205 | 206 | `python test.py` 207 | 208 | ### The IDLE Programming Environment 209 | 210 | In addition to using the Python interpreter in script mode and interactive mode, you can use an _integrated development environment_, which is a program that gives you tools to write, execture, and test a program. 211 | 212 | With IDLE, you can write programs, save them to disk, and execute them. 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | -------------------------------------------------------------------------------- /notes/03.md: -------------------------------------------------------------------------------- 1 | # Chapter 3: Decision Structures and Boolean Logic 2 | 3 | ## 3.1 The `if` Statement 4 | 5 | A *control structure* is a logical design that controls the order in which a set of statements execute. A *sequence structure* is a set of statements that execute in the order that they appear. A *decision structure* is a control structure that executes a set of statements only under certain conditions. An action is *conditionally executed* if it is performed only when a certain condition is true. A *single alternative decision structure* provides only one alternative path of execution. 6 | 7 | 8 | ## Boolean Expressions and Relational Operators 9 | 10 | Expressions tested by `if` statements are called *Boolean expressions.* Typically, such expressions are formed with *relational operators* which determine if a specific relationship exists between two values. 11 | 12 | The following table depicts the relational operators available in Python: 13 | 14 | 15 | | **Operator** | **Meaning** | 16 | | ------------ | ------------------------ | 17 | | > | Greater than | 18 | | < | Less than | 19 | | >= | Greater than or equal to | 20 | | <= | Less than or equal to | 21 | | == | Equal to | 22 | | != | Not equal to | 23 | 24 | Examples of Boolean expressions that compare variables `x` and `y`: 25 | 26 | 27 | | **Expression** | **Meaning** | 28 | | -------------- | ------------------------------------ | 29 | | `x > y` | Is `x` greater than `y`? | 30 | | `x < y` | Is `x` less than `y`? | 31 | | `x >= y` | Is `x` greater than or equal to `y`? | 32 | | `x <= y` | Is `x` less than or equal to `y`? | 33 | | `x == y` | Is `x` equal to `y`? | 34 | | `x != y` | Is `x` not equal to `y`? | 35 | 36 | You can use the Python interpreter mode to experiment with these operators 37 | 38 | 39 | >>> x = 1 [ENTER] 40 | >>> y = 0 [ENTER] 41 | >>> x > y [ENTER] 42 | True 43 | 44 | **The** `**>=**` **and** `**<=**` **Operators** 45 | The `>=` operator determines whether the operand on its left is greater than *or* equal to the operand on its right. The `<=` operator determines whether the operand on its left is less than *or* equal to the operand on its right. 46 | 47 | **The** `**==**` **Operator** 48 | The `==` operator determines whether the operand on its left is equal to the operand on its right. 49 | 50 | **The** `**!=**` **Operator** 51 | The `!=` operator is the not-equal-to operator. It determines whether the operand on its left is not equal to the operand on its right, which is the opposite of the `==` operator. 52 | 53 | 54 | ## Putting It All Together 55 | if sales > 50000: 56 | bonus = 500.0 57 | 58 | If `sales` is greater than `50000`, the variable bonus is assigned to `500.0`. 59 | 60 | 61 | if balance == 0: 62 | # Statements appearing here will 63 | # be executed only if the balance is 64 | # equal to 0. 65 | 66 | 67 | if choice != 5: 68 | # Statements appearing here will 69 | # be executed only if choice is 70 | # not equal to 5. 71 | 72 | 73 | ## 3.2 The `if-else` Statement 74 | 75 | The `if-else` statement is a *dual alternative decision structure* which has two possible paths of execution—one path is taken if a condition is true, and the other path is taken if the condition is false. 76 | 77 | 78 | if condition: 79 | statement 80 | statement 81 | statement, etc 82 | else: 83 | statement 84 | statement 85 | statment, etc 86 | 87 | **Indentation in the** `**if-else**` Statement 88 | When you write an `if-else` statement, follow these guidelines for indentation: 89 | 90 | - Make sure the `if` clause and the `else` clause are aligned. 91 | - The `if` and the `else` clause are each followed by a block of statements. Make sure the statements in the blocks are consistently indented. 92 | 93 | 94 | ## 3.2 Comparing Strings 95 | 96 | 97 | name1 = 'Mary' 98 | name2 = 'Mark' 99 | if name1 == name2: 100 | print('The names are the same.') 101 | else: 102 | print('The names are NOT the same.') 103 | 104 | The `==` operator compares `name1` and `name2` to determine whether they are equal. Because the strings ‘Mary’ and ‘Mark’ are not equal, the `else` clause will display the message: ‘The names are NOT the same.’ 105 | 106 | String comparisons are case sensitive. For instance, the strings ‘saturday’ and ‘Saturday’ are not equal. 107 | 108 | **Other String Comparisons** 109 | In addition to determining whether strings are equal or not equal, you can also determine whether one string is greater than or less than another string. 110 | 111 | Recall that computers do not actually store characters, such as A, B, C, and so on, in memory. Rather, they store numeric codes that represent the characters (from the ASCII character set). 112 | 113 | Some facts pertaining to ASCII 114 | 115 | - The uppercase characters A through Z are represented by the numbers 65 through 90. 116 | - The lowercase characters a through z are represented by the numbers 97 through 122. 117 | - When digits 0-9 are stored as characters, that are represented by numbers 48 through 57. 118 | - A blank space is represented by the number 32. 119 | 120 | 121 | if 'a' < 'b': 122 | print('The letter a is less than the letter b') 123 | 124 | The above code determines whether the ASCII code for the character ‘a’ is less than the code for letter ‘b.’ 125 | 126 | When you use relational operators to compare strings such as “Mary” and “Mark”, the strings are compared character-by-character. 127 | 128 | “Mary” is greater than “Mark” because the ASCII code for “y” is greater than the code for “k”, the strings are the same length, and the first three letters are the same. 129 | 130 | If one of the strings in a comparison is shorter than the other, only the corresponding characters will be compared. If the corresponding characters are identical, then the shorter string is considered less than the longer string. 131 | 132 | 133 | ## 3.4 Nested Decision Structures and the `if-elif-else` Statement 134 | 135 | Follow these rules when writing nested `if` statements: 136 | 137 | - Make sure each `else` clause is aligned with its matching `if` clause. 138 | - Make sure the statements in each block are consistently indented. 139 | 140 | **The** `**if-elif-else**` **Statement** 141 | Here is the general format: 142 | 143 | 144 | if condition_1: 145 | statement 146 | statement 147 | etc. 148 | elif condition_2: 149 | statement 150 | statement 151 | etc. 152 | else: 153 | statement 154 | statement 155 | etc. 156 | 157 | If `condition_1` is true, the block of statements that immediately follow is executed, up to the `elif` clause. The rest of the structure is ignored. If `condition_1` is false, however, the program jumps to the very next `elif` clause and tests `condition_2`. If it is true, the block of statements that immediately follow is executed, up to the next `elif` clause. The rest of the structure is ignored. This process continues until a condition is true, or no more `elif`s. If no condition is true, block statements after the `else` clause are executed. 158 | 159 | 160 | ## 3.5 Logical Operators 161 | 162 | The logical `and` operator and the logical `or` operator allow you to connect multiple Boolean expressions to create a compound expression. The logical `not` operator reverses the truth of a Boolean expression. 163 | 164 | 165 | | **Expression** | **Meaning** | 166 | | ------------------ | ------------------------------------------------- | 167 | | `x > y and a < b` | Is `x` greater than `y` AND is `a` less than `b`? | 168 | | `x == y or x == z` | Is `x` equal to `y` OR is `x` equal to `z`? | 169 | | `not (x > y)` | Is the expression `x > y` NOT true? | 170 | 171 | 172 | **AND Operator** 173 | The `and` operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true only when both subexpressions are true. 174 | 175 | **OR Operator** 176 | The `or` operator takes two Boolean expressions as operands and creates a compound Boolean expression that is true when either of the subexpressions is true. 177 | 178 | **Short-Circuit Evaluation** 179 | Both the `and` and `or` operators perform *short-circuit evaluation*. Essentially, the interpreter skips checking the remaining operands if it doesn’t need to. For instance, if an operand on the left side of the `and` operator is false, the interpreter doesn’t even bother checking the boolean values of the remaining operators because it already has an answer. 180 | 181 | **The** `**not**` **Operator** 182 | The `not` operator is a unary (meaning it operates on one operand) operator that takes a Boolean expression as its operand and reverses its logical value. 183 | 184 | **Checking Numeric Ranges with Logical Operators** 185 | When determining whether a number is inside a range, it is best to use the `and` operator. For example, the following `if` statement checks the value in `x` to determine whether it is inside the range of 20 through 40: 186 | 187 | 188 | if x >= 20 and x <= 40: 189 | print('In range of 20 and 40') 190 | 191 | Use the `or` operator when checking if a number is outside of a range: 192 | 193 | 194 | if x < 20 or x > 40: 195 | print('Outside of range 20 and 40') 196 | 197 | 198 | ## 3.6 Boolean Variables 199 | 200 | A boolean variable can reference one of two values: `True` or `False`. Boolean variables are commonly used as flags, which indicate whether specific conditions exist. 201 | 202 | In addition to `str`, `int`, and `float`, Python has a `bool` datatype that can either be `True` or `False`. -------------------------------------------------------------------------------- /notes/04.md: -------------------------------------------------------------------------------- 1 | # Chapter 4: Repetition Structures 2 | 3 | # 4.1 Introduction to Repetition Structures 4 | 5 | A repetition structure causes a statement or set of statements to execute repeatedly. 6 | 7 | Benefits of repetition structures: 8 | 9 | - No duplicated code, therefore, smaller programs 10 | - Saves time 11 | - Easy to maintain 12 | 13 | A *repetition structure* repeats code as many times as necessary. 14 | 15 | ## Condition-Controlled and Count-Controlled Loops 16 | 17 | A *condition-controlled loop* uses a true/false condition to control the number of times that it repeats (e.g., `while` loops). 18 | 19 | A *count-controlled* loop repeats a specified number of times (e.g., `for` loops). 20 | 21 | # 4.2 The `while` Loop: A Condition-Controlled Loop 22 | 23 | The `while` loop: do some task *while* a condition is *true*. 24 | 25 | General format of a `while` loop in Python: 26 | 27 | 28 | while condition: 29 | statement 30 | statement 31 | etc. 32 | 33 | The `condition` is evaluated as either true or false. If true, statements that appear in the block are executed, and then the loop starts over. If false, the program exists the loop. 34 | 35 | Each execution of the body of a loop is known as an *iteration.* 36 | 37 | ## The `while` Loops is a Pretest Loop 38 | 39 | A *pretest loop* evaluates the condition prior to executing. While loops will not execute if the condition is `false` to begin with. 40 | 41 | ## Infinite Loops 42 | 43 | Most of the time, loops must contain within themselves a way to terminate. An *infinite loop* continues to repeat until the program is interrupted. In most cases, this should be avoided. 44 | 45 | # 4.3 The `for` Loop: A Count-Controlled Loop 46 | 47 | The `for` statement is designed to work with a sequence of data items. Here is the general format: 48 | 49 | 50 | for variable in [value1, value2, value3]: 51 | statement 52 | statement 53 | etc. 54 | 55 | The `variable` is assigned the first value in the list, and then the statements that appear in the block are executed. Then, `variable` is assigned the next value in the list, and the statements in the block are executed again. This continues until `variable` has been assigned the last value in the list. 56 | 57 | The variable used in a `for` statement is commonly referred to as a *target variable* because it is the target of an assignment at the beginning of each loop iteration. 58 | 59 | 60 | ## Using the `range` Function with the `for` Loop 61 | 62 | The range function creates a type of object known as an iterable. An *iterable* is an object, similar to a list, that contains a sequence of values that can be iterated over with something like a loop. Here is an example: 63 | 64 | 65 | for num in range(5): 66 | print(num) 67 | 68 | Here, range generates a sequence of numbers in the range of 0 up to (but not including) 5. It’s the same as: 69 | 70 | 71 | for num in [0, 1, 2, 3, 4]: 72 | print(num) 73 | 74 | If you pass one argument to `range`, that argument is used as the ending limit (amount of times the loop will iterate). If you pass two arguments, the first is the starting value and the second is the ending value. 75 | 76 | 77 | for num in range(1, 5): 78 | print(num) # 1, 2, 3, 4 79 | 80 | A third argument can be passed to `range`. This argument is a *step value* because it changes how much the loop increments by. 81 | 82 | 83 | for num in range(1, 10, 2): 84 | print(num) # 1, 3, 5, 7, 9 85 | ## Letting the User Control the Loop Iterations 86 | 87 | You can use the `input` function to allow the user to specify the start, end, and step of the `range` function. 88 | 89 | 90 | ## Generating an Iterable Sequence that Ranges from Highest to Lowest 91 | 92 | You can also use `range` to generate sequences of numbers that go from highest to lowest: 93 | 94 | 95 | range(10, 0, -1) # 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 96 | 97 | 98 | # 4.4 Calculating a Running Total 99 | 100 | A running total is a sum of numbers that accumulates with each iteration of a loop. The variable used to keep the running total is called an *accumulator.* The accumulator is declared outside of the loop and a statement within the loop appends a value to the accumulator. 101 | 102 | 103 | accumulator = 0 104 | for num in range(1, 3): 105 | accumulator += num 106 | 107 | print(accumulator) # 3 108 | ## Augmented Assignment Operators 109 | | **Operator** | **Example Usage** | **Equivalent To** | 110 | | ------------ | ----------------- | ----------------- | 111 | | `+=` | `x += 5` | `x = x + 5` | 112 | | `-=` | `x -= 2` | `x = x - 2` | 113 | | `*=` | `x *= 10` | `x = x * 10` | 114 | | `/=` | `a /= b` | `a = a / b` | 115 | | `%=` | `c %= 3` | `c = c % 3` | 116 | 117 | # 4.5 Sentinels 118 | 119 | A *sentinel* is a special value that marks the end of a sequence of values. When a program reads the sentinel value, it knows it has reached the end of the sequence, so the loop terminates. A sentinel must be distinctive enough that it will not be mistaken as a regular value in the sequence. 120 | 121 | 122 | # 4.6 Input Validation Loops 123 | 124 | Input validation is the process of inspecting data that has been input to a program, to make sure it is valid before it is used in a computation. We have to instruct the computer on what bad data is. 125 | 126 | A programmer should design their programs in such a way that bad input is never accepted. 127 | 128 | A *priming read* is when input is acquired before the loop to be tested. 129 | 130 | 131 | score = int(input('Enter test score: ')) 132 | 133 | while score < 0 or score > 100: 134 | print('Error: score cannot be negative') 135 | score = int(input('Enter test score: ')) 136 | 137 | The above loop will continue to iterate until a test score between 1 and 100 is provided. 138 | 139 | # 4.7 Nested Loops 140 | 141 | A loop that is inside another loop is *nested.* 142 | 143 | An example would be a clock: 144 | 145 | for hours in range(24): 146 | for minutes in range(60): 147 | for seconds in range(60): 148 | print(hours, minutes, seconds, sep=':') 149 | 150 | Things to know about nested loops: 151 | 152 | - An inner loop goes through all of its iterations for every single iteration of an outer loop. 153 | - Inner loops complete their iterations faster than outer loops. 154 | - To get the total number of iterations of a nested loop, multiply the number of iterations of all the loops. 155 | 156 | 157 | 158 | 159 | -------------------------------------------------------------------------------- /notes/06.md: -------------------------------------------------------------------------------- 1 | # Chapter 6: Files and Exceptions 2 | 3 | # 6.1 Introduction to File Input and Output 4 | 5 | When a program needs to save data for later use, it writes the data in a file. The data can be read from the file at a later time. 6 | 7 | When data is written to a file, it is copied from a variable in RAM to the file. When data is read from a file, it is copied from the file into RAM and referenced by a variable. 8 | 9 | Three steps taken when a file is used by a program: 10 | 11 | 1. *Open the file:* Opening an output file allows the program to write to it. Opening an input file allows the program to read from it. 12 | 2. *Process the file:* Data is either written or read from the file. 13 | 3. *Close the file:* When processing is complete, the file must be closed. 14 | 15 | 16 | ## Types of Files 17 | 18 | Programming languages usually provide both *sequential* and *direct* access: 19 | 20 | - *Sequential:* All preceding data must be read before you read sequential data. 21 | - *Direct:* Any piece of data in the file can be read without reading data that comes before it. 22 | ## Filenames and File Objects 23 | 24 | Files contain extensions which describe the data that lie within (e.g., .docx, .txt, etc.). In order for a program to work with a file on the computer’s disk, it must create a file object in memory. Such an object allows the program to work with the file. In a program, a variable references the file object, which is used by the program to carry out operations. 25 | 26 | ## Opening a File 27 | 28 | To open a file in Python, use the `open()` function: 29 | 30 | 31 | file_variable = open(filename, mode) 32 | 33 | In the above, `file_variable` is the variable that references the file object. The `filename` is the name of the file and `mode` specifies the mode (reading, writing, etc.). 34 | 35 | Here are a few modes: 36 | 37 | 38 | | **Mode** | **Description** | 39 | | -------- | ---------------------------------------------------------------------------------------------------------------- | 40 | | r | Read only. | 41 | | w | Write to the file. If file exists, erase contents. Else, create the file. | 42 | | a | Write to the file. All data written to the file will be appended to its end. If file doesn’t exist, create it. | 43 | 44 | open('customers.txt', 'r') # Read from a text file 45 | open('sales.txt', 'w') # Create a new txt file and write data to it 46 | ## Specifying the Location of a File 47 | 48 | To open a file in a different location, specify a path. If the path is a string literal, prefix it with `r`, which means *raw string*. Python does not interpret escaped characters in raw strings. 49 | 50 | ## Writing Data to a File 51 | 52 | File objects have a method `write` that can be used to write data to a file. 53 | 54 | 55 | file_variable.write(string) 56 | 57 | After writing to a file, it should be closed. This is so unsaved data that is in a buffer (in memory) can be written to the file. 58 | 59 | 60 | file_variable.close() 61 | 62 | 63 | ## Reading Data from a File 64 | 65 | If you opened a file using `r` mode, you can read from it using the `read()` method. 66 | 67 | 68 | file_variable.read() 69 | 70 | Don’t forget to close after reading the file. 71 | 72 | 73 | file_variable.close() 74 | 75 | To read a line of a file, use `readline()` 76 | 77 | 78 | file_variable.readline() 79 | file_variable.close() 80 | 81 | 82 | ## Concatenating a Newline to a String 83 | 84 | When a program writes data that has been entered by the user to a file, it is usually necessary to concatenate a `\n` escape sequence to the data before writing it, which ensures the data is on a new line. 85 | 86 | ## Reading a String and Stripping the Newline from It 87 | 88 | Strings have a `rstrip()` method used to strip specific characters from the end of a string. 89 | 90 | 91 | name = 'John\n' 92 | name = name.rstrip('\n') 93 | 94 | 95 | ## Appending Data to an Existing File 96 | 97 | Use the `a` mode to open an output file in *append mode* which means: 98 | 99 | - If the file exists, it will **not** be erased. If the file does not exists, it will be created. 100 | - When data is written, it is written at the end of the file. 101 | 102 | 103 | ## Writing and Reading Numeric Data 104 | 105 | Numbers need to be converted to string in order to be written to a file. Simply use the `str()` method to convert a number to a string. 106 | 107 | 108 | outfile.write(str(55) + '\n') 109 | 110 | To read the numbers from a file, simply convert each line to an integer using `int()`. 111 | 112 | 113 | num = int(infile.readline()) 114 | 115 | 116 | # 6.2 Using Loops to Process Files 117 | ## Reading a File with a Loop and Detecting the End of the File 118 | 119 | To determine the end of a file, check to see if `readline()` returns an empty string. 120 | 121 | 122 | # Open a file 123 | infile = open('file.txt', 'r') 124 | 125 | # Check first line before 126 | # entering loop to see if it 127 | # is empty 128 | line = infile.readline() 129 | 130 | while line != '': 131 | # Do processing 132 | 133 | # Read next line 134 | line = infile.readline() 135 | 136 | 137 | ## Using Python’s `for` Loop to Read Lines 138 | 139 | A `for` loop can be used to read the contents from a file without being told when to stop. 140 | 141 | 142 | for variable in file_object: 143 | statement 144 | statement 145 | etc. 146 | 147 | Here, `variable` will reference a line within a file. 148 | 149 | # 6.3 Processing Records 150 | 151 | The data that is stored in a file is frequently organized in records. A record is a complete set of data about an item, and a field is an individual piece of data within a record. 152 | 153 | ## Modifying Records 154 | 155 | To modify a record in a sequential file, you must create a second temporary file. You copy all of the original file’s records to the temporary file, but when you get to the record that is to be modified, you do not write its old contents to the temporary file. Instead, you write its new modified values to the temporary file. Then, you finish copying any remaining records from the original file to the temporary file. 156 | 157 | The temporary file then takes place of the original file. You delete the original file and rename the temporary file. 158 | 159 | To rename and remove files, you must import the `os` module. 160 | 161 | 162 | from os import remove, rename 163 | remove('original.txt') 164 | rename('temp.txt', 'original.txt') 165 | ## Deleting Records 166 | 167 | To delete records from a sequential file, you must create a temporary file. You copy all of the original records to the temporary file except for the one that should be deleted. The temporary file then takes place of the original. 168 | 169 | # 6.4 Exceptions 170 | 171 | An *exception* is an error that occurs while a program is running, causing the program to abruptly halt. They can be handled using a `try/except` statement. 172 | 173 | For instance, dividing by 0 raises the following exception: 174 | 175 | 176 | Traceback (most recent call last): 177 | File "20.py", line 13, in 178 | main() 179 | File "20.py", line 9, in main 180 | result = num1 / num2 181 | ZeroDivisionError: division by zero 182 | 183 | One way to handle raised exceptions is an `if` statement: 184 | 185 | 186 | num1 = 5 187 | num2 = 0 188 | 189 | if num2 != 0: 190 | result = num1 / num2 191 | print(num1, 'divided by', num2, 'is', result) 192 | else: 193 | print('Cannot divide by 0.') 194 | 195 | Some exceptions cannot be avoided, though. For instance, an exception is raised if you try to convert a string (e.g., ‘forty’) to an integer: 196 | 197 | 198 | hours = int(input('How many hours did you work? ')) 199 | ValueError: invalid literal for int() with base 10: 'forty' 200 | 201 | A better way of handling exceptions is using an *exception handler*: 202 | 203 | 204 | try: 205 | statement 206 | statement 207 | etc. 208 | except ExceptionName: 209 | statement 210 | statement 211 | etc. 212 | 213 | The code block in `try` is called the *try suite*. Statements within it have the potential of raising an exception. After, the *except clause* begins. The `ExceptionName` is optional. 214 | 215 | When the `try/except` statement executes, the statements in the try suite begin to execute. The following happens next: 216 | 217 | - If a statement within the try suit raises an exception specified by the `ExceptionName` in an except clause, the appropriate except clause executes and control is transferred to statements below the `try/except` statement. 218 | - If a statement in the try suite raises an exception that is **not** specified by `ExceptionName` in an except clause, the program halts with a traceback error message. 219 | - If no statements in the `try/except` statement raise exceptions, the subsequent except clauses are skipped and control is transferred to statements below the `try/catch` statement. 220 | ## Handling Multiple Exceptions 221 | 222 | Sometimes code within the try suite has the potential of throwing many types of exceptions. For example, consider the following code that tries to read from a `sales_data.txt` file: 223 | 224 | 225 | 226 | total = 0.0 227 | 228 | filename = 'sales_data.txt' 229 | 230 | try: 231 | infile = open(filename, 'r') 232 | 233 | for line in infile: 234 | amount = float(line) 235 | total += amount 236 | 237 | infile.close() 238 | 239 | print('Total:', format(total, ',.2f')) 240 | 241 | except IOError: 242 | print(f'Failed to read file {filename}.') 243 | except ValueError: 244 | print(f'Non-numeric data found in file {filename}.') 245 | except: 246 | print('An error occurred.') 247 | 248 | Notice the multiple `except` clauses. 249 | 250 | ## Using One `except` Clause to Catch All Exceptions 251 | 252 | To catch all exceptions, simply omit the `ExceptionName` like so: 253 | 254 | 255 | try: 256 | # code that can raise an exception... 257 | except: 258 | print('Something went wrong.') # Generic exception clause 259 | 260 | 261 | ## Displaying an Exception’s Default Error Message 262 | 263 | When an exception is thrown, an object known as an *exception object* is created in memory. The object contains a default error message. You can optionally assign the the exception object to a variable like so and print it: 264 | 265 | 266 | except ValueError as err: 267 | print(err) 268 | 269 | If you want to use just one except clause, but access the exception object, you can specify `Exception` as the type: 270 | 271 | 272 | except Exception as err: 273 | print(err) 274 | 275 | 276 | ## The `else` Clause 277 | 278 | You can add an optional `else` clause after the except clauses. The statements within the `else` clause are executed only if no exceptions were raised. 279 | 280 | 281 | try: 282 | statement 283 | statement 284 | etc. 285 | except: 286 | statement 287 | statement 288 | etc. 289 | else: 290 | statement 291 | statement 292 | etc. 293 | 294 | 295 | ## The `finally` Clause 296 | 297 | You can add an optional `finally` clause after the except clause. The statements within the `finally` clause are executed whether an exception is raised or not. This is commonly used for cleanup (e.g., closing a file, etc.) 298 | 299 | 300 | try: 301 | statement 302 | statement 303 | etc. 304 | except: 305 | statement 306 | statement 307 | etc. 308 | finally: 309 | statement 310 | statement 311 | etc. 312 | 313 | -------------------------------------------------------------------------------- /notes/07.md: -------------------------------------------------------------------------------- 1 | # Chapter 7: Lists and Tuples 2 | 3 | # 7.1 Sequences 4 | 5 | A *sequence* is an object that holds multiple items of data, stored one after the other. You can perform operations on a sequence to examine and manipulate the contents within. 6 | 7 | Lists and Tuples are two types of sequence objects in Python. The difference is simple: a tuple is immutable, which means that once it is created, the contents cannot change. 8 | 9 | # 7.2 Introduction to Lists 10 | 11 | A *list* is an object that contains multiple data items and is mutable. Items can be manipulated by way of indexing, slicing, etc. 12 | 13 | Here is a simple examples of *elements* in a list: 14 | 15 | 16 | even_numbers = [2, 4, 6, 8, 10] 17 | 18 | Lists can store multiple data types: 19 | 20 | 21 | info = ['Matt', 21, 15000.00] 22 | 23 | Python has a built-in `list` function that can convert certain types of objects to lists. For instance, you can convert the iterable returned by `range` like so: 24 | 25 | 26 | my_list = list(range(1, 5)) 27 | ## The Repetition Operator 28 | 29 | The *repetition operator* makes multiple copies of a list and joins them all together. An example: 30 | 31 | >>> numbers = [0] * 5 32 | >>> print(numbers) 33 | >>> [0, 0, 0, 0, 0] 34 | ## Iterating over a List with the `for` Loop 35 | 36 | You can iterate over a list using the `for` loop. Here is an example: 37 | 38 | 39 | numbers = [99, 100, 101, 102] 40 | for n in numbers: 41 | print(n) 42 | 43 | The above produces the following output: 44 | 45 | 99 46 | 100 47 | 101 48 | 102 49 | ## Indexing 50 | 51 | You can access individual items in a list with an *index.* The index value starts at 0, goes to 1, and so on. 52 | 53 | 54 | my_list = [25, 50, 75] 55 | print(my_list[0], my_list[1], my_list[2]) # 25, 50, 75 56 | 57 | You can use negative indices to refer to an element’s position relative to the end of a list. 58 | 59 | 60 | my_list = [3, 5, 7, 9] 61 | print(my_list[-1], my_list[-2], my_list[-3], my_list[-4]) # 9, 7, 5, 3 62 | 63 | An `IndexError` exception is raised when you use an invalid index. 64 | 65 | ## The `len` Function 66 | 67 | `len` returns the length of a sequence, such as a list. An example: 68 | 69 | 70 | my_list = [5, 6, 7, 8] 71 | print(len(my_list)) # 4 72 | ## Lists are Mutable 73 | 74 | Lists are *mutable,* meaning their elements can be changed. For instance, you can assign an index value to an element like so: 75 | 76 | 77 | my_list = [55, 89] 78 | my_list[1] = 90 79 | print(my_list) # 55, 90 80 | 81 | When doing the above, you must use a valid index for an existing element or an `IndexError` exception will occur. 82 | 83 | 84 | my_list = [9, 8] 85 | my_list[2] = 6 # Exception! 86 | 87 | If you want to fill a list by way of an index value, you must create the list with the desired size. 88 | 89 | 90 | numbers = [0] * 5 # A list that holds 5 items 91 | 92 | index = 0 93 | while index < len(numbers): 94 | numbers[index] = 100 + index 95 | index += 1 96 | 97 | ## Concatenating Lists 98 | 99 | Concatenate two lists with the `+` operator: 100 | 101 | 102 | [1, 3, 5] + [7, 9, 11] 103 | 104 | You can also concatenate one list to another using the `+=` operator: 105 | 106 | 107 | list1 = [1, 3, 5] 108 | list2 = [7, 9, 11] 109 | list1 += list2 110 | 111 | 112 | # 7.3 List Slicing 113 | 114 | A slicing expression selects a range of elements from a sequence. A *slice* is a span of items that are taken from a sequence. 115 | 116 | To get a slice, you use the following format: 117 | 118 | 119 | list_name[start : end] 120 | 121 | In general, *start* is the index of the first element in the slice, and *end* is the index marking the end of the slice. The expression returns a list containing a copy of the elements from *start* up to (but not including) *end.* 122 | 123 | For instance, say we have this list: 124 | 125 | 126 | days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] 127 | 128 | To get Tuesday-Thursday, we can do this: 129 | 130 | 131 | mid_days = [2:5] # ['Tuesday', 'Wednesday', 'Thursday'] 132 | 133 | If you leave out the *start* index in a slicing expression, Python uses 0 as the starting index. 134 | 135 | 136 | nums = [5, 10, 15, 20, 25] 137 | print(nums[:3]) # [5, 10, 15] 138 | 139 | If you leave out the *end* index in a slicing expression, Python uses the length of the list minus one as the ending index. 140 | 141 | 142 | nums = [10, 20, 30, 45, 67] 143 | print(nums[1:]) # [20, 30, 45, 67] 144 | 145 | If you leave out both the *start* and *end*, you get a copy of a list. 146 | 147 | 148 | nums = [9, 5, 6, 2] 149 | print(nums[:]) [9, 5, 6, 2] 150 | 151 | You can also include a *step value* in a slice. 152 | 153 | 154 | my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 155 | print(numbers[1:8:2]) # [2, 4, 6, 8] 156 | 157 | You can also use negative index values in slicing expressions. 158 | 159 | 160 | my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 161 | print(numbers[-6:]) # [5, 6, 7, 8, 9, 10] 162 | 163 | Invalid indices don’t cause exceptions. 164 | 165 | - If the *end* index specifies a position beyond the end of the list, Python will use the length of the list instead. 166 | - If the *start* index specifies a position before the beginning of the list, Python will use 0 instead. 167 | - If the *start* index is greater than the *end* index, the slicing expression will return an empty list. 168 | # 7.4 Finding Items in Lists with the `in` Operator 169 | 170 | You can use the `in` operator to determine whether an item is contained in a list. 171 | 172 | 173 | item in list 174 | 175 | The above expression returns `True` if `item` is an element in `list`, otherwise, `False`. 176 | 177 | # 7.5 List Methods and Useful Built-in Functions 178 | 179 | Lists have methods to allow you to add and remove elements, change the order of elements, etc. 180 | 181 | ## The `append` Method 182 | append(item) 183 | 184 | Adds an element to the end of a list. 185 | 186 | ## The `index` Method 187 | index(item) 188 | 189 | Returns the index of the first element whose value is equal to the argument provided. If the item is not found, a *ValueError* exception is raised. 190 | 191 | ## The `insert` Method 192 | insert(index, item) 193 | 194 | Inserts `item` into the list at the specified `index`. When an item is inserted into a list, the list expands in size to accommodate. The item that was previously at the specified index, and all the items after it, are shifted by one position toward the end of the list. No exceptions will occur if you specify an invalid index. If you specify an index beyond the end of the list, the item will be added to the end of the list. If you use a negative index that specifies an invalid position, the item will be inserted at the beginning of the list. 195 | 196 | ## The `sort` Method 197 | nums = [3,2,1] 198 | nums.sort() 199 | print(nums) # [1, 2, 3] 200 | 201 | strs = ['charlie', 'alpha', 'bravo'] 202 | strs.sort() 203 | print(strs) # ['alpha', 'bravo', 'charlie'] 204 | 205 | Sorts the items in the list so they appear in ascending order. 206 | 207 | ## The `remove` Method 208 | remove(item) 209 | 210 | Removes the first occurrence of item from the list. A *ValueError* exception is raised if item is not found in the list. 211 | 212 | ## The `reverse` Method 213 | nums = [5, 6, 7] 214 | nums.reverse() 215 | print(nums) # [7, 6, 5] 216 | 217 | Reverses the order of items in the list. 218 | 219 | ## The `del` Statement 220 | 221 | Use the `del` statement to remove an item at a specific index. 222 | 223 | 224 | my_list = [1, 3, 5] 225 | del my_list[0] 226 | print(my_list) [3, 5] 227 | 228 | 229 | ## The `min` and `max` Functions 230 | 231 | `min` accepts a list as an argument and returns the item that has the lowest value in the sequence. 232 | 233 | 234 | print(min([66, 102, 4, 815])) # 4 235 | 236 | `max` is just like `min`, however, it returns the item that has the *highest* value in the sequence. 237 | 238 | 239 | print(max(['bravo', 'zulu', 'alpha'])) # 'zulu' 240 | # 7.6 Copying Lists 241 | 242 | To make a copy of a list, you must copy the list’s elements. 243 | 244 | Simply assigning one variable an existing list doesn’t copy it. It merely provides the variable a reference to the list: 245 | 246 | 247 | list1 = [1, 2, 3, 4] 248 | lis2 = list1 249 | list1.remove(2) 250 | print(list1) # [1, 3, 4] 251 | print(list2) # [1, 3, 4] 252 | 253 | As demonstrated above, removing an item from the list affects both variables. 254 | 255 | You can make a shallow copy of a list by omitting the *start* and *end* operands in a slice like so: 256 | 257 | list1 = [6, 7, 8] 258 | list2 = list1[:] # shallow copy of list1 259 | list1.remove(8) 260 | print(list2) # [6, 7, 8] (not affected by removal) 261 | 262 | Or you can copy a list with a loop: 263 | 264 | 265 | list1 = [1, 2, 3, 4] 266 | list2 = [] 267 | for item in list1: 268 | list2.append(item) 269 | # 7.7 Processing Lists 270 | ## Working with Lists and Files 271 | 272 | Saving the contents of a list to a file is easy. Python file objects have a method named `writelines` that writes an entire list to a file. 273 | 274 | 275 | outfile = open('cities.txt', 'w') 276 | outfile.writelines(['Chicago', 'Dallas', 'New York']) 277 | outfile.close() 278 | 279 | To add a new line after each element, use a for-loop instead of `writelines`: 280 | 281 | 282 | for city in cities: 283 | outfile.write(city + '\n') 284 | 285 | File objects in Python have a method named `readlines` that returns a file’s contents as a list of strings. Each line in the file will be an item in the list. The items in the list will include their terminating newline character, which in many cases will need to be stripped. 286 | 287 | 288 | # removing terminating new line character 289 | index = 0 290 | while index < len(cities): 291 | cities[index] = cities[index].rstrip('\n') 292 | index += 1 293 | # 7.8 Two-Dimensional Lists 294 | 295 | A *two-dimensional list* is a list that has other lists as its elements. 296 | 297 | 298 | teams = [['Joe', 'Cameron'], ['Matt', 'Ian']] 299 | 300 | Lists of lists are also known as *nested lists*. The lists within a list are thought of as rows, and each of the elements within as columns. 301 | 302 | 303 | scores = [[55, 67, 13], [99, 43, 27], [50, 100, 75]] 304 | print(scores[0][0]) # 55 305 | print(scores[1][1]) # 43 306 | print(scores[2][2]) # 75 307 | # 7.9 Tuples 308 | 309 | A *tuple* is an **immutable** sequence, which means its contents **cannot change**. 310 | 311 | An example of a tuple: 312 | 313 | 314 | my_tuple = ('Matt', 21, 50000.00) 315 | 316 | Tuples support all the same operations as lists (excluding those that change contents). Tuples support the following: 317 | 318 | - Subscript indexing (retrieval only) 319 | - Methods such as `index` 320 | - Built-in functions such as `len`, `min`, and `max` 321 | - Slicing expressions 322 | - The `in` operator 323 | - The `+` and `*` operators 324 | 325 | Tuples **do not support** methods like `append, remove, insert, reverse, sort`. 326 | 327 | ## What’s the Point? 328 | 329 | One reason tuples exist is performance. Processing a tuple is **faster than** processing a list, so tuples are good for processing large data sets. Another reason is that the contents of a tuple are safe since the sequence is **immutable**. 330 | 331 | ## Converting Between Lists and Tuples 332 | 333 | You can use the built-in `list` function to convert a tuple to a list and the built-in `tuple()` function to convert a list to a tuple. 334 | 335 | 336 | number_tuple = (5, 10, 15) 337 | number_list = list(number_tuple) 338 | 339 | str_list = ['hello', 'world'] 340 | str_tuple = tuple(str_list) 341 | 342 | 343 | -------------------------------------------------------------------------------- /notes/11.md: -------------------------------------------------------------------------------- 1 | # Chapter 11: Inheritance 2 | 3 | # 11.1 Introduction to Inheritance 4 | 5 | Inheritance allows a new class to extend an existing class. This new class inherits the members of the class it extends. 6 | 7 | ## Generalization and Specialization 8 | 9 | In the real world, you can find many objects that are specialized versions of other more general objects. For example, the term “insect” describes a general type of creature with various characteristics. Bees and grasshoppers are insects, therefore, they have all the general characteristics of an insect. However, they have the ability to have characteristics of their own. 10 | 11 | ## Inheritance and the “Is a” Relationship 12 | 13 | When one object is a specialized version of another object, there is a “is a” relationship between them. Some examples: 14 | 15 | - A poodle **is a** dog. 16 | - A car **is a** vehicle. 17 | - A flower **is a** plant. 18 | - A rectangle **is a** shape. 19 | 20 | Inheritance involves a superclass and a subclass. The *superclass* is the general class and the *subclass* is the specialized class. The subclass inherits attributes and methods from the superclass version without any of them having to be rewritten. 21 | 22 | Very simple example of inheritance: 23 | 24 | 25 | class Automobile(): 26 | def __init__(self, make, model, mileage, price): 27 | self.__make = make 28 | self.__model = model 29 | self.__mileage = mileage 30 | self.__price = price 31 | 32 | class Car(Automobile): 33 | def __init__(self, make, model, mileage, price, doors): 34 | Automobile.__init__(self, make, model, mileage, price) 35 | 36 | Here, `Automobile` is the *superclass* of `Car` as indicated by: 37 | 38 | 39 | class Car(Automobile): 40 | 41 | When we inherit from a parent, we must call it’s initialization method and pass `self`: 42 | 43 | 44 | Parent.__init__(self, ...) 45 | 46 | Now, `Car` has access to all attributes and methods declared in `Automobile` and can make its own if needed. 47 | 48 | # 11.2 Polymorphism 49 | 50 | *Polymorphism* allows subclasses to have methods with the same names as methods in their superclasses. It gives the ability for a program to call the correct method depending on the type of object that is used to call it. 51 | 52 | 53 | # animals.py 54 | class Mammal: 55 | 56 | def __init__(self, species): 57 | self.__species = species 58 | 59 | def show_species(self): 60 | print(f'I am a {self.species}.') 61 | 62 | def make_sound(self): 63 | print('Grrrrr') 64 | 65 | class Dog(Mammal): 66 | 67 | def __init__(self): 68 | Mammal.__init__(self, 'Dog') 69 | 70 | def make_sound(self): 71 | print('Woof! Woof!') 72 | 73 | # demo.py 74 | cow = animals.Mammal('Cow') 75 | print(cow.show_species()) # I am a cow. 76 | 77 | dog = animals.Dog() 78 | print(dog.show_species()) # I am a dog. 79 | 80 | 81 | ## The `isinstance` Function 82 | 83 | Polymorphism provides great flexibility. For example, consider the function: 84 | 85 | 86 | def show_mammal_info(creature): 87 | creature.show_species() 88 | creature.make_sound() 89 | 90 | We can pass any object to the function so long as it has `show_species` and `make_sound` methods. 91 | 92 | But… what happens if we pass an object to `show_mammal_info` that isn’t a mammal? 93 | 94 | 95 | show_mammal_info('I am a string') 96 | 97 | def show_mammal_info(creature): 98 | creature.show_species() 99 | creature.make_sound() 100 | 101 | Since a string literal doesn’t have such methods, the following error is thrown: 102 | 103 | 104 | AttributeError: 'str' object has no attribute 'show_species' 105 | 106 | This can be prevented with the built-in `isinstance(object, ClassName)` function. 107 | 108 | --------------------------------------------------------------------------------