├── README.md
└── StartOutWithPython
├── Chapter02
├── ProgrammingExercises
│ ├── distance_traveled.py
│ ├── land_calculation.py
│ ├── personal_information.py
│ ├── sales_prediction.py
│ ├── sales_tax.py
│ └── total_purchase.py
└── output.py
├── Chapter03
├── Examples
│ ├── auto_repair_payroll.py
│ ├── example.py
│ ├── grader.py
│ ├── loan_qualifier.py
│ ├── password.py
│ ├── sort_names.py
│ └── test_average.py
└── ProgrammingExercises
│ ├── age_classifier.py
│ ├── area_rectangles.py
│ ├── day_of_the_week.py
│ ├── february_days.py
│ ├── roman_numerals.py
│ └── time_calculator.py
├── Chapter04
└── ProgrammingExercises
│ ├── average_rainfall.py
│ ├── celsius_farhenheit.py
│ ├── distance_traveled.py
│ ├── factorial.py
│ ├── ocean_level.py
│ ├── pattern.py
│ ├── pennies_for_pay.py
│ ├── populaton.py
│ ├── sum_of_numbers.py
│ └── try.py
├── Chapter05
├── ProgrammingExercises
│ ├── automobile_costs.py
│ ├── calories_from_fats_carbohydrates.py
│ ├── how_much_insurance.py
│ ├── kilometer_converter.py
│ ├── list_prime.py
│ ├── math_quiz.py
│ ├── maximum.py
│ ├── paint_job_estimator.py
│ ├── prime_numbers.py
│ ├── property_tax.py
│ ├── rock_paper_scissors.py
│ ├── sales_tax.py
│ └── test_average.py
├── __pycache__
│ ├── circle.cpython-37.pyc
│ └── rectangle.cpython-37.pyc
├── circle.py
├── example.py
├── geometry.py
└── rectangle.py
├── Chapter06
├── Examples
│ ├── biodata.py
│ ├── biodata.txt
│ ├── biodata_line.py
│ ├── employees.txt
│ ├── exm.py
│ ├── file_read.py
│ ├── file_write.py
│ ├── friends.txt
│ ├── line_read.py
│ ├── numbers.txt
│ ├── philosophers.txt
│ ├── read_bio.py
│ ├── read_emp_records.py
│ ├── read_numbers.py
│ ├── read_running_times.py
│ ├── read_sales.py
│ ├── read_sales2.py
│ ├── sales.txt
│ ├── sales_data.txt
│ ├── sales_report.py
│ ├── sales_report1.py
│ ├── sales_report2.py
│ ├── sales_report4.py
│ ├── save_emp_records.py
│ ├── save_running_times.py
│ ├── strip_newline.py
│ ├── video_times.txt
│ ├── write_names.py
│ ├── write_numbers.py
│ └── write_sales.py
└── ProgrammingExercises
│ ├── average_of_numbers.py
│ ├── average_steps_taken.py
│ ├── exception_handling.py
│ ├── file_display.py
│ ├── file_head_display.py
│ ├── golf.txt
│ ├── golf_scores.py
│ ├── golf_scores2.py
│ ├── index.html
│ ├── item_counter.py
│ ├── items_names.py
│ ├── line_numbers.py
│ ├── names.txt
│ ├── numbers.txt
│ ├── personal_webpage_generator.py
│ ├── random_number_file_reader.py
│ ├── random_number_file_writer.py
│ ├── random_numbers.txt
│ └── sum_of_numbers.py
├── Chapter07
├── Examples
│ ├── add_coffee_records.py
│ ├── cities.txt
│ ├── coffee.txt
│ ├── command.py
│ ├── delete_coffee_records.py
│ ├── display_file.py
│ ├── formatting.py
│ ├── in_list.py
│ ├── index_list.py
│ ├── insert_list.py
│ ├── list_append.py
│ ├── modify_coffee_records.py
│ ├── numberlist.txt
│ ├── pie_chart.py
│ ├── prime_numbers.py
│ ├── random_numbers.py
│ ├── read_coffee_records.py
│ ├── read_list.py
│ ├── read_number_list.py
│ ├── read_run_total.py
│ ├── remove_item.py
│ ├── sales_list.py
│ ├── search_coffee_records.py
│ ├── send.py
│ ├── tuples.py
│ ├── two_dimension_list.py
│ ├── write_list.py
│ ├── write_number_list.py
│ ├── write_run_total.py
│ └── writelines.py
└── ProgrammingExercises
│ ├── 1994_Weekly_Gas_Averages.txt
│ ├── 1994_weekly_gas_price.py
│ ├── 1994_weekly_gas_price2.py
│ ├── 8_ball_responses.txt
│ ├── BoyNames.txt
│ ├── GirlNames.txt
│ ├── USPopulation.txt
│ ├── WorldSeriesWinners.txt
│ ├── accounts.txt
│ ├── answers.txt
│ ├── bar_chart.py
│ ├── barrista_pay.py
│ ├── charge_acc1.py
│ ├── charge_acc2.py
│ ├── charge_account_validation.py
│ ├── charge_account_validation2.py
│ ├── charge_accounts.txt
│ ├── cities.txt
│ ├── drivers_licence_exam.py
│ ├── exm.py
│ ├── expense_piechart.py
│ ├── larger_than_n.py
│ ├── line_graph.py
│ ├── lo_shu_magic_square.py
│ ├── lottery_number_generator.py
│ ├── magic8_ball_file.py
│ ├── magic_8ball.py
│ ├── name_search.py
│ ├── number_analysis.py
│ ├── numberlist.txt
│ ├── population.txt
│ ├── population_data.py
│ ├── prime_number_generator.py
│ ├── rainfall_statistics.py
│ ├── random_functions.py
│ ├── read_pop_data.py
│ ├── sales_list.py
│ ├── total_sales.py
│ └── world_series_champions.py
├── Chapter08
├── Examples
│ ├── __pycache__
│ │ └── login.cpython-37.pyc
│ ├── generate_login.py
│ └── login.py
└── ProgrammingExercise
│ ├── GasPrices.txt
│ ├── HighToLow.txt
│ ├── LowToHigh.txt
│ ├── average_no_of_words.py
│ ├── character_analysis.py
│ ├── date_printer.py
│ ├── exm.py
│ ├── gas_highest.txt
│ ├── gas_lowest.txt
│ ├── gas_prices.py
│ ├── gas_prices2.py
│ ├── initials.py
│ ├── morse_code.py
│ ├── most_frequent.py
│ ├── mypbnumbers.txt
│ ├── pbnumbers.txt
│ ├── powerball_lottery.py
│ ├── powerball_lottery2.py
│ ├── sentence_capitalizer.py
│ ├── sumofdigits_inastring.py
│ ├── text.txt
│ ├── try.py
│ ├── try.txt
│ ├── trypb.py
│ ├── vowels_consonants.py
│ └── word_separator.py
├── Chapter09
├── Examples
│ ├── exm.py
│ ├── info.dat
│ ├── phonebook.dat
│ ├── pickle_objects.py
│ ├── set.py
│ └── unpickle_objects.py
└── ProgrammingExercises
│ ├── WorldSeries.txt
│ ├── WorldSeriesWinners.txt
│ ├── blackjack_simulation.py
│ ├── capital_quiz.py
│ ├── course_information.py
│ ├── decrypted_sampletext.txt
│ ├── encrypted_sampletext.txt
│ ├── exm.py
│ ├── file1.txt
│ ├── file2.txt
│ ├── file_analysis.py
│ ├── file_encrypt.py
│ ├── file_encrypt2.py
│ ├── index.txt
│ ├── name_email_address.py
│ ├── sampletext.txt
│ ├── text.txt
│ ├── word_frequency.py
│ ├── word_index.py
│ ├── words.txt
│ ├── world_series2.py
│ └── world_series_winners.py
├── Chapter10
├── Examples
│ ├── __pycache__
│ │ └── contact.cpython-37.pyc
│ ├── contact.py
│ ├── contact_manager.py
│ └── contacts.dat
└── ProgrammingExercises
│ ├── __pycache__
│ └── employee_class.cpython-37.pyc
│ ├── car_class.py
│ ├── dictionary.dat
│ ├── employee_class.py
│ ├── employee_management.py
│ ├── patient_charges.py
│ ├── personal_information.py
│ └── retail_item_class.py
├── Chapter11
├── Examples
│ ├── __pycache__
│ │ └── animals.cpython-37.pyc
│ ├── animals.py
│ ├── polymorphism_demo.py
│ ├── polymorphism_demo2.py
│ └── wrong_type.py
└── Programming Exercises
│ ├── __pycache__
│ └── employee_production_worker.cpython-37.pyc
│ ├── employee_production_supervisor_worker_demo.py
│ ├── employee_production_worker.py
│ ├── person_and_customer_classes.py
│ └── shift_supervisor_demo.py
└── Chapter12
├── Example
├── endless_recursion.py
├── recursive.py
└── try.py
└── Programming Exercise
├── largest_list_item.py
├── recursive_lines.py
├── recursive_list_sum.py
├── recursive_multiplication.py
├── recursive_power.py
└── recursive_printing.py
/README.md:
--------------------------------------------------------------------------------
1 | # Solutions
2 |
3 | This repo consists of solutions to all programming
4 | exercises in the Book Starting Out With Python By
5 | TONY GADDIS.
6 |
7 | There are 13 programming exercises in the book,
8 | but these solutions cover (Chapter02 through chapter12)
9 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/ProgrammingExercises/distance_traveled.py:
--------------------------------------------------------------------------------
1 | SPEED = 70
2 | T1 = 6
3 | T2 = 10
4 | T3 = 15
5 |
6 | distance1 = SPEED * T1
7 | distance2 = SPEED * T2
8 | distance3 = SPEED * T3
9 |
10 | print(f'Distance traveled in {T1} hours is {distance1} Miles\\Hr')
11 | print(f'Distance traveled in {T2} hours is {distance2} Miles\\Hr')
12 | print(f'Distance traveled in {T3} hours is {distance3} Miles\\Hr')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/ProgrammingExercises/land_calculation.py:
--------------------------------------------------------------------------------
1 | one_acre = 43560 # sq feet
2 |
3 | land_sqfeet = float(input('Enter the land\'s square feet: '))
4 | num_acres = land_sqfeet / one_acre
5 | print('The number of acres in the land is ',format(num_acres, '.2f'), 'acres')
6 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/ProgrammingExercises/personal_information.py:
--------------------------------------------------------------------------------
1 | # This program displays my personal information...
2 |
3 | print('''
4 | Name: Salami Tunde Muhamed
5 | Address: ILUPEJU Phase2, Opposite Mosebolan House Sabo Oyo.
6 | Oyo State Nigeria.
7 | 100001
8 | Telephone Number: 070-3321-6997
9 | College Major: ELECTRICAL/ ELECTRONICS ENGINEERING
10 | ''')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/ProgrammingExercises/sales_prediction.py:
--------------------------------------------------------------------------------
1 | PROFIT = 0.23
2 | total_sales = float(input('Enter the total sales: '))
3 | gain = PROFIT * total_sales
4 | annual_profit = total_sales + gain
5 | print('The annual profit is $', format(annual_profit, ',.2f'), sep='')
6 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/ProgrammingExercises/sales_tax.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter02/ProgrammingExercises/sales_tax.py
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/ProgrammingExercises/total_purchase.py:
--------------------------------------------------------------------------------
1 | TAX = 0.07
2 | total_sales = 0.0
3 | sub_total = 0.0
4 | total_tax = 0.0
5 |
6 |
7 | for item in range(5):
8 | print('Enter the price of item #', item+1, end='')
9 | price = float(input(': '))
10 | sales_tax = TAX * price
11 | sale = price - sales_tax
12 | sub_total += sale
13 | total_tax += sales_tax
14 | total_sales += sale
15 | print(f'Subtotal: {sub_total}')
16 | print()
17 | print(f'Total Tax: {total_tax}')
18 |
19 | print(f'Total Sales: ${total_sales}')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter02/output.py:
--------------------------------------------------------------------------------
1 | print('How many students wrote the test?', end='')
2 | num_students = int(input(': '))
3 | print('How many subjects was written by each student?', end='')
4 | num_test = int(input(': '))
5 |
6 |
7 | total_score = []
8 |
9 | for student in range(num_students):
10 | print(f'Student Number #{student+1}')
11 | print('=================')
12 |
13 | total = 0.0
14 | for test in range(num_test):
15 | score = int(input('Enter the score for test number #' + str(test+1) + ': '))
16 | total += score
17 |
18 | total_score.append(total)
19 | print()
20 |
21 | print(f'Total Score For All The {num_students} is {total_score}')
22 | print()
23 | for index, tot_score in enumerate(total_score):
24 | avg = tot_score / num_test
25 | print('Average Score Of Student Number #', index+1, 'is', format(avg, '.1f'))
26 | # print(f'Average Score Of Student Number #{index+1} is {avg}')
27 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/auto_repair_payroll.py:
--------------------------------------------------------------------------------
1 | BASE_HOURS = 40
2 | OT_MULTIPLIER = 1.5
3 |
4 | hours = float(input('Enter the number of hours worked: '))
5 | pay_rate = float(input('Enter the hourly pay rate: '))
6 |
7 | if hours > BASE_HOURS:
8 | overtime_hours = hours - BASE_HOURS
9 | overtime_pay = overtime_hours * pay_rate * OT_MULTIPLIER
10 | gross_pay = BASE_HOURS * pay_rate + overtime_pay
11 | print(f'Your Gross Pay is ${gross_pay:,.2f}')
12 |
13 |
14 | else:
15 | gross_pay = hours * pay_rate
16 | print(f'Your Gross Pay is ${gross_pay:,.2f}')
17 |
18 |
19 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/example.py:
--------------------------------------------------------------------------------
1 | name1 = 'Mary'
2 | name2 = 'Mark'
3 |
4 | if name1 > name2:
5 | print('Mary is greater than Mark.')
6 | else:
7 | print('Mark is greater than Mary.')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/grader.py:
--------------------------------------------------------------------------------
1 | # This program checks the grade of student and displays it on the screen
2 |
3 | A_GRADE = 90
4 | B_GRADE = 80
5 | C_GRADE = 70
6 | D_GRADE = 60
7 |
8 | student_score = int(input('Enter your score to check your grade: '))
9 |
10 | if student_score >= A_GRADE:
11 | print('Your Grade = A.')
12 | elif student_score >= B_GRADE and student_score < A_GRADE:
13 | print('Your Grade = B.')
14 | elif student_score >= C_GRADE and student_score < B_GRADE:
15 | print('Your Grade = C.')
16 | elif student_score >= D_GRADE and student_score < C_GRADE:
17 | print('Your Grade = D.')
18 | else:
19 | print('Your Grade is F.')
20 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/loan_qualifier.py:
--------------------------------------------------------------------------------
1 | # This program determines whether a bank customer qualifies for a loan
2 |
3 | MIN_SALARY = 30000
4 | MIN_YEAR = 2
5 |
6 | salary = float(input('Enter your annual salary: '))
7 | years_on_job = int(input('Enter the number of years employed: '))
8 |
9 | # if salary >= MIN_SALARY and years_on_job >= MIN_YEAR:
10 | # print('You qualify for the loan.')
11 | # else:
12 | # print('You do not qualify for the loan.')
13 |
14 | if salary >= MIN_SALARY:
15 | if years_on_job >= MIN_YEAR:
16 | print('You qualify for the loan.')
17 | else:
18 | print(f'You must have been on the job for at least {MIN_YEAR} years to qualify for the loan..')
19 |
20 | else:
21 | print(f'You must earn at least ${MIN_SALARY} to qualify for the loan.')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/password.py:
--------------------------------------------------------------------------------
1 | password = input('Enter the password: ')
2 |
3 | if password == 'prospero':
4 | print('Password accepted...')
5 | else:
6 | print('Sorry, that is the wrong password!!!')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/sort_names.py:
--------------------------------------------------------------------------------
1 | # This program compares string with the less than (<) operator
2 |
3 | name1 = input('Enter a name (last name first): ')
4 | name2 = input('Enter another name (last name first): ')
5 |
6 | print('Here are the names listed in alphabetical order...')
7 | print()
8 |
9 | if name1 < name2:
10 | print(name1)
11 | print(name2)
12 |
13 | else:
14 | print(name2)
15 | print(name1)
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/Examples/test_average.py:
--------------------------------------------------------------------------------
1 | # This program calculates the average score of students
2 | # that took three tests and congratulate them if the average
3 | # is greater than 95
4 |
5 | HIGH_SCORE = 95
6 |
7 | print('Calculate Your average test score: ')
8 | print('----------------------------------')
9 | print()
10 |
11 | test1 = float(input('Enter your first test score: '))
12 | test2 = float(input('Enter your second test score: '))
13 | test3 = float(input('Enter your third test score: '))
14 | print()
15 |
16 | average_score = (test1+test2+test3) / 3
17 | print(f'Your average score is {average_score:.1f}')
18 |
19 | if average_score >= HIGH_SCORE:
20 | print('Congratulations!!!.')
21 | print('Great average score...')
22 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/ProgrammingExercises/age_classifier.py:
--------------------------------------------------------------------------------
1 | # Write a program that asks the user to enter a person’s age. The
2 | # program should display a message indicating whether the person
3 | # is an infant, a child, a teenager, or an adult.
4 |
5 | print('Enter your age to check if you are\nan infant, a child, a teenager, or an adult', end='')
6 | age = int(input(': '))
7 |
8 | if age <= 1:
9 | print('You are an INFANT.')
10 | elif age >= 1 and age < 13:
11 | print('You are a CHILD.')
12 | elif age >= 13 and age < 20:
13 | print('You are a TEENAGER.')
14 | elif age >= 20:
15 | print('You are an ADULT.')
16 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/ProgrammingExercises/area_rectangles.py:
--------------------------------------------------------------------------------
1 | # This program calculates the area of two rectangles and check
2 | # which has the greatest area and if the areas are the same
3 |
4 | length1 = int(input('Enter the length of the first rectangle: '))
5 | width1 = int(input('Enter the width of the first rectangle: '))
6 |
7 | length2 = int(input('Enter the length of the second rectangle: '))
8 | width2 = int(input('Enter the width of the second rectangle: '))
9 |
10 | area1 = length1 * width1
11 | area2 = length2 * width2
12 |
13 | print(area1)
14 | print(area2)
15 | print()
16 |
17 | if area1 > area2:
18 | print('The First Rectangle Has The Largest Area.')
19 | elif area2 > area1:
20 | print('The Second Rectangle Has The Largest Area.')
21 | else:
22 | print('Both Rectangles Has Equal Areas.')
23 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/ProgrammingExercises/day_of_the_week.py:
--------------------------------------------------------------------------------
1 | # This program displays the day of the week corresponding
2 | # to the numbers 1 through 7
3 |
4 | MONDAY = 1
5 | TUESDAY = 2
6 | WEDNESDAY = 3
7 | THURSDAY = 4
8 | FRIDAY = 5
9 | SATURDAY = 6
10 | SUNDAY = 7
11 |
12 | for trial in range(3):
13 | user_input = int(input('Enter a value, (1 through 7): '))
14 | if user_input == MONDAY:
15 | print(f'{user_input} corresponds to Monday')
16 | elif user_input == TUESDAY:
17 | print(f'{user_input} corresponds to Tuesday')
18 | elif user_input == WEDNESDAY:
19 | print(f'{user_input} corresponds to Wednesday')
20 | elif user_input == THURSDAY:
21 | print(f'{user_input} corresponds toThursday')
22 | elif user_input == FRIDAY:
23 | print(f'{user_input} corresponds to Friday')
24 | elif user_input == SATURDAY:
25 | print(f'{user_input} corresponds to Saturday')
26 | elif user_input == SUNDAY:
27 | print(f'{user_input} corresponds to Sunday')
28 | else:
29 | print(f'Error!!! {user_input} out of range.')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/ProgrammingExercises/february_days.py:
--------------------------------------------------------------------------------
1 | print('Check whether the month February is 28 or 29 days\nif the year is leap...')
2 | print()
3 |
4 | year = int(input('Enter the year: '))
5 |
6 | if year % 100 == 0 and year % 400 == 0:
7 | print(f'In {year}, February has 29 days. Therefore {year} is LEAP')
8 | elif year % 100 != 0:
9 | if year % 4 == 0:
10 | print(f'In {year}, February has 29 days. Therefore {year} is LEAP')
11 | else:
12 | print(f'In {year}, February has 28 days. Therefore {year} is not LEAP')
13 | else:
14 | print(f'In {year}, February has 28 days. Therefore {year} is not LEAP')
15 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/ProgrammingExercises/roman_numerals.py:
--------------------------------------------------------------------------------
1 | print('Enter a number within the range of 1 through 10', end='')
2 | num = int(input(': '))
3 |
4 | if num == 1:
5 | print('Roman Numerals: i')
6 | if num == 2:
7 | print('Roman Numerals: ii')
8 | if num == 3:
9 | print('Roman Numerals: iii')
10 | elif num == 4:
11 | print('Roman Numerals: iv')
12 | elif num == 5:
13 | print('Roman Numerals: v')
14 | elif num == 6:
15 | print('Roman Numerals: vi')
16 | elif num == 7:
17 | print('Roman Numerals: vii')
18 | elif num == 8:
19 | print('Roman Numerals: viii')
20 | elif num == 9:
21 | print('Roman Numerals: ix')
22 | elif num == 10:
23 | print('Roman Numerals: x')
24 | else:
25 | print('Number out of range!!!')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter03/ProgrammingExercises/time_calculator.py:
--------------------------------------------------------------------------------
1 |
2 | BASE_SECONDS = 60
3 | BASE_HOURS = 3600
4 | BASE_DAYS = 86400
5 |
6 | print('Enter the number of seconds', end='')
7 | seconds = int(input(': '))
8 |
9 | if seconds == BASE_SECONDS:
10 | minutes_equi = seconds // BASE_SECONDS
11 | print(f'{seconds} seconds= {minutes_equi}mins')
12 |
13 | elif seconds > BASE_SECONDS and seconds < 3600:
14 | seconds_equi = seconds % BASE_SECONDS
15 | min_equi = (seconds - seconds_equi) / BASE_SECONDS
16 | print(f'{seconds} seconds= {min_equi}mins: {seconds_equi}secs')
17 |
18 | elif seconds >= 3600 and seconds < 86400:
19 | hours_remain = seconds % BASE_HOURS
20 | hours_original = seconds - hours_remain
21 | hours_equi = hours_original / BASE_HOURS # Hours Equivalent
22 |
23 | seconds_equi = hours_remain % BASE_SECONDS # seconds Equivalent
24 |
25 | min_remain = hours_remain - seconds_equi
26 |
27 | min_equi = min_remain / BASE_SECONDS # Minutes Equivalent
28 | print(f'{seconds} seconds= {hours_equi}hrs: {min_equi}mins: {seconds_equi}secs')
29 |
30 | elif seconds >= 86400:
31 | days = seconds % BASE_DAYS
32 | days_remain = seconds - days
33 | days_equi = days_remain / BASE_DAYS # Days Equivalent
34 |
35 | hours_remain = seconds % BASE_HOURS
36 | hours_original = seconds - hours_remain
37 | hours_equi = hours_original / BASE_HOURS # Hours Equivalent
38 |
39 | seconds_equi = hours_remain % BASE_SECONDS # seconds Equivalent
40 |
41 | min_remain = hours_remain - seconds_equi
42 |
43 | min_equi = min_remain / BASE_SECONDS # Minutes Equivalent
44 | print(f'{seconds} seconds= {days_equi}days: {hours_equi}hrs: {min_equi}mins: {seconds_equi}secs')
45 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/average_rainfall.py:
--------------------------------------------------------------------------------
1 | MONTHS = 12
2 | years = int(input('Enter the number of years: '))
3 |
4 | for yr in range(years):
5 | print('Year #', yr+1)
6 | print('========')
7 | print()
8 |
9 | total = 0.0
10 | for month in range(MONTHS):
11 | print('Enter the inches of rainfall for month #',month+1, end='')
12 | inch = float(input(': '))
13 | total += inch
14 | average = total / MONTHS
15 | print(f'Average Rainfall for year #{yr+1} is: {average:.1f}')
16 | print()
17 |
18 | months_total = years * MONTHS
19 | print(f'Total Number Of Months is: {months_total}')
20 |
21 |
22 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/celsius_farhenheit.py:
--------------------------------------------------------------------------------
1 | # This program displays the celsius and their fahrenheit equivalents
2 |
3 | LIMIT = 20
4 | print('Celsius\tFarhenheit')
5 |
6 | for C in range(1, LIMIT+1):
7 | F = 95 / (C + 32)
8 | print(C, '\t', format(F, '.1f'))
9 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/distance_traveled.py:
--------------------------------------------------------------------------------
1 | # This program displays the distance a car has traveled in miles
2 |
3 | LIMIT = 3
4 | SPEED = 40
5 |
6 | speed = float(input('Enter the speed in Miles\\Hour: '))
7 | hour = int(input('How many hours has the car taken: '))
8 |
9 | print('Hour\tDistance Traveled')
10 | print('=========================')
11 |
12 | for hr in range(1, hour+1):
13 | distance = hr * SPEED
14 | print(f'{hr}\t{distance}')
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/factorial.py:
--------------------------------------------------------------------------------
1 | # This program ask a user to enter a number
2 | # and find its factorial
3 |
4 | print('Finding Factorials Of Numbers...')
5 | num = 1
6 |
7 | number = int(input('Enter a number: '))
8 | for n in range(1, number+1):
9 | num = num * n
10 |
11 | print(f'The factorial of {number} is: {num}')
12 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/ocean_level.py:
--------------------------------------------------------------------------------
1 | MAX_YEAR = 25
2 | total = 0.0
3 | for yr in range(MAX_YEAR):
4 | total += 1.6
5 |
6 | print(f'In the next {MAX_YEAR} years, the ocean would have risen to {total:,.1f}mm.')
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/pattern.py:
--------------------------------------------------------------------------------
1 | for row in range(6):
2 | print('#', end='')
3 | for col in range(row):
4 | print(' ', end='')
5 |
6 | print('#')
7 | print()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/pennies_for_pay.py:
--------------------------------------------------------------------------------
1 | # Ask the user to enter the number of days
2 |
3 | num_days = int(input('Enter the number of days: '))
4 | print()
5 | total = 0.0
6 |
7 | print('Days\tSalary(Pennies)')
8 | print('=======================')
9 |
10 | for day in range(1, num_days+1):
11 | if day == 1:
12 | salary = day
13 |
14 | # Salaries for days 2 and above
15 | else:
16 | salary = salary * 2
17 | total += salary
18 |
19 | print(f'{day} \t {salary}')
20 |
21 | print()
22 |
23 | # Convert pennies to dollars by multiplying by 350
24 |
25 | total_salary_in_dollars = total / 350
26 | print(f'Total Salary for {num_days} days is: ${total_salary_in_dollars:,.1f}')
27 |
28 |
29 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/populaton.py:
--------------------------------------------------------------------------------
1 | start_num = float(input('Enter the starting number of organisms: '))
2 | daily_increase = float(input('Enter the daily population increase: '))
3 | days_to_multiply = int(input('Enter the number of days the organisms would be left to multiply: '))
4 |
5 | for day in range(1, days_to_multiply+1):
6 | if day == 1:
7 | pop = start_num
8 | else:
9 | pop = pop + (daily_increase * pop)
10 | print(f'{day} \t {pop}')
11 |
12 | # elif day == 2:
13 | # pop = pop + (daily_increase * pop)
14 | # elif day > 2:
15 | # pop = pop + (daily_increase * pop)
16 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/sum_of_numbers.py:
--------------------------------------------------------------------------------
1 | # Ask user to enter a series of positive numbers
2 | # The user should enter a negative number to signal the end of the series
3 |
4 |
5 | sum = 0.0
6 |
7 | print('Enter a series of +VE numbers or enter -VE numbers to cancel', end='')
8 |
9 | number = int(input(': '))
10 |
11 | while number > 0:
12 | sum += number
13 | print('Enter more positive numbers', end='')
14 |
15 | number = int(input(': '))
16 |
17 | print(f'Total: {sum}')
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter04/ProgrammingExercises/try.py:
--------------------------------------------------------------------------------
1 | start_num = float(input('Enter the starting number of organisms: '))
2 | daily_increase = float(input('Enter the daily population increase: '))
3 | days_to_multiply = int(input('Enter the number of days the organisms would be left to multiply: '))
4 |
5 | print()
6 | print('Day\tPopulation')
7 | print('==================')
8 |
9 | for day in range(1, days_to_multiply+1):
10 | if day == 1:
11 | pop = start_num
12 | else:
13 | pop = pop + (daily_increase * pop)
14 | print(f'{day} \t {pop}')
15 |
16 | # elif day == 2:
17 | # pop = pop + (daily_increase * pop)
18 | # elif day > 2:
19 | # pop = pop + (daily_increase * pop)
20 |
21 | def main():
22 | first_age = int(input('Enter your age: '))
23 | second_age = int(input('Enter your friend\'s age: ')
24 |
25 | total = sum(first_age, second_age)
26 | print('Together, you are', total, 'year\'s old')
27 |
28 |
29 | def sum(num1, num2):
30 | result = num1 + num2
31 | return result
32 |
33 | main()
34 |
35 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/automobile_costs.py:
--------------------------------------------------------------------------------
1 | # This program asks the user to enter the expenses cost
2 | # of operating his or her automobile
3 | # loan payment: insurance: gas: oil: tires: and maintenance
4 | # Then display the total monthly costs and the total annual costs
5 |
6 | YEAR_FACTOR = 12
7 |
8 |
9 | def main():
10 |
11 | monthly_costs = total_monthly_costs()
12 |
13 | print(f'The Total Monthly Costs Is: ${monthly_costs:,.2f}')
14 | print('The Total Annual Costs Is $', format(total_annual_costs(monthly_costs),' ,.2f'), sep='')
15 |
16 |
17 | def total_monthly_costs():
18 | loan = float(input('Enter the amount of total loan payed: '))
19 | insurance = float(input('Enter the amount of insurance incurred: '))
20 | gas = float(input('Enter the amount spent on gas: '))
21 | oil = float(input('Enter the amount spent on oil: '))
22 | tires = float(input('Enter the amount spent on tires: '))
23 | maintenance = float(input('Enter the amount of total maintenance: '))
24 | total_cost = loan + insurance + gas + oil + tires + maintenance
25 | return total_cost
26 |
27 |
28 | def total_annual_costs(costs):
29 | return costs * YEAR_FACTOR
30 |
31 |
32 | main()
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/calories_from_fats_carbohydrates.py:
--------------------------------------------------------------------------------
1 | # This program asks the user to enter the number of
2 | # fats gram and carbohydrates gram consume per day
3 | # and displays their calories on screen.
4 |
5 | def main():
6 | fat_gram = float(input('Enter the number of fat grams consumed per day: '))
7 | carbohydrates_gram = float(input('Enter the number of carbohydrates grams consumed per day: '))
8 |
9 | calories_from_fats = fatty(fat_gram)
10 | calories_from_carbohydrates = carbo(carbohydrates_gram)
11 |
12 | print(f'Calories From Fats Is: {calories_from_fats}Kcal')
13 | print(f'Calories From Carbohydrates Is: {calories_from_carbohydrates}Kcal')
14 |
15 |
16 |
17 | def fatty(fat):
18 | calories = fat * 9
19 | return calories
20 |
21 |
22 | def carbo(car):
23 | calories = car * 4
24 | return calories
25 |
26 |
27 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/how_much_insurance.py:
--------------------------------------------------------------------------------
1 | INSURANCE_PERCENT = 0.8
2 |
3 | def main():
4 | replacement_cost = float(input('Enter the replacement cost: '))
5 |
6 | insurance_cost = insurance(replacement_cost)
7 | print(f'Minimum Amount Of Insurance Is: ${insurance_cost:,.2f}')
8 |
9 | def insurance(cost):
10 | insurance_amount = cost * INSURANCE_PERCENT
11 | return insurance_amount
12 |
13 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/kilometer_converter.py:
--------------------------------------------------------------------------------
1 | def main():
2 | distance_km = float(input('Eneter a distance in km: '))
3 |
4 | kilo_converter(distance_km)
5 |
6 |
7 | def kilo_converter(distance):
8 | distance_miles = distance * 0.6214
9 | print(f'{distance}Km is equal to {distance_miles:,.2f}Miles.')
10 |
11 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/list_prime.py:
--------------------------------------------------------------------------------
1 | def main():
2 | number = int(input('Enter a number: '))
3 |
4 | prime = is_prime(number)
5 |
6 | if prime:
7 | print(number, 'is a prime number.')
8 | else:
9 | print(number, 'is not a prime number.')
10 |
11 |
12 |
13 | def is_prime():
14 | for test_num in range(1, 101):
15 |
16 | counter = 0
17 | for num in range(2, test_num):
18 | if test_num % num == 0:
19 | counter += 1
20 |
21 |
22 |
23 |
24 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/math_quiz.py:
--------------------------------------------------------------------------------
1 | # This is a math quiz program
2 |
3 | import random
4 |
5 | MIN = 1
6 | MAX = 1000
7 |
8 | def main():
9 | # Ask the user to enter two numbers and find their sum
10 | print()
11 | print('Welcome To Random Math Quiz')
12 | print('===========================')
13 | print('If you are sure of yourself, let get started then...')
14 | print()
15 | input('Press (Enter) to continue...')
16 |
17 | again = 'y'
18 | while again == 'y' or again == 'Y':
19 | num1 = random.randint(MIN, MAX)
20 | num2 = random.randint(MIN, MAX)
21 |
22 | print('Solve the following:', num1, '+' , num2, '=?')
23 |
24 | result = num1 + num2
25 |
26 | ans = int(input('Enter your answer: '))
27 | if ans == result:
28 | print('Congratulations!!! Your answer is correct.')
29 | else:
30 | print('Sorry, the correct answer is',result)
31 | print()
32 |
33 | again = input('Do you wanna perform more quiz? Enter [Y/n] to continue: ')
34 |
35 | print()
36 |
37 | print('Ooch!!! You are leaving? ')
38 | print('We hope you\'ll be back again in the future to take more quizzes.')
39 |
40 |
41 | main()
42 |
43 |
44 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/maximum.py:
--------------------------------------------------------------------------------
1 | def maximum(num1, num2):
2 | if num1 > num2:
3 | return num1
4 | else:
5 | return num2
6 |
7 | print('The maximum number is:', maximum(25, 35))
8 |
9 | maxim = [10, 20, 30, 40, 70, 100]
10 | print(max(maxim))
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/paint_job_estimator.py:
--------------------------------------------------------------------------------
1 | # For every 112 square feet of wall space, 1 gallon of paint and 8 hours
2 | # of labor is required and charges is $35 per hour
3 |
4 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/prime_numbers.py:
--------------------------------------------------------------------------------
1 | def main():
2 | number = int(input('Enter a number: '))
3 |
4 | prime = is_prime(number)
5 |
6 | if prime:
7 | print(number, 'is a prime number.')
8 | else:
9 | print(number, 'is not a prime number.')
10 |
11 |
12 |
13 | def is_prime(number):
14 |
15 | counter = 0
16 | for num in range(2, number):
17 | if number % num == 0:
18 | counter += 1
19 |
20 | if counter == 0:
21 | return True
22 | else:
23 | return False
24 |
25 |
26 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/property_tax.py:
--------------------------------------------------------------------------------
1 |
2 | # This program displays the property tax and assessment value
3 | # on a piece of land
4 |
5 | MULTIPLIER = 0.6
6 | ASS_MULTIPLIER = 10000
7 | PROP_MULTIPLIER = 72
8 |
9 | def property_tax():
10 | actual_val = float(input('Enter the property actual value: '))
11 |
12 | assessment_val = actual_val * MULTIPLIER
13 |
14 | # For each $100 of the assessment value
15 | # assessment value / 100
16 |
17 | each_assess_val = assessment_val / ASS_MULTIPLIER
18 | property_tax = each_assess_val * PROP_MULTIPLIER
19 |
20 | print(f'The Assessment Value Is: ${assessment_val:,.2f}')
21 | print(f'The Property Tax Is: ${property_tax:,.2f}')
22 |
23 | property_tax()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/sales_tax.py:
--------------------------------------------------------------------------------
1 | # This program ask the user to enter the amount of purchase
2 | # Then compute the state and county sales tax
3 |
4 | STATE_SALES_TAX = 0.05
5 | COUNTY_SALES_TAX = 0.025
6 |
7 | def main():
8 | purchase_price = purchase_amount()
9 |
10 | state_price = state_sales(purchase_price)
11 |
12 | county_price = county_sales(purchase_price)
13 |
14 | total_sales = total_sales_tax(state_price, county_price)
15 |
16 | print(f'Puchased Amount Is: ${purchase_price:,.2f}')
17 | print(f'The State Sales Tax Is: ${state_price:,.2f}')
18 | print(f'The County Sales Tax Is: ${county_price:,.2f}')
19 | print(f'The Total Sales Is: ${total_sales:,.2f}')
20 |
21 |
22 | def purchase_amount():
23 | purchase = float(input('Enter the amount of purchase: '))
24 | return purchase
25 |
26 |
27 | def state_sales(price):
28 | state_sales_price = price * STATE_SALES_TAX
29 | return state_sales_price
30 |
31 |
32 | def county_sales(price):
33 | county_sales_price = price * COUNTY_SALES_TAX
34 | return county_sales_price
35 |
36 |
37 | def total_sales_tax(state, county):
38 | return state + county
39 |
40 | main()
41 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/ProgrammingExercises/test_average.py:
--------------------------------------------------------------------------------
1 | def main():
2 | score_1 = int(input('Enter the first score: '))
3 | score_2 = int(input('Enter the second score: '))
4 | score_3 = int(input('Enter the third score: '))
5 | score_4 = int(input('Enter the fourth score: '))
6 | score_5 = int(input('Enter the fifth score: '))
7 |
8 | average = calc_average(score_1, score_2, score_3, score_4, score_5)
9 |
10 | for score in range(1, 6):
11 | if score == 1:
12 | first_grade = determine_grade(score_1)
13 | elif score == 2:
14 | second_grade = determine_grade(score_2)
15 | elif score == 3:
16 | third_grade = determine_grade(score_3)
17 | elif score == 4:
18 | fourth_grade = determine_grade(score_4)
19 | else:
20 | fifth_grade = determine_grade(score_5)
21 |
22 | print()
23 | print('Test\tScore\tGrade')
24 | print('=====================')
25 | print('Test1\t', score_1, '\t', first_grade)
26 | print('Test2\t', score_2, '\t', second_grade)
27 | print('Test1\t', score_3, '\t', third_grade)
28 | print('Test1\t', score_4, '\t', fourth_grade)
29 | print('Test1\t', score_5, '\t', fifth_grade)
30 |
31 | print()
32 | print('The average score is:', format(average, '.1f'))
33 |
34 |
35 |
36 | def calc_average(score_1, score_2, score_3, score_4, score_5):
37 | avg = (score_1 + score_2 + score_3 + score_4 + score_5) / 5
38 | return avg
39 |
40 |
41 | def determine_grade(score):
42 | if score >= 90 and score <= 100:
43 | return 'A'
44 | elif score >= 80 and score < 90:
45 | return 'B'
46 | elif score >= 70 and score < 80:
47 | return 'C'
48 | elif score >= 60 and score < 70:
49 | return 'D'
50 | elif score <= 60:
51 | return 'F'
52 | else:
53 | return 'Invalid Score !!!'
54 |
55 |
56 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/__pycache__/circle.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter05/__pycache__/circle.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/__pycache__/rectangle.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter05/__pycache__/rectangle.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/circle.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | def area(radius):
4 | return math.pi * radius ** 2
5 |
6 |
7 | def circumference(radius):
8 | return 2 * math.pi * radius
9 |
10 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/example.py:
--------------------------------------------------------------------------------
1 | import math
2 |
3 | # def main():
4 | # number = float(input('Enter a number: '))
5 | # square_root = math.sqrt(number)
6 | # print(f'The Square root of {number} is square_root.')
7 |
8 | # main()
9 |
10 | # def main():
11 | # a = float(input('Enter the length of side A: '))
12 | # b = float(input('Enter the length of side B: '))
13 |
14 | # c = math.hypot(a, b)
15 |
16 | # print('The length of the hypotenus is', c)
17 |
18 | # main()
19 |
20 |
21 | radius = int(input('Enter the radius of the circle: '))
22 | def area(rad):
23 | return math.pi * radius ** 2
24 |
25 | print('The area is:', format(area(radius),'.1f'))
26 |
27 | def circumference(rad):
28 | return 2 * math.pi * radius
29 |
30 | print('The circumference is:', format(circumference(radius),'.1f'))
31 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/geometry.py:
--------------------------------------------------------------------------------
1 | import circle
2 | import rectangle
3 |
4 | AREA_CIRCLE_CHOICE = 1
5 | CIRCUMFERENCE_CHOICE = 2
6 | AREA_RECTANGLE_CHOICE = 3
7 | PERIMETER_RECTANGLE_CHOICE = 4
8 | QUIT_CHOICE = 5
9 |
10 | def main():
11 | choice = 0
12 | while choice != QUIT_CHOICE:
13 | display_menu()
14 |
15 | choice = int(input('Enter your choice: '))
16 | if choice == AREA_CIRCLE_CHOICE:
17 | radius = float(input('Enter the circle\'s radius: '))
18 | print('The Area is', circle.area(radius))
19 | elif choice == CIRCUMFERENCE_CHOICE:
20 | radius = float(input('Enter the circle\'s radius: '))
21 | print('The Circumference is', circle.circumference(radius))
22 | elif choice == AREA_RECTANGLE_CHOICE:
23 | width = float(input('Enter the rectangle\'s width: '))
24 | length = float(input('Enter the rectangle\'s length: '))
25 | print('The Area of the rectangle is', rectangle.area(width, length))
26 | elif choice == PERIMETER_RECTANGLE_CHOICE:
27 | width = float(input('Enter the rectangle\'s width: '))
28 | length = float(input('Enter the rectangle\'s length: '))
29 | print('The Perimeter of is', rectangle.perimeter(width, length))
30 | elif choice == QUIT_CHOICE:
31 | print('Exiting the program...')
32 | else:
33 | print('Error: Invalid Selection.')
34 |
35 |
36 | def display_menu():
37 | print('MENU')
38 | print('1) Area of a circle')
39 | print('2) Circumference of a circle')
40 | print('3) Area of a Rectangle')
41 | print('4) Perimeter of a Rectangle')
42 | print('5) Quit')
43 |
44 |
45 | main()
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter05/rectangle.py:
--------------------------------------------------------------------------------
1 | def area(width, length):
2 | return width * length
3 |
4 |
5 | def perimeter(width, length):
6 | return 2 * (width + length)
7 |
8 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/biodata.py:
--------------------------------------------------------------------------------
1 | filename = 'biodata.txt'
2 | datas = '''
3 | Name: Tunde Muhamed
4 | Age: 29
5 | School: LAUTECH
6 | Phone: 070-3321-6997
7 | Status: Single
8 | '''
9 |
10 | my_data = open(filename, 'w')
11 | my_data.write(datas)
12 | my_data.close()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/biodata.txt:
--------------------------------------------------------------------------------
1 |
2 | Name: Tunde Muhamed
3 | Age: 29
4 | School: LAUTECH
5 | Phone: 070-3321-6997
6 | Status: Single
7 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/biodata_line.py:
--------------------------------------------------------------------------------
1 | def main():
2 | biodata = open('biodata.txt', 'r')
3 | line1 = biodata.readline()
4 | line2 = biodata.readline()
5 | line3 = biodata.readline()
6 | line4 = biodata.readline()
7 | line5 = biodata.readline()
8 | line6 = biodata.readline()
9 | biodata.close()
10 |
11 | print(line1)
12 | print(line2)
13 | print(line3)
14 | print(line4)
15 | print(line5)
16 | print(line6)
17 |
18 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/employees.txt:
--------------------------------------------------------------------------------
1 | Tunde Muhamed
2 | 4587
3 | Engineering
4 | Tomi Olorunkosebi
5 | 4588
6 | Micro-Biology
7 | Ogunniyi Titi
8 | 4589
9 | Marketing
10 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/exm.py:
--------------------------------------------------------------------------------
1 | try:
2 | num1 = int(input('1: '))
3 | num2 = int(input('2: '))
4 |
5 | result = num1 / num2
6 | print('Result=', result)
7 |
8 | # except ValueError as tunde:
9 | # print('Error!!!', tunde)
10 |
11 | # except ZeroDivisionError as ibk:
12 | # print('Error!!!', ibk)
13 |
14 | # To catch all forms of error
15 | except Exception as shina:
16 | print(shina)
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/file_read.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('philosophers.txt', 'r')
3 | file_contents = infile.read()
4 | infile.close()
5 |
6 | print(file_contents)
7 |
8 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/file_write.py:
--------------------------------------------------------------------------------
1 | def main():
2 | outfile = open('philosophers.txt', 'w')
3 | outfile.write('Tunde Muhamed\n')
4 | outfile.write('Shina Onilude\n')
5 | outfile.write('Mary Olowookere\n')
6 | outfile.close()
7 |
8 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/friends.txt:
--------------------------------------------------------------------------------
1 | Tunde
2 | Shina
3 | Mary
4 | Kazim
5 | Mayowa
6 | Tomi
7 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/line_read.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('philosophers.txt', 'r')
3 | line1 = infile.readline()
4 | line2 = infile.readline()
5 | line3 = infile.readline()
6 | infile.close()
7 |
8 | print(line1)
9 | print(line2)
10 | print(line3)
11 |
12 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/numbers.txt:
--------------------------------------------------------------------------------
1 | 45
2 | 60
3 | 10
4 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/philosophers.txt:
--------------------------------------------------------------------------------
1 | Tunde Muhamed
2 | Shina Onilude
3 | Mary Olowookere
4 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/read_bio.py:
--------------------------------------------------------------------------------
1 | # def main():
2 | # biodata = open('biodata.txt', 'r')
3 | # contents = biodata.read()
4 | # biodata.close()
5 |
6 | # print(contents)
7 |
8 | # main()
9 |
10 | myfile = open('friends.txt', 'a')
11 | myfile.write('Kazim\n')
12 | myfile.write('Mayowa\n')
13 | myfile.write('Tomi\n')
14 | myfile.close()
15 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/read_emp_records.py:
--------------------------------------------------------------------------------
1 | # This program displays the records that are in
2 | # the employees.txt file
3 |
4 | def main():
5 | # open the employees.txt file
6 | emp_file = open('employees.txt', 'r')
7 |
8 | # Read the first line from the file which is the
9 | # name field of the first record
10 |
11 | name = emp_file.readline()
12 | while name != '':
13 |
14 | # Read the ID number Field
15 | id_num = emp_file.readline()
16 |
17 | # Read the department field
18 | dept = emp_file.readline()
19 |
20 | # Strip the newlines from the field
21 |
22 | name = name.rstrip('\n')
23 | id_num = id_num.rstrip('\n')
24 | dept = dept.rstrip('\n')
25 |
26 | # Display the records
27 | print('Name:', name)
28 | print('ID:', id_num)
29 | print('Dept:', dept)
30 | print()
31 |
32 | # Read the name field of the next record
33 |
34 | name = emp_file.readline()
35 |
36 | emp_file.close()
37 |
38 | main()
39 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/read_numbers.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('numbers.txt', 'r')
3 |
4 | num1 = int(infile.readline())
5 | num2 = int(infile.readline())
6 | num3 = int(infile.readline())
7 |
8 | infile.close()
9 |
10 | total = num1 + num2 + num3
11 |
12 | print('The numbers are:', num1, num2, num3)
13 | print('Their total is:', total)
14 |
15 |
16 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/read_running_times.py:
--------------------------------------------------------------------------------
1 | def main():
2 | video_file = open('video_times.txt', 'r')
3 |
4 | total = 0.0
5 | count = 0
6 |
7 | print('Here are the running times for each video:')
8 |
9 | for line in video_file:
10 | run_time = float(line)
11 | count += 1
12 |
13 | print('Video #', count, ': ', run_time, sep='')
14 |
15 | total += run_time
16 |
17 | video_file.close()
18 |
19 | print('The total running time is', total, 'seconds')
20 |
21 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/read_sales.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('sales.txt', 'r')
3 | value = infile.readline()
4 |
5 | while value != '':
6 | line = float(value)
7 | print(line)
8 |
9 | value = infile.readline()
10 |
11 | infile.close()
12 |
13 | main()
14 |
15 | # m = '99'
16 | # print(int(m))
17 | # num = float(m)
18 | # print(num)
19 | # print(str(num))
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/read_sales2.py:
--------------------------------------------------------------------------------
1 | def main():
2 | sales_file = open('sales.txt', 'r')
3 |
4 | for line in sales_file:
5 | amount = float(line)
6 | print(format(amount, '.2f'))
7 |
8 | sales_file.close()
9 |
10 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/sales.txt:
--------------------------------------------------------------------------------
1 | 1000.0
2 | 2000.0
3 | 3000.0
4 | 4000.0
5 | 5000.0
6 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/sales_data.txt:
--------------------------------------------------------------------------------
1 | 24987.62
2 | 26978.97
3 | 32589.45
4 | 31978.47
5 | 22781.76
6 | 29871.44
7 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/sales_report.py:
--------------------------------------------------------------------------------
1 | # This program asks the user to enter sales amount for a month
2 | # and save them in a file name sales_data.txt
3 |
4 | def main():
5 | again = 'y'
6 | sales_file = open('sales_data.txt', 'w')
7 |
8 | while again == 'y' or again == 'Y':
9 | print('Enter the sales amount for a month', end='')
10 | sales = float(input(': '))
11 |
12 | sales_file.write(str(sales) + '\n')
13 |
14 | again = input('Do you want to enter more sales? [Y/n] to continue: ')
15 |
16 | sales_file.close()
17 |
18 | print('Sales has been written to sales_data.txt.')
19 |
20 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/sales_report1.py:
--------------------------------------------------------------------------------
1 | def main():
2 | total = 0.0
3 |
4 | try:
5 | infile = open('sales_data.txt', 'r')
6 | for line in infile:
7 | amount = float(line)
8 | total += amount
9 |
10 | infile.close()
11 |
12 | print('Total: $', format(total, ',.2f'), sep='')
13 |
14 |
15 | except IOError:
16 | print('An Error occured trying to read the file.')
17 |
18 | except ValueError:
19 | print('Non numeric data found in the file.')
20 |
21 | except:
22 | print('An error occured.')
23 |
24 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/sales_report2.py:
--------------------------------------------------------------------------------
1 | def main():
2 | total = 0.0
3 |
4 | try:
5 | infile = open('sales_data.txt', 'r')
6 | for line in infile:
7 | amount = float(line)
8 | total += amount
9 |
10 | infile.close()
11 |
12 | print('Total: $', format(total, ',.2f'), sep='')
13 |
14 |
15 | # except IOError:
16 | # print('An Error occured trying to read the file.')
17 |
18 | # except ValueError:
19 | # print('Non numeric data found in the file.')
20 |
21 | except:
22 | print('An error occured.')
23 |
24 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/sales_report4.py:
--------------------------------------------------------------------------------
1 | def main():
2 | total = 0.0
3 |
4 | try:
5 | infile = open('sales_data.txt', 'r')
6 | for line in infile:
7 | amount = float(line)
8 | total += amount
9 |
10 | infile.close()
11 |
12 | except Exception as err:
13 | print(err)
14 |
15 | else:
16 | print('Total: $', format(total, ',.2f'), sep='')
17 |
18 |
19 |
20 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/save_emp_records.py:
--------------------------------------------------------------------------------
1 | # This program gets employee data from the user and
2 | # saves it as record in the employees.txt files
3 |
4 | def main():
5 | # Get the number of employees records to create
6 | num_emps = int(input('How many employee records do you want to create? '))
7 |
8 | # open a file for writing
9 | emp_file = open('employees.txt', 'w')
10 | # Get the employee's data and write it to the file
11 | for count in range(1, num_emps+1):
12 | print('Enter data for employee #', count, sep='')
13 | name = input('Name: ')
14 | id_number = input('ID number: ')
15 | dept = input('Department: ')
16 |
17 | # write the data as a record to the file
18 |
19 | emp_file.write(name + '\n')
20 | emp_file.write(id_number + '\n')
21 | emp_file.write(dept + '\n')
22 | print()
23 |
24 | emp_file.close()
25 | print('Employee records written to employee.txt.')
26 |
27 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/save_running_times.py:
--------------------------------------------------------------------------------
1 | def main():
2 | num_videos = int(input('How many videos are in the project? '))
3 | video_file = open('video_times.txt', 'w')
4 |
5 | print('Enter the running times for each video.')
6 |
7 | for count in range(1, num_videos+1):
8 | run_time = float(input('Video #' + str(count) + ': '))
9 | video_file.write(str(run_time) + '\n')
10 |
11 | video_file.close()
12 |
13 | print('The times has been saved to video_times.txt.')
14 |
15 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/strip_newline.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('friends.txt', 'r')
3 |
4 | name1 = infile.readline()
5 | name2 = infile.readline()
6 | name3 = infile.readline()
7 |
8 | name1 = name1.rstrip('\n')
9 | name2 = name2.rstrip('\n')
10 | name3 = name3.rstrip('\n')
11 |
12 | infile.close()
13 |
14 | print(name1)
15 | print(name2)
16 | print(name3)
17 |
18 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/video_times.txt:
--------------------------------------------------------------------------------
1 | 24.5
2 | 12.2
3 | 14.6
4 | 20.4
5 | 22.5
6 | 19.3
7 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/write_names.py:
--------------------------------------------------------------------------------
1 | def main():
2 | print('Enter the names of three friends.')
3 | name1 = input('Friend #1: ')
4 | name2 = input('Friend #2: ')
5 | name3 = input('Friend #3: ')
6 |
7 | myfile = open('friends.txt', 'w')
8 | # myfile.write(f'{name1}\n{name2}\n{name3}')
9 | myfile.write(name1 + '\n')
10 | myfile.write(name2 + '\n')
11 | myfile.write(name3 + '\n')
12 |
13 | myfile.close()
14 |
15 | print('The names are written to friends.txt.')
16 |
17 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/write_numbers.py:
--------------------------------------------------------------------------------
1 | def main():
2 | outfile = open('numbers.txt', 'w')
3 |
4 | num1 = int(input('Enter a number: '))
5 | num2 = int(input('Enter another number: '))
6 | num3 = int(input('Enter another number: '))
7 |
8 | outfile.write(str(num1) + '\n')
9 | outfile.write(str(num2) + '\n')
10 | outfile.write(str(num3) + '\n')
11 |
12 | outfile.close()
13 |
14 | print('Data written to numbers.txt. ')
15 |
16 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/Examples/write_sales.py:
--------------------------------------------------------------------------------
1 | def main():
2 | num_days = int(input('For howw many days do you have sales? '))
3 |
4 | sales_file = open('sales.txt', 'w')
5 |
6 | for count in range(1, num_days+1):
7 | sales = float(input('Enter the sales for day #' + str(count) + ': '))
8 | sales_file.write(str(sales) + '\n')
9 |
10 | sales_file.close()
11 |
12 | print('Data written to sales.txt.')
13 |
14 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/average_of_numbers.py:
--------------------------------------------------------------------------------
1 | # This program calculates the average of the numbers in
2 | # the file named numbers.txt
3 |
4 | def main():
5 | total = 0.0
6 | count = 0
7 |
8 | infile = open('numbers.txt', 'r')
9 |
10 | for line in infile:
11 | val = float(line)
12 | count += 1
13 | total += val
14 |
15 | infile.close()
16 |
17 | average = total / count
18 |
19 | print(f'The average of all numbers in the file (numbers.txt) is {average:.1f}.')
20 |
21 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/average_steps_taken.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter06/ProgrammingExercises/average_steps_taken.py
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/exception_handling.py:
--------------------------------------------------------------------------------
1 | # This program modifies the program written in average_of_numbers.py module
2 | # and should handle the following errors... IOError when reading files
3 | # and ValueError when items read are converted to numbers
4 |
5 | def main():
6 | total = 0.0
7 | count = 0
8 |
9 |
10 | try:
11 | infile = open('numbers.txt', 'r')
12 |
13 | for line in infile:
14 | val = float(line)
15 | count += 1
16 | total += val
17 |
18 | infile.close()
19 |
20 | average = total / count
21 |
22 | print(f'The average of all numbers in the file (numbers.txt) is {average:.1f}.')
23 |
24 | # handling FileNotFoundError
25 | except IOError:
26 | print('The data can not be read from the file.')
27 |
28 | # handling bad data error
29 | except ValueError:
30 | print('The value cnnot be converted to numbers.')
31 |
32 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/file_display.py:
--------------------------------------------------------------------------------
1 | # This program writes integer numbers to a file named numbers.txt
2 |
3 | def main():
4 | # create a way to control the loop
5 | again = 'y'
6 |
7 | # open an output file
8 | outfile = open('numbers.txt', 'w')
9 |
10 | while again == 'y' or again == 'Y':
11 | number = int(input('Enter a number: '))
12 | outfile.write(str(number) + '\n')
13 |
14 | # Enter more numbers
15 | again = input('Enter [Y/n] to enter another number: ')
16 |
17 | outfile.close()
18 |
19 | print('Integer numbers have been written to numbers.txt.')
20 |
21 | # call the main function
22 | main()
23 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/file_head_display.py:
--------------------------------------------------------------------------------
1 | # This program asks the user to enter the name of a file
2 | # and displays the first 5 lines in the file
3 |
4 | def main():
5 | filename = input('Enter a file name: ')
6 |
7 | infile = open(filename, 'r')
8 | line1 = infile.readline()
9 | line2 = infile.readline()
10 | line3 = infile.readline()
11 | line4 = infile.readline()
12 | line5 = infile.readline()
13 |
14 | line1 = line1.rstrip('\n')
15 | line2 = line2.rstrip('\n')
16 | line3 = line3.rstrip('\n')
17 | line4 = line4.rstrip('\n')
18 | line5 = line5.rstrip('\n')
19 |
20 | infile.close()
21 |
22 | print(line1)
23 | print(line2)
24 | print(line3)
25 | print(line4)
26 | print(line5)
27 |
28 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/golf.txt:
--------------------------------------------------------------------------------
1 | Tunde Muhamed
2 | 98.7
3 | Shina Onilude
4 | 90.7
5 | Ibukun Sheriff
6 | 97.8
7 | Tomi Olorunkosebi
8 | 78.3
9 | Bolarinwa Tunde
10 | 123.8
11 | Kolade Simeon
12 | 55.4
13 | Oloyede Jacob
14 | 46.1
15 | Agboola John
16 | 80.0
17 | Tunde
18 | 55
19 | Wale
20 | 98
21 | Tunde
22 | 55
23 | Wale
24 | 76
25 | Shade
26 | 43
27 | John
28 | 33
29 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/golf_scores.py:
--------------------------------------------------------------------------------
1 | # This program reads player's name and score in a golf amateur club
2 | # as a record with name field and score field in a file named golf.txt
3 |
4 | def main():
5 | # design a mean to control the loop
6 | again = 'y'
7 |
8 | # open a file named golf.txt in append mode
9 | golf_file = open('golf.txt', 'a')
10 |
11 | while again == 'y' or again == 'Y':
12 | player_name = input('Enter the player\'s name: ')
13 | score = int(input('Enter the player\'s score: '))
14 |
15 | # Write the player's name and score to the golf.txt file
16 | golf_file.write(player_name + '\n')
17 | golf_file.write(str(score) + '\n')
18 |
19 | # print a blank space
20 | print()
21 |
22 | # Enter more player records
23 | again = input('Enter more player records? [Y/n] to continue: ')
24 |
25 | golf_file.close()
26 |
27 | print('The player\'s records have been written to golf.txt file.')
28 |
29 | main()
30 |
31 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/golf_scores2.py:
--------------------------------------------------------------------------------
1 | # This program reads the contents of the golf.txt file
2 | # and displays the on the screen
3 |
4 | def main():
5 |
6 | again = 'y'
7 |
8 | golf_file = open('golf.txt', 'r')
9 |
10 | # read the first line
11 | name = golf_file.readline()
12 | while name != '':
13 | score = float(golf_file.readline())
14 |
15 | # strip the newline
16 | name = name.rstrip('\n')
17 |
18 | # Display the contents of the file
19 | print('Name:', name)
20 | print('Score:', score)
21 | print()
22 |
23 | name = golf_file.readline()
24 |
25 | golf_file.close()
26 |
27 | main()
28 |
29 |
30 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/item_counter.py:
--------------------------------------------------------------------------------
1 | # This program displays the number of names that are stored
2 | # in the file names.txt
3 |
4 | def main():
5 | count = 0
6 | filename = input('Enter a filename: ')
7 |
8 | infile = open(filename, 'r')
9 |
10 | for line in infile:
11 | count += 1
12 |
13 | infile.close()
14 |
15 | print(f'Total number of names in this file ({filename}) is {count}.')
16 |
17 | main()
18 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/items_names.py:
--------------------------------------------------------------------------------
1 | def main():
2 | # create a way to control the loop
3 | again = 'y'
4 |
5 | # open an output file
6 | outfile = open('names.txt', 'w')
7 |
8 | while again == 'y' or again == 'Y':
9 | name = input('Enter a name: ')
10 | outfile.write(name + '\n')
11 |
12 | # Enter more numbers
13 | again = input('Enter [Y/n] to enter another name: ')
14 |
15 | outfile.close()
16 |
17 | print('Names have been written to names.txt.')
18 |
19 | # call the main function
20 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/line_numbers.py:
--------------------------------------------------------------------------------
1 | # # This program asks the user to enter the name of a file
2 | # with each line preceded with a line number and a colon
3 |
4 | def main():
5 | count = 0
6 | filename = input('Enter a file name: ')
7 |
8 | infile = open(filename, 'r')
9 | for line in infile:
10 | amount = int(line)
11 | count += 1
12 | print('Line Number #', count, ': ', amount, sep='')
13 |
14 | infile.close()
15 |
16 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/names.txt:
--------------------------------------------------------------------------------
1 | Tunde
2 | Wale
3 | Shakirat
4 | Shina
5 | Tomi
6 | Mary
7 | Shade
8 | SamD Don
9 | Marvellous
10 | Adawa
11 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/numbers.txt:
--------------------------------------------------------------------------------
1 | 33
2 | 55
3 | 81
4 | 15
5 | 22
6 | 42
7 | 27
8 | 35
9 | 19
10 | 15
11 | 10
12 | 37
13 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/personal_webpage_generator.py:
--------------------------------------------------------------------------------
1 | def main():
2 | name = input('What is your name? ')
3 | descr = input('Describe yourself in two sentences: ')
4 |
5 | html_result = f'''
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 | {name}
14 |
15 |
16 |
17 | {descr}
18 |
19 |
20 |
21 |
22 | '''
23 |
24 | print(html_result)
25 |
26 | main()
27 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/random_number_file_reader.py:
--------------------------------------------------------------------------------
1 | # This program reads the content of the file named random_numbers.txt
2 | # then displays the numbers, displays the total of the numbers, and
3 | # the number of random numbers read from the file.
4 |
5 | def main():
6 | total = 0.0
7 | count = 0
8 |
9 | infile = open('random_numbers.txt', 'r')
10 |
11 | print('The List Of The Random NUmbers...')
12 | print('------------------------------')
13 |
14 | for line in infile:
15 | val = float(line)
16 | count += 1
17 | total += val
18 | print(f'#{count}: {val}')
19 |
20 | print()
21 |
22 | infile.close()
23 |
24 | # display the sum of all the random numbers
25 | print(f'Total of all random numbers in (random_numbers.txt) file is/are {total}.')
26 |
27 | # Display how many random numbers in the file
28 | print(f'The number of random numbers in (random_numbers.txt) file is {count}.')
29 |
30 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/random_number_file_writer.py:
--------------------------------------------------------------------------------
1 | # This program writes a series of random numbers to a file
2 | # Each random number should be in the range of 1 through 500
3 | # The program should specify how many random numbers the file should hold
4 |
5 | import random
6 |
7 | def main():
8 | num_rand = int(input('How many random numbers do you want this file to hold? '))
9 |
10 | outfile = open('random_numbers.txt', 'w')
11 |
12 | for num in range(1, num_rand+1):
13 | rand_num = random.randint(1, 500)
14 | outfile.write(str(rand_num) + '\n')
15 |
16 | outfile.close()
17 |
18 | print('Random Numbers have been written to random_numbers.txt.')
19 |
20 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/random_numbers.txt:
--------------------------------------------------------------------------------
1 | 199
2 | 171
3 | 448
4 | 376
5 | 201
6 | 241
7 | 343
8 | 268
9 | 3
10 | 411
11 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter06/ProgrammingExercises/sum_of_numbers.py:
--------------------------------------------------------------------------------
1 | # This program calculates the total of the numbers in
2 | # the file named numbers.txt
3 |
4 | def main():
5 | total = 0.0
6 |
7 | infile = open('numbers.txt', 'r')
8 |
9 | for line in infile:
10 | val = float(line)
11 | total += val
12 |
13 | infile.close()
14 |
15 | print(f'The total of all numbers in the file (numbers.txt) is/are {total:.1f}.')
16 |
17 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/add_coffee_records.py:
--------------------------------------------------------------------------------
1 | # This program adds as many as coffee records in a file named coffee.txt
2 |
3 | def main():
4 | # open a file coffee.txt in append mode
5 | coffee_file = open("coffee.txt", "a")
6 |
7 | # create a way to controll the loop
8 | again = "y"
9 | while again == "y" or again == "Y":
10 | print("Enter the description of the coffee.")
11 | descr = input(": ")
12 | print("Enter the quantity.")
13 | qty = int(input(": "))
14 |
15 | # write the description and the quantity to the file
16 | coffee_file.write(descr + "\n")
17 | coffee_file.write(str(qty) + "\n")
18 |
19 | # add more coffee records
20 | again = input("Enter [Y/n] to add more records quit: ")
21 |
22 | # close the file
23 | coffee_file.close()
24 | print("Coffee records has been written to coffee.txt.")
25 |
26 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/cities.txt:
--------------------------------------------------------------------------------
1 | New York
2 | Hoston
3 | Atlanta
4 | Dallas
5 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/coffee.txt:
--------------------------------------------------------------------------------
1 | Savanna Swamp Coffee
2 | 34.0
3 | Cognitive Coffee Mill
4 | 30.0
5 | Amazon Rain Coffee
6 | 25.0
7 | Savanna Swamp Coffee
8 | 33.0
9 | Brown Indian Coffee
10 | 30.0
11 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/command.py:
--------------------------------------------------------------------------------
1 | started = False
2 | command = ""
3 |
4 | while command == "":
5 | print("Enter (START) to start the Car OR (STOP) to stop the Car.")
6 | command = input(": ").lower()
7 | if command == "start":
8 | if started:
9 | print("Car already started !!!")
10 | else:
11 | started = True
12 | print("Car started...")
13 |
14 | elif command == "stop":
15 | if not started:
16 | print("Car already stopped...")
17 | else:
18 | started = False
19 | print("Car stopped...")
20 |
21 | command = ""
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/delete_coffee_records.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter07/Examples/delete_coffee_records.py
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/display_file.py:
--------------------------------------------------------------------------------
1 | def main():
2 | filename = input("Enter a filename: ")
3 |
4 | try:
5 | infile = open(filename, "r")
6 | contents = infile.read()
7 | print("The contents of", "(", filename, ") are...")
8 | print("-------------------------------------")
9 | print()
10 | print(contents)
11 |
12 | infile.close()
13 |
14 | except IOError:
15 | print("The file", filename, "is not found.")
16 |
17 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/formatting.py:
--------------------------------------------------------------------------------
1 | def msg_format(name, website):
2 | return f"Hello {name}, you are welcome to {website}"
3 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/in_list.py:
--------------------------------------------------------------------------------
1 | # This program demonstrates the in operator used with a list
2 |
3 | def main():
4 | # Create a list of product numbers
5 | prod_nums = ['V475', 'F987', 'Q143', 'R688']
6 |
7 | # Get a product number to search for
8 | search = input('Enter a product number: ')
9 |
10 | # if search in prod_nums:
11 | if search not in prod_nums:
12 | print(search, 'was not found in the list.')
13 | else:
14 | print(search, 'was found in the list.')
15 |
16 | main()
17 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/index_list.py:
--------------------------------------------------------------------------------
1 | # This program takes an index of an item in a list
2 | # and assign it to another new item
3 |
4 | def main():
5 | # Create a list of item
6 | names = ['Tunde', 'Wuraade', 'Tomi']
7 |
8 | print('These are the lists of your names:')
9 | print(names)
10 |
11 | # Enter an item to search
12 | name = input('What name do you want to change? ')
13 |
14 | try:
15 | name_index = names.index(name)
16 |
17 | # Enter a new name
18 | new_name = input('Enter the new name: ')
19 | names[name_index] = new_name
20 |
21 | print('Here is the updated lists of names: ')
22 | print(names)
23 |
24 | except ValueError:
25 | print('Name was not found in the list.')
26 |
27 | main()
28 |
29 |
30 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/insert_list.py:
--------------------------------------------------------------------------------
1 | # This program demonstrates the insert method
2 |
3 | def main():
4 | # Create a list with some names
5 | names = ['James', 'Kathryn', 'Bill']
6 |
7 | # Display the list
8 | print('The list before inserting new name:')
9 | print(names)
10 | print()
11 |
12 | # Insert a new name at element 0
13 | names.insert(0, 'Tunde Muhamed')
14 |
15 | # Display the list again
16 | print('The list after inserting new name:')
17 | print(names)
18 |
19 | main()
20 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/list_append.py:
--------------------------------------------------------------------------------
1 | # This program demonstrates how the append method can be
2 | # used to add items to the end of the list
3 |
4 | def main():
5 | # First create an empty list
6 | name_list = []
7 |
8 | # Create a variable to control the loop
9 | again = 'y'
10 |
11 | # Add some names to the list
12 | while again == 'y':
13 | # Get a name from the user
14 | name = input('Enter a name: ')
15 |
16 | # Append the name to the list
17 | name_list.append(name)
18 |
19 | # Add more names?
20 | print('Do you want to add another name? ')
21 | again = input('Y=yes, anything else=no: ')
22 | print()
23 |
24 | # Display the names that were entered
25 | print('Here are the names you entered: ')
26 | for name in name_list:
27 | print(name)
28 |
29 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/modify_coffee_records.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | def main():
4 | found = False
5 | coffee_file = open("coffee.txt", "r")
6 | temp_file = open("temp.txt", "w")
7 |
8 | search = input("Enter the description to search for: ")
9 | new_qty = int(input("Enter the new quantity (in pounds): "))
10 |
11 | descr = coffee_file.readline()
12 | while descr != "":
13 | qty = float(coffee_file.readline())
14 |
15 | descr = descr.rstrip("\n")
16 |
17 | if search == descr:
18 | temp_file.write(descr + "\n")
19 | temp_file.write(str(new_qty) + "\n")
20 | found = True
21 |
22 | else:
23 | temp_file.write(descr + "\n")
24 | temp_file.write(str(qty) + "\n")
25 |
26 | descr = coffee_file.readline()
27 |
28 | coffee_file.close()
29 |
30 | os.remove("coffee.txt")
31 | os.rename("temp.txt", "coffee.txt")
32 |
33 | if found:
34 | print("The coffee record has been updated..")
35 | else:
36 | print("The description was not found in the list.")
37 |
38 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/numberlist.txt:
--------------------------------------------------------------------------------
1 | 1
2 | 2
3 | 3
4 | 4
5 | 5
6 | 6
7 | 7
8 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/pie_chart.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter07/Examples/pie_chart.py
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/prime_numbers.py:
--------------------------------------------------------------------------------
1 | def main():
2 | number = int(input("Enter a number: "))
3 | prime = is_prime(number)
4 | if prime:
5 | print(number, "is a prime number.")
6 | else:
7 | print(number, "is not a prime number.")
8 |
9 | def is_prime(num):
10 | counter = 0
11 | for n in range(2, num):
12 | if num % n == 0:
13 | counter += 1
14 |
15 | if counter == 0:
16 | return True
17 | else:
18 | return False
19 |
20 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/random_numbers.py:
--------------------------------------------------------------------------------
1 | # This program assigns random numbers to a two_dimensional list
2 |
3 | import random
4 |
5 | ROWS = 3
6 | COLS = 4
7 |
8 | def main():
9 | values = [
10 | [0, 0, 0, 0],
11 | [0, 0, 0, 0],
12 | [0, 0, 0, 0]
13 | ]
14 |
15 | # Fill in the lists with random numbers
16 | for r in range(ROWS):
17 | for c in range(COLS):
18 | values[r][c] = random.randint(1, 100)
19 |
20 | # Display the random numbers
21 | print(values)
22 |
23 | print()
24 | for r in range(ROWS):
25 | for c in range(COLS):
26 | print(values[r][c])
27 |
28 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/read_coffee_records.py:
--------------------------------------------------------------------------------
1 | def main():
2 | coffee_file = open("coffee.txt", "r")
3 |
4 | # read the first line
5 | descr = coffee_file.readline()
6 | while descr != "":
7 | qty = float(coffee_file.readline())
8 |
9 | # strip the new line using rstrip method
10 | descr = descr.rstrip("\n")
11 |
12 | print("Description:", descr)
13 | print("Quantity:", qty)
14 | print()
15 |
16 | # read another line
17 |
18 | descr = coffee_file.readline()
19 |
20 | coffee_file.close()
21 |
22 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/read_list.py:
--------------------------------------------------------------------------------
1 | # this program reads a file's contents into a list
2 |
3 | def main():
4 | infile = open('cities.txt', 'r')
5 |
6 | # read the contents of the file into a list
7 | cities = infile.readlines()
8 |
9 | infile.close()
10 |
11 | # strip the newline from each elements
12 | # index = 0
13 | # while index < len(cities):
14 | # cities[index] = cities[index].rstrip('\n')
15 | # index += 1
16 |
17 | print(cities)
18 |
19 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/read_number_list.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('numberlist.txt', 'r')
3 | numbers = infile.readlines()
4 |
5 | index = 0
6 | while index < len(numbers):
7 | numbers[index] = int(numbers[index])
8 | index += 1
9 |
10 | infile.close()
11 |
12 | print(numbers)
13 |
14 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/read_run_total.py:
--------------------------------------------------------------------------------
1 | # File read using while loop
2 |
3 | """def main():
4 | total = 0.0
5 | count = 0
6 |
7 | video_file = open("video_times.txt", "r")
8 | line = video_file.readline()
9 |
10 | while line != "":
11 | amount = float(line)
12 | count += 1
13 | print("Video #", count, ": ", amount, sep="")
14 |
15 | total += amount
16 | line = video_file.readline()
17 |
18 | video_file.close()
19 |
20 | print("Total runtime is:", format(total, ".1f"), "seconds.")
21 |
22 | main()
23 | """
24 |
25 | # File read using for loop
26 |
27 | def main():
28 | total = 0.0
29 | count = 0
30 |
31 | video_file = open("video_times.txt", "r")
32 | for line in video_file:
33 | amount = float(line)
34 | count += 1
35 |
36 | print("Video #", count, ": ", amount, sep="")
37 |
38 | total += amount
39 |
40 | video_file.close()
41 |
42 | print("Total runtime is:", format(total, ".1f"), "seconds.")
43 |
44 | main()
45 |
46 |
47 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/remove_item.py:
--------------------------------------------------------------------------------
1 | # This program deonstrates how to use the remove method
2 | # to remove an item from a list
3 |
4 | def main():
5 | # Create a list with some items
6 | food = ['Pizza', 'Burgers', 'Chips']
7 |
8 | print('Here are the items in the fod list:')
9 | print(food)
10 | print()
11 |
12 | # Get the item to remove
13 | item = input('Which item do you want to remove? ')
14 |
15 | try:
16 | food.remove(item)
17 |
18 | print('Here is the revised list:')
19 | print(food)
20 |
21 | except ValueError:
22 | print('That item was not found in the list.')
23 |
24 | # except Exception as err:
25 | # print('ERROR !!!:', err)
26 |
27 |
28 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/sales_list.py:
--------------------------------------------------------------------------------
1 | # The NUM_DAYS constant holds the number of days that we will gather sales data for
2 |
3 | NUM_DAYS = 5
4 |
5 | def main():
6 | # create a list to hold the sales for each day
7 | sales = [0] * 5
8 |
9 | index = 0
10 |
11 | print('Enter the sales for each day.')
12 |
13 | while index < NUM_DAYS:
14 | print('Day #', index+1, ': ', sep='', end='')
15 | sales[index] = float(input())
16 | index += 1
17 |
18 | # Display the values entered
19 | print('Here are the values you entered:')
20 | for value in sales:
21 | print(value)
22 |
23 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/search_coffee_records.py:
--------------------------------------------------------------------------------
1 | def main():
2 | found = False
3 | coffee_file = open("coffee.txt", "r")
4 |
5 | search = input("Enter the description to search for: ")
6 |
7 | descr = coffee_file.readline()
8 | while descr != "":
9 | qty = float(coffee_file.readline())
10 |
11 | descr = descr.rstrip("\n")
12 |
13 | if search == descr:
14 | print("Description:", descr)
15 | print("Quantity:", qty)
16 | found = True
17 |
18 | descr = coffee_file.readline()
19 |
20 | coffee_file.close()
21 |
22 | if not found:
23 | print("The description was not found in the records.")
24 |
25 | main()
26 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/send.py:
--------------------------------------------------------------------------------
1 | def send(name, website=None, verbose=False):
2 |
3 | if website != None:
4 | return f"You are welcome {name}, you have just log on to\n{website}"
5 | else:
6 | return f"You are welcome {name}!"
7 |
8 | if verbose:
9 | r = requests.get("https://www.goal.com")
10 | return r
11 |
12 | else:
13 | return "Website error"
14 |
15 |
16 | res = send("Tunde Muhamed", verbose=True)
17 | print(res)
18 |
19 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/tuples.py:
--------------------------------------------------------------------------------
1 | # my_tuple_list = (1, 2, 3, 4, 5)
2 | # max_num = max(my_tuple_list)
3 | # min_num = min(my_tuple_list)
4 | # print('Maximum num:', max_num)
5 | # print('Minimum num:', min_num)
6 |
7 | # for num in range(5):
8 | # number = int(input('Enter a number: '))
9 | # my_tuple_list.append(num)
10 |
11 | # print(my_tuple_list)
12 |
13 | my_tuple_list = (1,)
14 | print(my_tuple_list[0])
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/two_dimension_list.py:
--------------------------------------------------------------------------------
1 | score = [
2 | [87, 76, 90],
3 | [56, 73, 50],
4 | [40, 49, 58]
5 | ]
6 |
7 | print('The Elements in row 1')
8 | print(score[0][0])
9 | print(score[0][1])
10 | print(score[0][2])
11 |
12 | print()
13 |
14 | print('The Elements in row 2')
15 | print(score[1][0])
16 | print(score[1][1])
17 | print(score[1][2])
18 |
19 | print()
20 |
21 | print('The Elements in row 3')
22 | print(score[2][0])
23 | print(score[2][1])
24 | print(score[2][2])
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/write_list.py:
--------------------------------------------------------------------------------
1 | def main():
2 | cities = ['New York', 'Hoston', 'Atlanta', 'Dallas']
3 |
4 | outfile = open('cities.txt', 'w')
5 |
6 | # Write the list to the file
7 | for item in cities:
8 | outfile.write(item + '\n')
9 |
10 | outfile.close()
11 |
12 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/write_number_list.py:
--------------------------------------------------------------------------------
1 | # This program writes a list of numbers to a file
2 |
3 | def main():
4 | numbers = [1, 2, 3, 4, 5, 6, 7]
5 | outfile = open('numberlist.txt', 'w')
6 |
7 | for item in numbers:
8 | outfile.write(str(item) + '\n')
9 |
10 | outfile.close()
11 |
12 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/write_run_total.py:
--------------------------------------------------------------------------------
1 | def main():
2 | video_file = open("video_times.txt", "w")
3 |
4 | print("How many videos do you want?", end="")
5 |
6 | num_videos = int(input(": "))
7 |
8 | for vid in range(1, num_videos+1):
9 | run_time = float(input("Video #" + str(vid) + ": "))
10 | video_file.write(str(run_time) + "\n")
11 |
12 | video_file.close()
13 |
14 | print("Run time written to video_times.txt.")
15 |
16 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/Examples/writelines.py:
--------------------------------------------------------------------------------
1 | # This program uses the writelines method to save a list of strings to a file
2 |
3 | def main():
4 | cities = ['New York', 'Hoston', 'Atlanta', 'Dallas']
5 |
6 | outfile = open('cities.txt', 'w')
7 | outfile.writelines(cities)
8 |
9 | outfile.close()
10 |
11 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/1994_Weekly_Gas_Averages.txt:
--------------------------------------------------------------------------------
1 | 2500
2 | 3500
3 | 4500
4 | 4600
5 | 1100
6 | 5500
7 | 6500
8 | 1250
9 | 3250
10 | 36000
11 | 5000
12 | 3000
13 | 3450
14 | 2130
15 | 2100
16 | 2310
17 | 7500
18 | 8500
19 | 9500
20 | 10500
21 | 10000
22 | 8000
23 | 9000
24 | 7000
25 | 2300
26 | 4322
27 | 5344
28 | 2357
29 | 1200
30 | 1290
31 | 1380
32 | 2370
33 | 4389
34 | 1750
35 | 1860
36 | 1980
37 | 1990
38 | 2190
39 | 3290
40 | 4290
41 | 5290
42 | 8900
43 | 9700
44 | 7650
45 | 4512
46 | 3278
47 | 5689
48 | 3421
49 | 5490
50 | 3289
51 | 1789
52 | 4550
53 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/1994_weekly_gas_price.py:
--------------------------------------------------------------------------------
1 | def main():
2 | outfile = open('1994_Weekly_Gas_Averages.txt', 'w')
3 | for i in range(52):
4 | price = int(input('Gas Price for day #' + str(i+1) + ': '))
5 | outfile.write(str(price) + '\n')
6 |
7 | outfile.close()
8 |
9 | print('Gas price has been written to 1994_Weekly_Gas_Averages.txt.')
10 |
11 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/1994_weekly_gas_price2.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 |
3 |
4 | def main():
5 | infile = open('1994_Weekly_Gas_Averages.txt', 'r')
6 | gas_price = infile.readlines()
7 |
8 | for index in range(len(gas_price)):
9 | gas_price[index] = int(gas_price[index])
10 |
11 | print()
12 | left_edges = gas_price
13 |
14 | height = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 300, 400, 50, 60, 70, 90,
15 | 100, 150, 200, 250, 300, 400, 500, 600, 700, 800, 50, 90, 100, 150, 170, 190, 220, 240, 260, 280 ,320, 360, 390, 420, 300]
16 |
17 | bar_width = 5
18 |
19 | plt.xlim(xmin=500, xmax=5000)
20 | plt.ylim(ymin=10, ymax=1000)
21 |
22 | plt.bar(left_edges, height, bar_width)
23 | plt.show()
24 |
25 | main()
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/8_ball_responses.txt:
--------------------------------------------------------------------------------
1 | Yes, of course!
2 | Without a doubt, yes.
3 | You can count on it
4 | For Sure!
5 | Ask me later.
6 | I'm not sure.
7 | I can't tell you right now.
8 | I'll tell you after my nap.
9 | No way!
10 | I don't think so.
11 | Without a doubt, No.
12 | The answer is clearly NO.
13 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/BoyNames.txt:
--------------------------------------------------------------------------------
1 | Jacob
2 | Michael
3 | Joshua
4 | Matthew
5 | Daniel
6 | Christopher
7 | Andrew
8 | Ethan
9 | Joseph
10 | William
11 | Anthony
12 | David
13 | Alexander
14 | Nicholas
15 | Ryan
16 | Tyler
17 | James
18 | John
19 | Jonathan
20 | Noah
21 | Brandon
22 | Christian
23 | Dylan
24 | Samuel
25 | Benjamin
26 | Zachary
27 | Nathan
28 | Logan
29 | Justin
30 | Gabriel
31 | Jose
32 | Austin
33 | Kevin
34 | Elijah
35 | Caleb
36 | Robert
37 | Thomas
38 | Jordan
39 | Cameron
40 | Jack
41 | Hunter
42 | Jackson
43 | Angel
44 | Isaiah
45 | Evan
46 | Isaac
47 | Mason
48 | Luke
49 | Jason
50 | Gavin
51 | Jayden
52 | Aaron
53 | Connor
54 | Aiden
55 | Aidan
56 | Kyle
57 | Juan
58 | Charles
59 | Luis
60 | Adam
61 | Lucas
62 | Brian
63 | Eric
64 | Adrian
65 | Nathaniel
66 | Sean
67 | Alex
68 | Carlos
69 | Bryan
70 | Ian
71 | Owen
72 | Jesus
73 | Landon
74 | Julian
75 | Chase
76 | Cole
77 | Diego
78 | Jeremiah
79 | Steven
80 | Sebastian
81 | Xavier
82 | Timothy
83 | Carter
84 | Wyatt
85 | Brayden
86 | Blake
87 | Hayden
88 | Devin
89 | Cody
90 | Richard
91 | Seth
92 | Dominic
93 | Jaden
94 | Antonio
95 | Miguel
96 | Liam
97 | Patrick
98 | Carson
99 | Jesse
100 | Tristan
101 | Alejandro
102 | Henry
103 | Victor
104 | Trevor
105 | Bryce
106 | Jake
107 | Riley
108 | Colin
109 | Jared
110 | Jeremy
111 | Mark
112 | Caden
113 | Garrett
114 | Parker
115 | Marcus
116 | Vincent
117 | Kaleb
118 | Kaden
119 | Brady
120 | Colton
121 | Kenneth
122 | Joel
123 | Oscar
124 | Josiah
125 | Jorge
126 | Cooper
127 | Ashton
128 | Tanner
129 | Eduardo
130 | Paul
131 | Edward
132 | Ivan
133 | Preston
134 | Maxwell
135 | Alan
136 | Levi
137 | Stephen
138 | Grant
139 | Nicolas
140 | Omar
141 | Dakota
142 | Alexis
143 | George
144 | Collin
145 | Eli
146 | Spencer
147 | Gage
148 | Max
149 | Cristian
150 | Ricardo
151 | Derek
152 | Micah
153 | Brody
154 | Francisco
155 | Nolan
156 | Ayden
157 | Dalton
158 | Shane
159 | Peter
160 | Damian
161 | Jeffrey
162 | Brendan
163 | Travis
164 | Fernando
165 | Peyton
166 | Conner
167 | Andres
168 | Javier
169 | Giovanni
170 | Shawn
171 | Braden
172 | Jonah
173 | Cesar
174 | Bradley
175 | Emmanuel
176 | Manuel
177 | Edgar
178 | Erik
179 | Mario
180 | Edwin
181 | Johnathan
182 | Devon
183 | Erick
184 | Wesley
185 | Oliver
186 | Trenton
187 | Hector
188 | Malachi
189 | Jalen
190 | Raymond
191 | Gregory
192 | Abraham
193 | Elias
194 | Leonardo
195 | Sergio
196 | Donovan
197 | Colby
198 | Marco
199 | Bryson
200 | Martin
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/GirlNames.txt:
--------------------------------------------------------------------------------
1 | Emily
2 | Madison
3 | Emma
4 | Olivia
5 | Hannah
6 | Abigail
7 | Isabella
8 | Samantha
9 | Elizabeth
10 | Ashley
11 | Alexis
12 | Sarah
13 | Sophia
14 | Alyssa
15 | Grace
16 | Ava
17 | Taylor
18 | Brianna
19 | Lauren
20 | Chloe
21 | Natalie
22 | Kayla
23 | Jessica
24 | Anna
25 | Victoria
26 | Mia
27 | Hailey
28 | Sydney
29 | Jasmine
30 | Julia
31 | Morgan
32 | Destiny
33 | Rachel
34 | Ella
35 | Kaitlyn
36 | Megan
37 | Katherine
38 | Savannah
39 | Jennifer
40 | Alexandra
41 | Allison
42 | Haley
43 | Maria
44 | Kaylee
45 | Lily
46 | Makayla
47 | Brooke
48 | Mackenzie
49 | Nicole
50 | Addison
51 | Stephanie
52 | Lillian
53 | Andrea
54 | Zoe
55 | Faith
56 | Kimberly
57 | Madeline
58 | Alexa
59 | Katelyn
60 | Gabriella
61 | Gabrielle
62 | Trinity
63 | Amanda
64 | Kylie
65 | Mary
66 | Paige
67 | Riley
68 | Jenna
69 | Leah
70 | Sara
71 | Rebecca
72 | Michelle
73 | Sofia
74 | Vanessa
75 | Jordan
76 | Angelina
77 | Caroline
78 | Avery
79 | Audrey
80 | Evelyn
81 | Maya
82 | Claire
83 | Autumn
84 | Jocelyn
85 | Ariana
86 | Nevaeh
87 | Arianna
88 | Jada
89 | Bailey
90 | Brooklyn
91 | Aaliyah
92 | Amber
93 | Isabel
94 | Danielle
95 | Mariah
96 | Melanie
97 | Sierra
98 | Erin
99 | Molly
100 | Amelia
101 | Isabelle
102 | Madelyn
103 | Melissa
104 | Jacqueline
105 | Marissa
106 | Shelby
107 | Angela
108 | Leslie
109 | Katie
110 | Jade
111 | Catherine
112 | Diana
113 | Aubrey
114 | Mya
115 | Amy
116 | Briana
117 | Sophie
118 | Gabriela
119 | Breanna
120 | Gianna
121 | Kennedy
122 | Gracie
123 | Peyton
124 | Adriana
125 | Christina
126 | Courtney
127 | Daniela
128 | Kathryn
129 | Lydia
130 | Valeria
131 | Layla
132 | Alexandria
133 | Natalia
134 | Angel
135 | Laura
136 | Charlotte
137 | Margaret
138 | Cheyenne
139 | Mikayla
140 | Miranda
141 | Naomi
142 | Kelsey
143 | Payton
144 | Ana
145 | Alicia
146 | Jillian
147 | Daisy
148 | Mckenzie
149 | Ashlyn
150 | Caitlin
151 | Sabrina
152 | Summer
153 | Ruby
154 | Rylee
155 | Valerie
156 | Skylar
157 | Lindsey
158 | Kelly
159 | Genesis
160 | Zoey
161 | Eva
162 | Sadie
163 | Alexia
164 | Cassidy
165 | Kylee
166 | Kendall
167 | Jordyn
168 | Kate
169 | Jayla
170 | Karen
171 | Tiffany
172 | Cassandra
173 | Juliana
174 | Reagan
175 | Caitlyn
176 | Giselle
177 | Serenity
178 | Alondra
179 | Lucy
180 | Kiara
181 | Bianca
182 | Crystal
183 | Erica
184 | Angelica
185 | Hope
186 | Chelsea
187 | Alana
188 | Liliana
189 | Brittany
190 | Camila
191 | Makenzie
192 | Veronica
193 | Lilly
194 | Abby
195 | Jazmin
196 | Adrianna
197 | Karina
198 | Delaney
199 | Ellie
200 | Jasmin
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/USPopulation.txt:
--------------------------------------------------------------------------------
1 | 151868
2 | 153982
3 | 156393
4 | 158956
5 | 161884
6 | 165069
7 | 168088
8 | 171187
9 | 174149
10 | 177135
11 | 179979
12 | 182992
13 | 185771
14 | 188483
15 | 191141
16 | 193526
17 | 195576
18 | 197457
19 | 199399
20 | 201385
21 | 203984
22 | 206827
23 | 209284
24 | 211357
25 | 213342
26 | 215465
27 | 217563
28 | 219760
29 | 222095
30 | 224567
31 | 227225
32 | 229466
33 | 231664
34 | 233792
35 | 235825
36 | 237924
37 | 240133
38 | 242289
39 | 244499
40 | 246819
41 | 249623
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/WorldSeriesWinners.txt:
--------------------------------------------------------------------------------
1 | Boston Americans
2 | New York Giants
3 | Chicago White Sox
4 | Chicago Cubs
5 | Chicago Cubs
6 | Pittsburgh Pirates
7 | Philadelphia Athletics
8 | Philadelphia Athletics
9 | Boston Red Sox
10 | Philadelphia Athletics
11 | Boston Braves
12 | Boston Red Sox
13 | Boston Red Sox
14 | Chicago White Sox
15 | Boston Red Sox
16 | Cincinnati Reds
17 | Cleveland Indians
18 | New York Giants
19 | New York Giants
20 | New York Yankees
21 | Washington Senators
22 | Pittsburgh Pirates
23 | St. Louis Cardinals
24 | New York Yankees
25 | New York Yankees
26 | Philadelphia Athletics
27 | Philadelphia Athletics
28 | St. Louis Cardinals
29 | New York Yankees
30 | New York Giants
31 | St. Louis Cardinals
32 | Detroit Tigers
33 | New York Yankees
34 | New York Yankees
35 | New York Yankees
36 | New York Yankees
37 | Cincinnati Reds
38 | New York Yankees
39 | St. Louis Cardinals
40 | New York Yankees
41 | St. Louis Cardinals
42 | Detroit Tigers
43 | St. Louis Cardinals
44 | New York Yankees
45 | Cleveland Indians
46 | New York Yankees
47 | New York Yankees
48 | New York Yankees
49 | New York Yankees
50 | New York Yankees
51 | New York Giants
52 | Brooklyn Dodgers
53 | New York Yankees
54 | Milwaukee Braves
55 | New York Yankees
56 | Los Angeles Dodgers
57 | Pittsburgh Pirates
58 | New York Yankees
59 | New York Yankees
60 | Los Angeles Dodgers
61 | St. Louis Cardinals
62 | Los Angeles Dodgers
63 | Baltimore Orioles
64 | St. Louis Cardinals
65 | Detroit Tigers
66 | New York Mets
67 | Baltimore Orioles
68 | Pittsburgh Pirates
69 | Oakland Athletics
70 | Oakland Athletics
71 | Oakland Athletics
72 | Cincinnati Reds
73 | Cincinnati Reds
74 | New York Yankees
75 | New York Yankees
76 | Pittsburgh Pirates
77 | Philadelphia Phillies
78 | Los Angeles Dodgers
79 | St. Louis Cardinals
80 | Baltimore Orioles
81 | Detroit Tigers
82 | Kansas City Royals
83 | New York Mets
84 | Minnesota Twins
85 | Los Angeles Dodgers
86 | Oakland Athletics
87 | Cincinnati Reds
88 | Toronto Blue Jays
89 | Toronto Blue Jays
90 | Atlanta Braves
91 | New York Yankees
92 | Florida Marlins
93 | New York Yankees
94 | New York Yankees
95 | New York Yankees
96 | Arizona Diamondbacks
97 | Anaheim Angels
98 | Florida Marlins
99 | Boston Red Sox
100 | Chicago White Sox
101 | St. Louis Cardinals
102 | Boston Red Sox
103 | Philadelphia Phillies
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/accounts.txt:
--------------------------------------------------------------------------------
1 | 5069903
2 | 6542832
3 | 5369434
4 | 6105331
5 | 6786616
6 | 5580455
7 | 5154882
8 | 5949133
9 | 5700768
10 | 6104360
11 | 6977680
12 | 6486628
13 | 5329535
14 | 5139483
15 | 6685270
16 | 6786676
17 | 5292780
18 | 5485499
19 | 6498378
20 | 6523265
21 | 5624104
22 | 5382940
23 | 5185813
24 | 5582336
25 | 5458800
26 | 5779506
27 | 5593638
28 | 5448207
29 | 5444931
30 | 6903164
31 | 6028090
32 | 6878647
33 | 5305252
34 | 5906506
35 | 5102142
36 | 6790639
37 | 5361987
38 | 5410485
39 | 5399210
40 | 6041834
41 | 6896521
42 | 6788213
43 | 6311942
44 | 6765983
45 | 5652814
46 | 6086742
47 | 6197835
48 | 6490863
49 | 6851554
50 | 6525051
51 | 5754960
52 | 5458739
53 | 6720987
54 | 6386213
55 | 6344178
56 | 5863321
57 | 5902038
58 | 6467700
59 | 6106969
60 | 5389867
61 | 6954207
62 | 6530976
63 | 5323277
64 | 5132185
65 | 5692096
66 | 6214175
67 | 5276515
68 | 6136427
69 | 6610960
70 | 6148094
71 | 5212337
72 | 5308738
73 | 5902140
74 | 5201268
75 | 6439254
76 | 5186201
77 | 5832799
78 | 6771976
79 | 5822622
80 | 5571106
81 | 6955994
82 | 6117432
83 | 6768768
84 | 5934003
85 | 6849201
86 | 5554153
87 | 5605353
88 | 6490389
89 | 6568765
90 | 5105227
91 | 5820620
92 | 6956086
93 | 5254450
94 | 5963469
95 | 5966759
96 | 5877500
97 | 5605047
98 | 5762658
99 | 6887374
100 | 5457550
101 | 5992255
102 | 5242200
103 | 5187061
104 | 5282074
105 | 5673233
106 | 5716513
107 | 5738045
108 | 5633256
109 | 6197609
110 | 6516901
111 | 6393200
112 | 5230902
113 | 5269376
114 | 6973399
115 | 5131302
116 | 5048343
117 | 5156365
118 | 5151692
119 | 6487092
120 | 5114309
121 | 5074099
122 | 5881912
123 | 5669332
124 | 5323531
125 | 5219498
126 | 5513181
127 | 6213681
128 | 6913496
129 | 6548726
130 | 5419093
131 | 5467569
132 | 6715888
133 | 6067484
134 | 5221617
135 | 5982250
136 | 6083864
137 | 5361501
138 | 5575630
139 | 6365621
140 | 5798433
141 | 6173081
142 | 5792781
143 | 6855362
144 | 5795082
145 | 5610761
146 | 5209420
147 | 6591883
148 | 6898716
149 | 5645225
150 | 6827659
151 | 5763718
152 | 6065512
153 | 6061223
154 | 6901602
155 | 6168911
156 | 5904375
157 | 6487611
158 | 5506911
159 | 5338518
160 | 5832163
161 | 5557504
162 | 6803294
163 | 5374272
164 | 5119591
165 | 5116061
166 | 6313837
167 | 5703050
168 | 5354077
169 | 6254059
170 | 5226012
171 | 5239948
172 | 6579738
173 | 6538009
174 | 6112022
175 | 5165030
176 | 5110172
177 | 6144297
178 | 6537422
179 | 5266125
180 | 6780598
181 | 6405799
182 | 5217847
183 | 6516245
184 | 6200546
185 | 5231396
186 | 6863278
187 | 5228542
188 | 5898231
189 | 5565466
190 | 5081194
191 | 6078445
192 | 6245035
193 | 6334277
194 | 5002049
195 | 6489809
196 | 5900068
197 | 6085691
198 | 5995969
199 | 6361925
200 | 6795066
201 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/answers.txt:
--------------------------------------------------------------------------------
1 | A
2 | B
3 | C
4 | C
5 | D
6 | A
7 | B
8 | C
9 | D
10 | A
11 | B
12 | B
13 | B
14 | B
15 | B
16 | B
17 | C
18 | A
19 | A
20 | D
21 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/bar_chart.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 |
3 | def main():
4 | left_edges = [0, 10, 20, 30, 40]
5 | heights = [100, 200, 300, 400, 500]
6 | bar_widths = 10
7 |
8 | plt.bar(left_edges, heights, bar_widths, color=("r", "b", "y", "g", "k"))
9 |
10 | plt.title("Sales By Year")
11 | plt.xlabel("Year")
12 | plt.ylabel("Sales")
13 | plt.xticks([5, 15, 25, 35, 45], ["2016", "2017", "2018", "2019", "2020"])
14 |
15 | plt.yticks([0, 100, 200, 300, 400, 500], ["$0m", "$1m", "$2m", "$3m", "$4m", "$5m"])
16 | plt.show()
17 |
18 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/barrista_pay.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter07/ProgrammingExercises/barrista_pay.py
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/charge_acc1.py:
--------------------------------------------------------------------------------
1 | import random
2 | def main():
3 | outfile = open("accounts.txt", "w")
4 | for index in range(200):
5 | number = random.randint(5000000, 7000000)
6 | outfile.write(str(number) + "\n")
7 |
8 | outfile.close()
9 |
10 | main()
11 |
12 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/charge_acc2.py:
--------------------------------------------------------------------------------
1 | #print("hello world")
2 | def main():
3 | found = False
4 |
5 | infile = open("accounts.txt", "r")
6 | charge_account = infile.readlines()
7 |
8 | index = 0
9 | while index < len(charge_account):
10 | charge_account[index] = int(charge_account[index])
11 | index += 1
12 |
13 | infile.close()
14 | # print(charge_account)
15 | print()
16 |
17 | search = int(input("Enter an account number to search for in the list: "))
18 |
19 | if search in charge_account:
20 | print(search, "is a valid account number.")
21 | else:
22 | print(search, "is an invalid account number.")
23 |
24 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/charge_account_validation.py:
--------------------------------------------------------------------------------
1 | def main():
2 | outfile = open("charge_accounts.txt", "w")
3 | again = "y"
4 | while again == "y" or again == "Y":
5 | print("Enter a (7 digits) account number:", end="")
6 | acc = int(input())
7 | outfile.write(str(acc) + "\n")
8 |
9 | print("Add more Account Numbers? [Y/n]: ", end="")
10 | again = input()
11 |
12 | outfile.close()
13 |
14 | print("Account Numbers has been written to charge_accounts.txt.")
15 |
16 | main()
17 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/charge_account_validation2.py:
--------------------------------------------------------------------------------
1 | #print("hello world")
2 | def main():
3 | found = False
4 |
5 | infile = open("charge_accounts.txt", "r")
6 | charge_account = infile.readlines()
7 |
8 | index = 0
9 | while index < len(charge_account):
10 | charge_account[index] = int(charge_account[index])
11 | index += 1
12 |
13 | infile.close()
14 | # print(charge_account)
15 | print()
16 |
17 | search = int(input("Enter an account number to search for in the list: "))
18 |
19 | for account in charge_account:
20 | if account == search:
21 | found = True
22 |
23 | if found:
24 | print(search, "is a valid account number.")
25 | else:
26 | print(search, "is an invalid account number.")
27 |
28 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/charge_accounts.txt:
--------------------------------------------------------------------------------
1 | 5658845
2 | 4520125
3 | 7895122
4 | 8777541
5 | 8451277
6 | 1302850
7 | 8080152
8 | 4562555
9 | 5552012
10 | 5050552
11 | 7825877
12 | 1250255
13 | 1005231
14 | 6545231
15 | 3852085
16 | 7576651
17 | 7881200
18 | 4581002
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/cities.txt:
--------------------------------------------------------------------------------
1 | New York
2 | Boston
3 | Atlanta
4 | Dallas
5 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/drivers_licence_exam.py:
--------------------------------------------------------------------------------
1 | CHOICE_QST = 20
2 | PASS_MARK = 15
3 |
4 | def main():
5 | counter = 1
6 | count_correct = 0
7 | wrong_answer_list = []
8 |
9 | # Create a list for correct answers
10 | correct_answer = ["A", "C", "A", "A", "D", "B", "C", "A", "C", "B", "A", "D", "C", "A", "D", "C", "B", "B", "D", "A"]
11 |
12 | # Students answer function
13 | student_answer()
14 |
15 | # Read the student's answer to a list
16 | stud_answers_list = read_answer()
17 |
18 | # Compare correct answers with students answer to check how many questions was answered right
19 |
20 | for index in range(CHOICE_QST):
21 | if correct_answer[index] == stud_answers_list[index]:
22 | count_correct += 1
23 | else:
24 | wrong_answer_list.append(index+1)
25 |
26 | print()
27 | input("Press (Enter) to continue and check how well you've done in this exam: ")
28 | if count_correct >= PASS_MARK:
29 | print("Congratulations. You have passed this exam.")
30 | else:
31 | print("Sorry!! You failed this exam. We'll be pleased to have you back next year.")
32 |
33 | print()
34 |
35 | # Display the total number of correctly answered questions
36 | print("Correctly Answered Questions:")
37 | print("You answered", count_correct, "questions correctly.")
38 | print()
39 |
40 | # Display the total number of incorrectly answered questions
41 | print("Incorrectly Answered Questions")
42 | print("You missed", len(wrong_answer_list), "questions.")
43 | print()
44 |
45 | # Lists showing the number of incorrectly answered questions
46 |
47 | print("These are the Question numbers you missed...")
48 |
49 | for wrong in wrong_answer_list:
50 | print(wrong, end="")
51 | if counter < len(wrong_answer_list):
52 | print(end=", ")
53 | counter += 1
54 |
55 |
56 | # This section creates a list of choices that the student has picked and write them to an output file.
57 | def student_answer():
58 | # Open a file to write students answers
59 | outfile = open("answers.txt", "w")
60 |
61 | print("From choice of A to D, select appropriate answers.")
62 | print("There are 20 multiple questions...")
63 | input("Press Enter to start: ")
64 | for qst in range(CHOICE_QST):
65 | ans = input("Answer question #" + str(qst+1) + ": ").upper()
66 |
67 | # Write your answer to the file
68 | outfile.write(ans + "\n")
69 |
70 | # Close the file
71 | outfile.close()
72 |
73 |
74 | def read_answer():
75 | infile = open("answers.txt", "r")
76 | stud_ans = infile.readlines()
77 |
78 | for index in range(len(stud_ans)):
79 | stud_ans[index] = stud_ans[index].rstrip("\n")
80 |
81 | infile.close()
82 |
83 | return stud_ans
84 |
85 |
86 | main()
87 |
88 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/exm.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | names = ['Tunde', 'Bolii', 'Tomi', 'Toyosi', 'John', 'Samuel']
4 | print(names[random.randint(0, len(names)-1)])
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/expense_piechart.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 |
3 | def main():
4 | expenses = [70000, 25000, 30000, 15000, 120000, 10000]
5 | categories = ['Rent', 'Gas', 'Food', 'Clothing', 'Car Payment', 'Misc']
6 | plt.pie(expenses, labels=categories)
7 | plt.title('Expense Pie Chart')
8 | plt.show()
9 |
10 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/larger_than_n.py:
--------------------------------------------------------------------------------
1 | def main():
2 |
3 | # This is the list
4 | numbers_list = list_func()
5 | print()
6 |
7 | # Enter a number n
8 | n = int(input("Enter a number (n) to compare with larger numbers in the list: "))
9 |
10 | # This is the list of numbers greater than n
11 | larger_list = larger_than_n(n, numbers_list)
12 |
13 | # Display the numbers
14 | print("The numbers that are larger than", n, "are:")
15 | counter = 1
16 | for n_each in larger_list:
17 | print(n_each, end="")
18 | if counter < len(larger_list):
19 | print(end=", ")
20 | counter += 1
21 |
22 |
23 | def list_func():
24 | num_list = []
25 | again = "y"
26 | while again == "y":
27 | print("Enter a number to add to the list: ", end="")
28 | num = int(input())
29 | num_list.append(num)
30 |
31 | again = input("Add more numbers? [Y/n] to continue: ")
32 |
33 | return num_list
34 |
35 | def larger_than_n(num, n_list):
36 | count_large = []
37 | for number in n_list:
38 | if number > num:
39 | count_large.append(number)
40 |
41 | return count_large
42 |
43 | print()
44 |
45 | main()
46 |
47 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/line_graph.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 |
3 | def main():
4 | x_coords = [0, 1, 2, 3, 4]
5 | y_coords = [0, 3, 1, 5, 2]
6 |
7 | plt.plot(x_coords, y_coords, "D")
8 |
9 | # Add a title
10 | plt.title("Sales By Year.")
11 |
12 | # Add labels to the axis
13 | plt.xlabel("Year")
14 | plt.ylabel("Sales")
15 |
16 | # Customize the tick marks
17 | plt.xticks([0, 1, 2, 3, 4], ["2016", "2017", "2018", "2019", "2020"])
18 |
19 | plt.yticks([0, 1, 2, 3, 4, 5], ["$0m", "$1m", "$2m", "$3m", "$4m", "$5m"])
20 |
21 | # Set the axis limits
22 | #plt.xlim(xmin=-1, xmax=10)
23 | #plt.ylim(ymin=-1, ymax=6)
24 |
25 | # Add Grid
26 | plt.grid(True)
27 | plt.show()
28 |
29 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/lo_shu_magic_square.py:
--------------------------------------------------------------------------------
1 | ROWS = 3
2 | COLS = 3
3 | def main():
4 | default_list = [
5 | [0, 0, 0],
6 | [0, 0, 0],
7 | [0, 0, 0]
8 | ]
9 |
10 | # This is the magic square list
11 | magic_list = lo_shu_square(default_list)
12 |
13 | # row calculations
14 | row1 = magic_list[0][0] + magic_list[0][1] + magic_list[0][2]
15 | row2 = magic_list[1][0] + magic_list[1][1] + magic_list[1][2]
16 | row3 = magic_list[2][0] + magic_list[2][1] + magic_list[2][2]
17 |
18 | # column calculations
19 | col1 = magic_list[0][0] + magic_list[1][0] + magic_list[2][0]
20 | col2 = magic_list[0][1] + magic_list[1][1] + magic_list[2][1]
21 | col3 = magic_list[0][2] + magic_list[1][2] + magic_list[2][2]
22 |
23 | # calculations for diagonals
24 | dia1 = magic_list[0][0] + magic_list[1][1] + magic_list[2][2]
25 | dia2 = magic_list[0][2] + magic_list[1][1] + magic_list[2][0]
26 |
27 | if row1 == row2 == row3 == col1 == col2 == col3 == dia1 == dia2:
28 | print("This is a Lo Shu Magic Square.")
29 |
30 | else:
31 | print("Not A Lo Shu Magic Square.")
32 |
33 |
34 | def lo_shu_square(sqr_list):
35 | for r in range(ROWS):
36 | for c in range(COLS):
37 | sqr_list[r][c] = int(input("Enter the values for row" + str(r+1) + "," + "col" + str(c+1) + ": "))
38 |
39 | return sqr_list
40 |
41 | # print()
42 | # print(sqr_list)
43 | # print()
44 |
45 |
46 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/lottery_number_generator.py:
--------------------------------------------------------------------------------
1 | # This program is used to simulate a lottery number generator
2 |
3 | import random
4 |
5 | NUM_LOT = 7
6 |
7 | def main():
8 | # Create a list to store the random numbers
9 | lottery_list = [0] * NUM_LOT
10 |
11 | # Generate random lottery numbers in the range of 0 through 9 and save it to the lottery list
12 |
13 | for index in range(NUM_LOT):
14 | lot_num = random.randint(0, 9)
15 | lottery_list[index] = lot_num
16 |
17 | # Display the contents of the list
18 | print("Here is the lists of the lottery numbers generated:")
19 | for rand_num in lottery_list:
20 | print(rand_num)
21 |
22 | main()
23 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/magic8_ball_file.py:
--------------------------------------------------------------------------------
1 | def main():
2 | outfile = open('8_ball_responses.txt', 'w')
3 | for index in range(12):
4 | response = input('Enter the response #' + str(index+1) + ': ')
5 | outfile.write(response + '\n')
6 |
7 | outfile.close()
8 |
9 | print('The 12 responses has been written to 8_ball_responses.txt.')
10 |
11 | main()
12 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/magic_8ball.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | def main():
4 | infile = open('8_ball_responses.txt', 'r')
5 | response_list = infile.readlines()
6 |
7 | for index in range(len(response_list)):
8 | response_list[index] = response_list[index].rstrip('\n')
9 |
10 | print()
11 | again = 'y'
12 | while again == 'y' or again == 'Y':
13 | print('Ask your question and get an answer', end='')
14 |
15 | qst = input(': ')
16 | print(response_list[random.randint(0, len(response_list)-1)])
17 |
18 | print()
19 | print('Ask more questions?')
20 | again = input('[Y/n] to continue: ')
21 |
22 | main()
23 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/name_search.py:
--------------------------------------------------------------------------------
1 | # This program reads the contents of BoyNames.txt and GirlNames.txt
2 | # into a list separately,
3 |
4 | def main():
5 | # Open a file for bith boys and girls in read mode
6 | boy_file = open('BoyNames.txt', 'r')
7 | girl_file = open('GirlNames.txt', 'r')
8 |
9 | # Read the contents of the file to a list
10 | boys_list = boy_file.readlines()
11 | girls_list = girl_file.readlines()
12 |
13 | # This is the list of boy names
14 | boy_names = boy_func(boys_list)
15 |
16 | # This is the list of girls names
17 | girl_names = girl_func(girls_list)
18 |
19 | user_func(boy_names, girl_names)
20 |
21 |
22 | def boy_func(boys):
23 | for index in range(len(boys)):
24 | boys[index] = boys[index].rstrip('\n')
25 |
26 | return boys
27 |
28 |
29 | def girl_func(girls):
30 | for index in range(len(girls)):
31 | girls[index] = girls[index].rstrip('\n')
32 |
33 | return girls
34 |
35 |
36 | # Function to perform the operation
37 | def user_func(boy_names, girl_names):
38 | name = input('Enter a name(Boy name or Girl name): ')
39 | if name in boy_names or name in girl_names:
40 | print(name, 'is among the most popular names.')
41 | else:
42 | print(name, 'was not found.')
43 |
44 |
45 | main()
46 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/number_analysis.py:
--------------------------------------------------------------------------------
1 | total = 0
2 | num_list = []
3 | print("Enter a series of 20 numbers:")
4 | for index in range(20):
5 | num = int(input("Number #" + str(index+1) + ": "))
6 | num_list.append(num)
7 |
8 | min_num = min(num_list)
9 | max_num = max(num_list)
10 |
11 | for number in num_list:
12 | total += number
13 |
14 | avg = total / len(num_list)
15 |
16 | print()
17 | print("The Lowest Number In The List Is:", min_num)
18 | print("The Highest Number In The List Is:", max_num)
19 | print("The Total Of The Numbers In The List Is:", total)
20 | print("The Average Of All The Numbers In The List Is:", avg)
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/numberlist.txt:
--------------------------------------------------------------------------------
1 | 1
2 | 2
3 | 3
4 | 4
5 | 5
6 | 6
7 | 7
8 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/population.txt:
--------------------------------------------------------------------------------
1 | 253671
2 | 326956
3 | 182933
4 | 317528
5 | 271190
6 | 285783
7 | 323030
8 | 338707
9 | 174682
10 | 311542
11 | 214344
12 | 215400
13 | 243219
14 | 333559
15 | 267892
16 | 253341
17 | 289788
18 | 299872
19 | 160568
20 | 349282
21 | 234353
22 | 196922
23 | 252758
24 | 300473
25 | 180405
26 | 172766
27 | 190014
28 | 221320
29 | 293154
30 | 246268
31 | 231182
32 | 345009
33 | 333842
34 | 254943
35 | 163466
36 | 304447
37 | 293476
38 | 319420
39 | 171223
40 | 159070
41 | 286552
42 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/population_data.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | MIN = 1950
4 | MAX = 1990
5 |
6 | def main():
7 |
8 | outfile = open("population.txt", "w")
9 |
10 | for index in range(MIN, MAX+1):
11 | num_pop = random.randint(150000, 350000)
12 | outfile.write(str(num_pop) + "\n")
13 |
14 | outfile.close()
15 | print("Populations number has been written to population.txt.")
16 |
17 | main()
18 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/prime_number_generator.py:
--------------------------------------------------------------------------------
1 | def main():
2 | number = int(input("Enter a number: "))
3 | is_prime = prime_numbers(number)
4 |
5 | print("Check which of the numbers between 2 and", number, "are (prime) and which are (composites))")
6 | print(is_prime)
7 |
8 | print()
9 | for index in is_prime:
10 | res = prime(index)
11 |
12 | if res:
13 | print(index, "is a prime number.")
14 | else:
15 | print(index, "is a composite number.")
16 |
17 |
18 | def prime_numbers(number):
19 | count = 0
20 | prime_list = []
21 | for num in range(2, number+1):
22 | prime_list.append(num)
23 |
24 | return prime_list
25 |
26 |
27 | def prime(prime_num):
28 | count = 0
29 | for i in range(2, prime_num):
30 | if prime_num % i == 0:
31 | count += 1
32 |
33 | if count == 0:
34 | return True
35 | else:
36 | return False
37 |
38 |
39 | main()
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/rainfall_statistics.py:
--------------------------------------------------------------------------------
1 | # This program calculates and display total rainfall for the year, the average monthly rainfall, months with highest rainfall, months with lowest rainfall
2 |
3 | MONTHS_TOT = 12
4 |
5 | def main():
6 | total = 0.0
7 |
8 | rainfall_monthly_list = [0] * MONTHS_TOT
9 |
10 | for index in range(MONTHS_TOT):
11 | print("Enter the amount of rainfall for month #", index+1, ": ", sep="", end="")
12 | amount = float(input())
13 | rainfall_monthly_list[index] = amount
14 |
15 | print()
16 | # calculate the total rainfall
17 | for val in rainfall_monthly_list:
18 | total += val
19 |
20 | print("The total annual rainfall is:", format(total, ",.2f"))
21 |
22 | print()
23 | # calculate the average rainfall
24 | avg = total / MONTHS_TOT
25 | print("The average monthly rainfall is:", format(avg, ",.2f"))
26 |
27 | print()
28 | # month with maximum rainfall
29 | max_rainfall = max(rainfall_monthly_list)
30 |
31 | # month with minimum rainfall
32 | min_rainfall = min(rainfall_monthly_list)
33 |
34 | print()
35 | for index in range(MONTHS_TOT):
36 | if rainfall_monthly_list[index] == max_rainfall:
37 | print("The month with maximum amount of rainfall is: Month", index+1)
38 | print("Maximum Rainfall:", max_rainfall)
39 | print()
40 | elif rainfall_monthly_list[index] == min_rainfall:
41 | print("The month with minimum amount of rainfall is: Month", index+1)
42 | print("Minimum Rainfall:", min_rainfall)
43 | print()
44 |
45 | main()
46 |
47 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/random_functions.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | random.random()
4 | random.randint(1, 5)
5 | random.randrange(1, 10, 2)
6 | random.shuffle([12, 34, 56, 60])
7 | random.choice([1, 2, 3, 4, 5])
8 | random.sample("abcdefghijklmnopqrstuvwxyz", 15)
9 |
10 |
11 | num_str = random.sample("abcdefghijklmnopqrstuvwxyz1234567890", 15)
12 | num_str = "".join([i for i in num_str])
13 | print(num_str)
14 | print()
15 | for let in num_str:
16 | print(let, end="")
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/read_pop_data.py:
--------------------------------------------------------------------------------
1 | MIN = 1950
2 | MAX = 1990
3 |
4 | def main():
5 | total = 0
6 | infile = open("USPopulation.txt", "r")
7 | pop_list = infile.readlines()
8 |
9 | for index in range(len(pop_list)):
10 | pop_list[index] = int(pop_list[index])
11 |
12 | #print()
13 | for pop in pop_list:
14 | total += pop
15 |
16 | avg_pop = total / len(pop_list)
17 | max_pop = max(pop_list)
18 | min_pop = min(pop_list)
19 |
20 | print("Total Annual Population Is: ", format(total, ",.1f"))
21 |
22 | print("Average Yearly Population Is: ", format(avg_pop, ",.1f"), sep="")
23 |
24 | index = 1950
25 | for count in range(len(pop_list)):
26 | if pop_list[count] == max_pop:
27 | print("The year with greatest increase in population is:", index)
28 | elif pop_list[count] == min_pop:
29 | print("The year with lowest increase in population is:", index)
30 | index += 1
31 |
32 | main()
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/sales_list.py:
--------------------------------------------------------------------------------
1 | NUM_DAYS = 5
2 |
3 | def main():
4 | sales = [0] * NUM_DAYS
5 |
6 | index = 0
7 | print("Enter the sales for each day.")
8 | while index < NUM_DAYS:
9 | print("Day #", index+1, ": ", sep="", end="")
10 | sales[index] = float(input())
11 | index += 1
12 |
13 | print("Here are the values you entered:")
14 | for value in sales:
15 | print(value)
16 |
17 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/total_sales.py:
--------------------------------------------------------------------------------
1 | # This program asks the user to enter amount of a store's sale for each day of the week, and stored in a list
2 |
3 | NUM_WEEK_DAYS = 7
4 |
5 | def main():
6 | total = 0.0
7 |
8 | # create a list for sales
9 | sales_list = [0] * NUM_WEEK_DAYS
10 |
11 | # Enter amount of sales
12 | for index in range(NUM_WEEK_DAYS):
13 | print("Enter sales for day #", index+1, ": ", sep="", end="")
14 | sales_list[index] = float(input())
15 |
16 | print()
17 | # Calculate the total sales
18 | for sale in sales_list:
19 | total += sale
20 |
21 | print(f"Total Sales For The Week Is: ${total:,.2f}.")
22 |
23 | # call the main function
24 | main()
25 |
26 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter07/ProgrammingExercises/world_series_champions.py:
--------------------------------------------------------------------------------
1 | def main():
2 | count = 0
3 | infile = open('WorldSeriesWinners.txt', 'r')
4 | winners_list = infile.readlines()
5 |
6 | for index in range(len(winners_list)):
7 | winners_list[index] = winners_list[index].rstrip('\n')
8 |
9 | search = input('Enter a team\'s name and know how\nmany World Series she has won: ')
10 | print()
11 |
12 | start_year = 2010
13 | start_list = []
14 |
15 | # for name in winners_list:
16 | # if name == search:
17 | # count += 1
18 | # start_year -= 1
19 | # start_list.append(start_year)
20 |
21 | for index in range(len(winners_list)):
22 | start_year -= 1
23 | if winners_list[index] == search:
24 | count += 1
25 | if start_year == 1904 or start_year == 1994:
26 | break
27 | start_list.append(start_year)
28 |
29 |
30 |
31 | print(search.upper(), 'has won World Series Championship', count, 'time(s).')
32 | print('The years list:', start_list)
33 |
34 | main()
35 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/Examples/__pycache__/login.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter08/Examples/__pycache__/login.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/Examples/generate_login.py:
--------------------------------------------------------------------------------
1 | import login
2 |
3 | def main():
4 | again = 'y'
5 | while again == 'y' or again == 'Y':
6 | first_name = input('Enter your first name: ')
7 | last_name = input('Enter your last name: ')
8 | id_number = input('Enter your student ID number: ')
9 |
10 | # print('Your system login name is:')
11 | password = login.get_login_name(first_name, last_name, id_number)
12 |
13 | while not
14 |
15 | if login.validate_password(password):
16 | print('Welcome. Login Successful!!!')
17 | else:
18 | print('Invalid password.')
19 | again = input('Start the process again: ')
20 |
21 | # print()
22 |
23 | # print('Enter your password: ')
24 | # password = input()
25 | # while not login.validate_password(password):
26 | # print('Enter a valid password!')
27 | # password = input(': ')
28 |
29 | # print('Welcome, your login is successful.')
30 |
31 |
32 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/Examples/login.py:
--------------------------------------------------------------------------------
1 | # Define a get login function with first name, last name
2 | # and id number characters
3 |
4 | def get_login_name(first, last, idnumber):
5 | set1 = first[0:3]
6 | set2 = last[0:3]
7 | set3 = idnumber[-3:]
8 |
9 | # Concatenate the three datas
10 | login_name = set1 + set2 + set3
11 |
12 | return login_name
13 |
14 |
15 | def validate_password(password):
16 | has_correct_length = False
17 | has_uppercase = False
18 | has_lowercase = False
19 | has_digit = False
20 |
21 | if len(password) >= 7:
22 | has_correct_length = True
23 |
24 | for ch in password:
25 | if ch.isupper():
26 | has_uppercase = True
27 | if ch.islower():
28 | has_lowercase = True
29 | if ch.isdigit():
30 | has_digit = True
31 |
32 | if has_correct_length and has_uppercase and has_lowercase and has_digit:
33 | is_valid = True
34 | else:
35 | is_valid = False
36 | return is_valid
37 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/average_no_of_words.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('text.txt', 'r')
3 | text_list = infile.readlines()
4 |
5 | for index in range(len(text_list)):
6 | text_list[index] = text_list[index].rstrip('\n')
7 |
8 | # print(text_list)
9 |
10 | item_length = []
11 |
12 | for items in text_list:
13 | count_s = perf_funct(items)
14 | item_length.append(count_s)
15 |
16 | # This is the list of the lengths of all words
17 | # print(item_length)
18 | total = 0
19 | for str_num in item_length:
20 | total += int(str_num)
21 | print('Total Number of words:', total)
22 |
23 | avg = total / len(item_length)
24 | print('Average Number of words:', avg)
25 |
26 | # Calculate the average word
27 |
28 | # print(text_list[2].split())
29 |
30 | def perf_funct(items):
31 | count = 0
32 | split_text = items.split()
33 | for item in split_text:
34 | count += 1
35 | return count
36 |
37 |
38 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/character_analysis.py:
--------------------------------------------------------------------------------
1 |
2 |
3 | def main():
4 | infile = open('text.txt', 'r')
5 | text = infile.read()
6 | infile.close()
7 | # print(text)
8 |
9 | str_text(text)
10 | print('Total Letters:', len(text))
11 |
12 |
13 | def str_text(read_text):
14 | count_upper = 0
15 | count_lower = 0
16 | count_digit = 0
17 | count_space = 0
18 |
19 | for ch in read_text:
20 | if ch.isupper():
21 | count_upper += 1
22 | elif ch.islower():
23 | count_lower += 1
24 | elif ch.isdigit():
25 | count_digit += 1
26 | elif ch.isspace():
27 | count_space += 1
28 | print('Uppercase Letters:', count_upper)
29 | print('Lowercase Letters:', count_lower)
30 | print('Digits:', count_digit)
31 | print('Space:', count_space)
32 |
33 | total_letters = count_upper + count_lower
34 | # print('Total Letters 2nd Method:', total_letters)
35 |
36 | print()
37 |
38 |
39 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/date_printer.py:
--------------------------------------------------------------------------------
1 | def main():
2 | date_str = input('Enter a date in the form (mm/dd/yyyy) : ')
3 | date_split = date_str.split('/')
4 |
5 | date_val = get_date(date_split)
6 | print(f'The date is: {date_val} {date_split[1]}, {date_split[2]}')
7 |
8 | # print(date_split)
9 |
10 | def get_date(date_split):
11 |
12 | if date_split[0] == '01':
13 | val = 'January'
14 | elif date_split[0] == '02':
15 | val = 'February'
16 | elif date_split[0] == '03':
17 | val = 'March'
18 | elif date_split[0] == '04':
19 | val = 'April'
20 | elif date_split[0] == '05':
21 | val = 'May'
22 | elif date_split[0] == '06':
23 | val = 'June'
24 | elif date_split[0] == '07':
25 | val = 'July'
26 | elif date_split[0] == '08':
27 | val = 'August'
28 | elif date_split[0] == '09':
29 | val = 'Seotempber'
30 | elif date_split[0] == '10':
31 | val = 'Octomber'
32 | elif date_split[0] == '11':
33 | val = 'November'
34 | elif date_split[0] == '12':
35 | val = 'December'
36 | return val
37 |
38 |
39 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/exm.py:
--------------------------------------------------------------------------------
1 | # def main():
2 | # outfile = open('try.txt', 'r')
3 | # for item in outfile:
4 | # ph = item.split()
5 | # print(ph)
6 | # # item = outfile.read()
7 | # # split_item = item.split()
8 | # # print(item)
9 | # # print(split_item)
10 | # # for items in outfile:
11 | # # # sp = items.split()
12 | # # print(items)
13 |
14 | # outfile.close()
15 |
16 | # main()
17 |
18 | # # name = [
19 | # # [1, 2, 3, 'tunde', {'age':29}, 'a', 'b', 'c']
20 | # # ]
21 | # # print(len(name))
22 |
23 | # nums = [1, 3, 150, 200, 3, 4, 3, 5, 5 , 7, 15, 8, 10, 9, 9, 11, 20, 30, 40, 50, 60, 90, 100, 80, 50]
24 | # maxx = list(set(nums))
25 | # # print(new)
26 | # # for item in new:
27 | # # print(item)
28 |
29 | # for i in range(-10, 0):
30 | # max_num = sorted(maxx)[i]
31 | # print(max_num)
32 |
33 |
34 | # num_list = []
35 | # numbers = '1 2 3 4 5 6 7'
36 | # split_num = numbers.split()
37 | # print(split_num)
38 |
39 | # for num in split_num:
40 | # num_list += num
41 | # print(num_list)
42 |
43 | # lists = []
44 | list1 = ['61', '61', '08', '61', '01', '26']
45 |
46 | list2 = ['60', '22', '31', '50', '14', '12']
47 | list3 = list1[:]
48 | print(list3)
49 | # list1 = [list2[3]]
50 | # print(list1)
51 | # list1.append(10)
52 | # print(list1)
53 | # for i in range(3):
54 | # if list1[0] == '61':
55 | # print('Yes')
56 | # elif list1[2] == '09':
57 | # print('Yes')
58 | # elif list1[1] == '6':
59 | # print('Yes')
60 | # else:
61 | # print('No')
62 |
63 | # lists += list1
64 | # lists += list2
65 | # print(lists)
66 | # list3 = list1 + list2
67 | # print(list3)
68 |
69 | # year = ''
70 | # month = ''
71 | # for i in range(3):
72 | # if year == '':
73 | # val = 'yes'
74 | # # print('yes')
75 | # elif month == '':
76 | # val = 'true'
77 | # # print('true')
78 | # elif year == '' and month == '':
79 | # val = 'valid'
80 |
81 | # else:
82 | # val = 'No'
83 | # print(val)
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/gas_prices.py:
--------------------------------------------------------------------------------
1 | def main():
2 | # open GasPrices.txt in read mode
3 | infile = open('GasPrices.txt', 'r')
4 |
5 | # Read the contents of the file into a list
6 | gas_list = infile.readlines()
7 | # print(gas_list)
8 |
9 | # strip \n from the list
10 | price = []
11 | date = []
12 | month = []
13 | day = []
14 | year = []
15 |
16 | for i in range(len(gas_list)):
17 | gas_list[i] = gas_list[i].rstrip('\n')
18 | gas_list[i] = gas_list[i].split(':')
19 | price.append(gas_list[i][1])
20 | date.append(gas_list[i][0])
21 | date[i] = date[i].split('-')
22 | month.append(date[i][0])
23 | day.append(date[i][1])
24 | year.append(date[i][2])
25 |
26 | infile.close()
27 |
28 | average_price(year, price, date)
29 | sorted_price(gas_list, price)
30 |
31 | # print(gas_list)
32 |
33 |
34 | def average_price(year, price, date):
35 | yearly_total = 0
36 | year_list = list(set(year))
37 | year_list.sort()
38 | yt_list = []
39 |
40 | for item in year_list:
41 | for i in range(len(year)):
42 | if year[i] == item:
43 | yearly_total += float(price[i])
44 | yt_list.append(yearly_total)
45 | yearly_total = 0
46 |
47 | total = 0
48 | for item in yt_list:
49 | total += item
50 | avg = format(total / len(yt_list), '.3f')
51 | avg_month = format((float(avg) / 12), '.3f')
52 |
53 | min_price = price.index(min(price))
54 | max_price = price.index(max(price))
55 |
56 | min_date = date[min_price]
57 | max_date = date[max_price]
58 |
59 | # print(min_date)
60 | # print(max_date)
61 |
62 | print('The average price of gas per year is $ ', avg, sep='')
63 | print('The average price of gas per month is $ ', avg_month, sep='')
64 | print(f'Minimum gas price is ${min(price)}, on {min_date[0]}-{min_date[1]}-{min_date[2]}')
65 | print(f'Maximum gas price is ${max(price)}, on {max_date[0]}-{max_date[1]}-{max_date[2]}')
66 |
67 | print()
68 |
69 |
70 | def sorted_price(date, price):
71 | # print(date)
72 | date1 = date
73 | for i in range(len(date1)):
74 | # date1.sort()
75 | # print(date1)
76 | date1[i][0], date1[i][1] = date1[i][1], date1[i][0]
77 | date1.sort()
78 | print(date1)
79 | date2 = date1[-1::-1] # From highest to lowest
80 | # print(date2)
81 | outfile1 = open('gas_lowest.txt', 'w')
82 | outfile2 = open('gas_highest.txt', 'w')
83 |
84 | # Write datas to file
85 | for item in date1:
86 | dt = item[1]
87 | pr = item[0]
88 | outfile1.write(str(dt) + ' ' + str(pr) + '\n')
89 |
90 | for item in date2:
91 | dt = item[1]
92 | pr = item[0]
93 | outfile2.write(str(dt) + ' ' + str(pr) + '\n')
94 |
95 | outfile1.close()
96 | outfile2.close()
97 |
98 | print('Datas has been successfully written to gas_lowest.txt')
99 | print('and gas_highest.txt.')
100 |
101 |
102 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/initials.py:
--------------------------------------------------------------------------------
1 | # This program gets a person first, middle and last names
2 | # and displays their first, middle and last initials
3 |
4 | def main():
5 | first = input('Enter your first name: ')
6 | middle = input('Enter your middle name: ')
7 | last = input('Enter your last name: ')
8 |
9 | my_initials = get_initials(first, middle, last)
10 | print('Your initials is: ', end='')
11 | print(my_initials)
12 |
13 |
14 | def get_initials(first_name, middle_name, last_name):
15 | set1 = first_name[0]
16 | set2 = middle_name[0]
17 | set3 = last_name[0]
18 |
19 | initials = set1 + '.' + set2 + '.' + set3
20 | return initials
21 |
22 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/morse_code.py:
--------------------------------------------------------------------------------
1 | def main():
2 | input_str = input('Enter a string and see its morse code: ')
3 |
4 | for char in input_str:
5 | result = test_str(char)
6 | print(result, end='')
7 |
8 | def test_str(ch):
9 | if ch == ' ':
10 | return 'space'
11 | elif ch == ',':
12 | return '--..--'
13 | elif ch == '.':
14 | return '.-.-.-'
15 | elif ch == '?':
16 | return '..--..'
17 | elif ch == '0':
18 | return '-----'
19 | elif ch == '1':
20 | return '.----'
21 | elif ch == '2':
22 | return '..---'
23 | elif ch == '3':
24 | return '...--'
25 | elif ch == '4':
26 | return '....-'
27 | elif ch == '5':
28 | return '.....'
29 | elif ch == '6':
30 | return '-....'
31 | elif ch == '7':
32 | return '--...'
33 | elif ch == '8':
34 | return '---..'
35 | elif ch == '9':
36 | return '----.'
37 | elif ch.upper() == 'A':
38 | return '.-'
39 | elif ch.upper() == 'B':
40 | return '-...'
41 | elif ch.upper() == 'C':
42 | return '-.-.'
43 | elif ch.upper() == 'D':
44 | return '-..'
45 | elif ch.upper() == 'E':
46 | return '.'
47 | elif ch.upper() == 'F':
48 | return '..-.'
49 | elif ch.upper() == 'G':
50 | return '--.'
51 | elif ch.upper() == 'H':
52 | return '....'
53 | elif ch.upper() == 'I':
54 | return '..'
55 | elif ch.upper() == 'J':
56 | return '.---'
57 | elif ch.upper() == 'K':
58 | return '-.-'
59 | elif ch.upper() == 'L':
60 | return '.-..'
61 | elif ch.upper() == 'M':
62 | return '--.'
63 | elif ch.upper() == 'N':
64 | return '-.'
65 | elif ch.upper() == 'O':
66 | return '---'
67 | elif ch.upper() == 'P':
68 | return '.--.'
69 | elif ch.upper() == 'Q':
70 | return '--.-'
71 | elif ch.upper() == 'R':
72 | return '.-.'
73 | elif ch.upper() == 'S':
74 | return '...'
75 | elif ch.upper() == 'T':
76 | return '-'
77 | elif ch.upper() == 'U':
78 | return '..-'
79 | elif ch.upper() == 'V':
80 | return '...-'
81 | elif ch.upper() == 'W':
82 | return '.--'
83 | elif ch.upper() == 'X':
84 | return '-..-'
85 | elif ch.upper() == 'Y':
86 | return '-.-'
87 | elif ch.upper() == 'Z':
88 | return '--..'
89 |
90 | main()
91 |
92 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/most_frequent.py:
--------------------------------------------------------------------------------
1 | def main():
2 | user_str = input('Enter a string: ')
3 |
4 | frequent = most_frquent(user_str)
5 | print('Most Frequent Character Is:', frequent.upper())
6 |
7 |
8 | def most_frquent(user_str):
9 | index = 0
10 | alphs = 'abcdefghijklmnopqrstuvwxyz'
11 | add_alphs = [0] * len(alphs)
12 |
13 | for ch in alphs:
14 | word_count = user_str.count(ch)
15 | add_alphs[index] += word_count
16 | index += 1
17 |
18 | most_frequent = max(add_alphs)
19 | freq_index = add_alphs.index(most_frequent)
20 | result = alphs[freq_index]
21 |
22 | return result
23 |
24 | main()
25 |
26 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/mypbnumbers.txt:
--------------------------------------------------------------------------------
1 | 16 58 25 9 54 17
2 | 33 22 59 47 43 5
3 | 25 66 17 54 40 2
4 | 9 25 46 9 31 17
5 | 28 59 9 33 24 5
6 | 45 23 11 56 67 5
7 | 59 35 10 50 41 4
8 | 43 31 43 30 16 19
9 | 65 24 60 68 35 12
10 | 58 7 41 61 53 10
11 | 7 41 37 55 19 1
12 | 59 60 28 43 24 25
13 | 39 60 36 54 58 25
14 | 14 25 19 36 39 20
15 | 14 47 5 15 38 9
16 | 36 8 9 35 19 16
17 | 12 41 32 21 9 22
18 | 6 41 14 5 25 25
19 | 49 14 59 67 41 6
20 | 68 36 57 26 14 23
21 | 4 43 38 8 47 2
22 | 44 27 34 21 63 13
23 | 49 42 21 12 61 16
24 | 4 4 2 63 24 21
25 | 43 9 47 39 61 10
26 | 18 54 66 37 45 25
27 | 45 31 68 11 44 13
28 | 45 59 26 66 54 7
29 | 13 32 52 44 25 25
30 | 61 33 45 10 4 11
31 | 32 5 65 8 49 2
32 | 49 8 15 42 29 15
33 | 24 34 56 65 18 23
34 | 6 2 43 41 66 10
35 | 60 50 53 6 39 5
36 | 15 2 19 44 33 9
37 | 22 2 23 28 29 7
38 | 52 4 49 62 18 22
39 | 6 66 43 45 51 6
40 | 1 5 11 40 69 14
41 | 47 43 28 5 25 10
42 | 55 31 2 42 55 23
43 | 20 63 66 34 20 22
44 | 6 39 16 11 25 24
45 | 63 40 66 16 9 1
46 | 44 44 17 45 27 5
47 | 40 42 19 34 6 24
48 | 6 3 41 39 27 19
49 | 41 1 68 49 41 11
50 | 60 55 40 55 22 22
51 | 63 15 15 52 26 11
52 | 68 54 68 40 57 16
53 | 49 45 40 31 28 14
54 | 12 56 28 30 66 22
55 | 1 26 69 67 61 23
56 | 28 21 49 35 67 6
57 | 36 68 18 50 39 6
58 | 50 55 31 7 31 20
59 | 21 5 48 44 46 6
60 | 52 21 45 28 25 24
61 | 42 41 52 19 4 14
62 | 52 21 58 54 48 14
63 | 36 19 5 24 21 13
64 | 13 66 27 35 26 8
65 | 43 62 64 7 33 18
66 | 47 43 53 1 29 11
67 | 23 33 32 19 25 24
68 | 12 48 8 11 20 2
69 | 32 49 14 15 19 10
70 | 57 11 63 58 29 6
71 | 8 8 28 22 16 16
72 | 54 16 57 61 46 1
73 | 24 27 56 46 31 23
74 | 50 48 38 9 61 22
75 | 34 33 43 57 52 17
76 | 60 14 57 17 55 10
77 | 63 24 32 46 48 20
78 | 63 20 19 44 8 21
79 | 2 34 44 40 52 17
80 | 63 30 23 4 2 12
81 | 22 21 22 56 34 21
82 | 38 42 17 13 57 19
83 | 9 58 39 39 38 22
84 | 43 43 59 54 64 16
85 | 7 38 31 35 21 8
86 | 55 52 43 20 53 1
87 | 66 24 3 46 37 13
88 | 61 18 52 38 46 4
89 | 10 49 8 8 32 15
90 | 15 23 38 68 18 15
91 | 53 26 62 38 38 2
92 | 1 34 27 44 64 16
93 | 49 33 12 6 25 26
94 | 54 26 48 35 5 8
95 | 57 49 42 13 44 1
96 | 59 22 59 48 6 2
97 | 34 60 36 50 52 22
98 | 51 62 6 55 65 13
99 | 14 24 44 48 10 5
100 | 41 13 53 53 36 14
101 | 25 47 4 10 24 16
102 | 7 68 5 39 18 3
103 | 7 52 41 27 65 16
104 | 48 19 18 2 20 25
105 | 13 49 8 37 50 2
106 | 37 23 55 54 25 3
107 | 39 41 41 28 53 21
108 | 13 48 47 43 29 14
109 | 40 50 5 16 64 18
110 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/powerball_lottery.py:
--------------------------------------------------------------------------------
1 | # import random
2 |
3 | # # This program writes random numbers to a file
4 | # def main():
5 | # # Open mypbnumbers.txt
6 | # outfile = open('mypbnumbers.txt', 'w')
7 | # for n in range(109):
8 | # pb_num = random.randint(1, 26)
9 | # for pb in range(6):
10 | # num = random.randint(1, 69)
11 | # if pb != 5:
12 | # outfile.write(str(num) + ' ')
13 | # else:
14 | # outfile.write(str(pb_num) + '\n')
15 |
16 | # outfile.close()
17 |
18 | # main()
19 |
20 |
21 | def main():
22 | most_num, most_pb, num1 = get_number_list()
23 | least_num, least_pb, num2 = get_number_list()
24 | most_over, pb_over, num3 = get_number_list()
25 | num_freq, pb_freq, num4 = get_number_list()
26 |
27 | print('The most 10 common numbers are: ')
28 |
29 | print(most_common_number(most_num))
30 |
31 | print('The least 10 common numbers are: ')
32 | print(least_common_number(most_num))
33 |
34 | print('The 10 most overdue numbers are: ')
35 | print(most_overdue_numbers(most_over))
36 |
37 | # Number frequencies
38 | print(frequency(num4))
39 | print()
40 | print()
41 |
42 | # Pb frequencies
43 | print(frequency(pb_freq))
44 |
45 |
46 | def get_number_list():
47 | infile = open('mypbnumbers.txt', 'r')
48 |
49 | new_list = []
50 | pb_numbers = []
51 | numbers = []
52 | num = []
53 |
54 | for item in infile:
55 | # print(item)
56 | ph = item.split()
57 | # print(ph)
58 | new_list.append(ph)
59 |
60 | infile.close()
61 | # print(new_list)
62 | # print(len(new_list))
63 |
64 | for r in range(len(new_list)):
65 | for c in range(6):
66 | numbers.append(new_list[r][c])
67 | if c != 5:
68 | num.append(new_list[r][c])
69 |
70 | pb_numbers.append(new_list[r][-1])
71 |
72 | # print(pb_numbers)
73 | # print()
74 | # print(numbers)
75 | # print()
76 | # print(num)
77 |
78 | return numbers, pb_numbers, num
79 |
80 |
81 | def most_common_number(numbers):
82 | counter = 0
83 | # set function returns a dictionary and removes all duplictes
84 | # So we have to convert back to list with a list function
85 | new = list(set(numbers))
86 | count_list = []
87 | new_list = []
88 |
89 | for item in new:
90 | count = numbers.count(item)
91 | count_list.append(count)
92 |
93 | maxx = list(set(count_list))
94 | for i in range(-10, 0):
95 | max_num = sorted(maxx)[i]
96 | index = count_list.index(max_num)
97 | index_new = new[index]
98 | new_list.append(index_new)
99 |
100 | new_list.reverse()
101 |
102 | return new_list
103 |
104 |
105 | def least_common_number(numbers):
106 | counter = 0
107 | new = list(set(numbers))
108 | count_list = []
109 | new_list = []
110 |
111 | for item in new:
112 | count = numbers.count(item)
113 | count_list.append(count)
114 |
115 | maxx = list(set(count_list))
116 | for i in range(10):
117 | max_num = sorted(maxx)[i]
118 | index = count_list.index(max_num)
119 | index_new = new[index]
120 | new_list.append(index_new)
121 |
122 | return new_list
123 |
124 |
125 | def most_overdue_numbers(numbers):
126 | new_list = []
127 | for i in range(-10, 0):
128 | max_num = numbers[i]
129 | new_list.append(max_num)
130 |
131 | new_list.reverse()
132 | return new_list
133 |
134 |
135 | def frequency(numbers):
136 | new = list(set(numbers))
137 |
138 | count_list = []
139 | new_list = []
140 | for item in new:
141 | count = numbers.count(item)
142 | count_list.append(count)
143 |
144 | print('number\tfrequecy')
145 | for index in range(len(new)):
146 | print(new[index], '\t', count_list[index])
147 |
148 | main()
149 |
150 |
151 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/sentence_capitalizer.py:
--------------------------------------------------------------------------------
1 | def main():
2 | user_str = input('Enter a string to convert: ')
3 | split_str = user_str.split()
4 |
5 | for item in split_str:
6 | res = perf_funct(item)
7 | print(res, end='')
8 |
9 |
10 | def perf_funct(split_word):
11 | set1 = split_word[0].upper()
12 | set2 = split_word[1:] + ' '
13 | return set1 + set2
14 |
15 | main()
16 |
17 |
18 | # Shina's code
19 | # def main():
20 | # # Ask user to enter a sentence
21 | # word = input('Please enter a sentence: ')
22 | # print(sentence(word))
23 |
24 | # def sentence(word):
25 | # first = word[0].upper()
26 | # last = word[1:]
27 | # upper_word = first + last
28 | # return upper_word
29 |
30 | # main()
31 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/sumofdigits_inastring.py:
--------------------------------------------------------------------------------
1 | # This program asks the user to enter a string
2 | # and displays the sum, eg 2514 = 12
3 |
4 |
5 | def main():
6 | total = 0
7 | num_str = input('Enter a series of single digit number: ')
8 |
9 | for ch in num_str:
10 | if ch.isdigit():
11 | total += int(ch)
12 |
13 | print('Total is:', total)
14 |
15 | main()
16 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/text.txt:
--------------------------------------------------------------------------------
1 | No one is unaware of the name of that famous English shipowner, Cunard.
2 | In 1840 this shrewd industrialist founded a postal service between Liverpool and Halifax, featuring three wooden ships with 400-horsepower paddle wheels and a burden of 1,162 metric tons.
3 | Eight years later, the company's assets were increased by four 650-horsepower ships at 1,820 metric tons, and in two more years, by two other vessels of still greater power and tonnage.
4 | In 1853 the Cunard Co., whose mail-carrying charter had just been renewed, successively added to its assets the Arabia, the Persia, the China, the Scotia, the Java, and the Russia, all ships of top speed and, after the Great Eastern, the biggest ever to plow the seas.
5 | So in 1867 this company owned twelve ships, eight with paddle wheels and four with propellers.
6 | If I give these highly condensed details, it is so everyone can fully understand the importance of this maritime transportation company, known the world over for its shrewd management.
7 | No transoceanic navigational undertaking has been conducted with more ability, no business dealings have been crowned with greater success.
8 | In twenty-six years Cunard ships have made 2,000 Atlantic crossings without so much as a voyage canceled, a delay recorded, a man, a craft, or even a letter lost.
9 | Accordingly, despite strong competition from France, passengers still choose the Cunard line in preference to all others, as can be seen in a recent survey of official documents.
10 | Given this, no one will be astonished at the uproar provoked by this accident involving one of its finest steamers.
11 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/try.py:
--------------------------------------------------------------------------------
1 | # # This program calculate average number of words per sentence.
2 |
3 | # def main():
4 | # # Open the file for reading
5 | # text = open('text.txt', 'r')
6 |
7 | # # Read the file
8 | # text_list = text.readlines()
9 |
10 | # new_list = []
11 | # # Strip \n from the list
12 | # for index in range(len(text_list)):
13 | # text_list[index] = text_list[index].rstrip('\n')
14 | # text_len = len(text_list[index])
15 | # new_list.append(text_len)
16 |
17 | # # Close the file
18 | # text.close()
19 |
20 | # total = 0
21 | # for num in new_list:
22 | # total += num
23 | # print(total)
24 | # avg = total / len(new_list)
25 | # print('The average number of words in this file is', format(avg, '.0f'))
26 |
27 | # main()
28 |
29 | # name = 'Tunde'
30 | # print(len(name))
31 |
32 | def main():
33 | # Open the file for reading
34 | text = open('text.txt', 'r')
35 |
36 | # Read the file
37 | text_list = text.readlines()
38 |
39 | # Strip \n from the list
40 | for index in range(len(text_list)):
41 | text_list[index] = text_list[index].rstrip('\n')
42 |
43 | # Close the file
44 | text.close()
45 |
46 | upper, lower, digit, space = 0, 0, 0, 0
47 |
48 | for item in text_list:
49 | res = analysis(item)
50 | upper += res[0]
51 | lower += res[1]
52 | digit += res[2]
53 | space += res[3]
54 | print('The total number of uppercase letters is', upper)
55 | print('The total number of lowercase letters is', lower)
56 | print('The total number of digits is', digit)
57 | print('The total number of whitespace is', space)
58 |
59 | def analysis(item):
60 | result = [0, 0, 0, 0]
61 | for ch in item:
62 | if ch.isupper():
63 | result[0] += 1
64 | elif ch.islower():
65 | result[1] += 1
66 | elif ch.isdigit():
67 | result[2] += 1
68 | elif ch.isspace():
69 | result[3] += 1
70 |
71 | return result
72 |
73 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/try.txt:
--------------------------------------------------------------------------------
1 | My Name is Tunde Muhamed
2 | I am 29 years old
3 | I was born in 1991.
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/trypb.py:
--------------------------------------------------------------------------------
1 |
2 | # def top_10_overdue():
3 | # numbers = [
4 | # 1, 2, 3, 4, 5, 6, 7,8, 9, 10
5 | # ]
6 |
7 | # times = [
8 | # 15, 10, 3, 5, 6, 15, 8, 1, 11, 15
9 | # ]
10 |
11 | # count = 0
12 | # overdue_list = []
13 | # not_seen_list = []
14 | # placeholder = ''
15 |
16 | # for number in numbers:
17 | # placeholder = number
18 |
19 | # for specific_number in numbers:
20 | # if specific_number == placeholder:
21 | # count = 0
22 | # else:
23 | # count += 1
24 |
25 | # overdue_list.append(number)
26 | # not_seen_list.append(count)
27 | # print(count)
28 | # print(overdue_list)
29 | # print(not_seen_list)
30 | # print(placeholder)
31 |
32 | # # top_10_overdue = []
33 | # # top_10_not_seen_for= []
34 | # # for count in range(10):
35 | # # index = not_seen_list.index(max(not_seen_list))
36 | # # top_10_not_seen_for.append(not_seen_list[index])
37 | # # top_10_overdue.append(overdue_list[index])
38 | # # del not_seen_list[index]
39 | # # del overdue_list[index]
40 |
41 | # top_10_overdue()
42 |
43 |
44 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/vowels_consonants.py:
--------------------------------------------------------------------------------
1 | def main():
2 | user_input = input('Enter a string: ')
3 |
4 | vow = vowels_funct(user_input)
5 | cons = consonants_funct(user_input)
6 |
7 | # Display the result
8 |
9 | print('Total vowel letters is:', vow)
10 | print('Total consonants letters is:', cons)
11 |
12 |
13 | def vowels_funct(user_input):
14 | count_vow = 0
15 | vowels_alph = 'aeiou'
16 |
17 | for ch in user_input:
18 | if ch in vowels_alph:
19 | count_vow += 1
20 |
21 | return count_vow
22 |
23 |
24 | def consonants_funct(user_input):
25 | count_cons = 0
26 | consonants_alph = 'bcdfghjklmnpqrstvwxyz'
27 |
28 | for ch in user_input:
29 | if ch in consonants_alph:
30 | count_cons += 1
31 |
32 | return count_cons
33 |
34 | main()
35 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter08/ProgrammingExercise/word_separator.py:
--------------------------------------------------------------------------------
1 | def main():
2 | user_str = input('Enter a sting: ')
3 |
4 | # set1 = user_str[0]
5 | # set2 = user_str[1:]
6 |
7 |
8 | for char in user_str:
9 | res = get_set(char)
10 | print(res, end='')
11 |
12 |
13 | def get_set(user):
14 |
15 | for ch in user:
16 | if user[0] == ch.upper():
17 | val = ch
18 |
19 | elif ch.isupper():
20 | val = user[0] + ' ' + ch.lower()
21 | else:
22 | val = ch
23 |
24 | return val
25 |
26 | main()
27 |
28 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/Examples/exm.py:
--------------------------------------------------------------------------------
1 | # myset = set(('one', 'two', 'three'))
2 | # # myset = set(['a', 'a', 'a'])
3 | # print(myset)
4 | # myset = set([1, 2, 3, 4, 5])
5 | # print(len(myset))
6 | # print(myset)
7 |
8 | # phonebook = dict()
9 | # print(phonebook)
10 | # phones = {}
11 | # print(phones)
12 |
13 | # myset = set('one two three')
14 | # print(myset)
15 | # set1 = set([1, 2, 3])
16 | # set2 = set([8, 9, 10])
17 | # # set1.update(set2)
18 | # print(set1)
19 | # print(set2)
20 | # set1.update('abc')
21 | # print(set1)
22 |
23 | # myset = set([1, 2, 3, 4, 5])
24 | # print(myset)
25 | # myset.clear()
26 | # print(myset)
27 |
28 | # person = {}
29 | # person['name'] = 'Tunde Muhamed'
30 | # person['age'] = 29
31 | # person['weight'] = 165
32 | # print(person)
33 |
34 | # import item
35 |
36 | # def main():
37 | # state = {'Abia':'Umaya', 'Adamawa':'Yola', 'Akwa Ibom': 'Uyo',
38 | # 'Bauchi':'Bauchi', 'Delta':'Asaba', 'Lagos':'Ikeja',
39 | # 'Niger':'Minna', 'Ogun':'Abeokuta', 'Ondo':'Akure',
40 | # 'Oyo':'Ibadan', 'Osun':'Osogbo', 'River':'Portercort',
41 | # 'Sokoto':'Sokoto', 'Kano':'Kano', 'Kaduna':'Kaduna',
42 | # 'Kwara':'Ilorin', 'Edo':'Benin city','Ekiti':'Ado Ekiti',
43 | # 'Kogi':'Lokoja','Imo':'Oweri','FCT':'Abuja'}
44 | # num = len(state)
45 | # count = 0
46 | # for index in range(num):
47 | # choice = item.pop_item(state)
48 | # print('What is the capital of '+str(choice[0])+' state? ', end='')
49 | # qst = input()
50 | # if qst.lower() == choice[1].lower():
51 | # count += 1
52 | # print('You score', count, 'out of', num, 'in this quiz!')
53 |
54 | # main()
55 |
56 | word = input('Enter a word: ')
57 | word_split = word.split()
58 | print(word_split)
59 | set_word = set(word_split)
60 | print(set_word)
61 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/Examples/info.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter09/Examples/info.dat
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/Examples/phonebook.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter09/Examples/phonebook.dat
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/Examples/pickle_objects.py:
--------------------------------------------------------------------------------
1 | # This program demonstrates object pickling
2 | import pickle
3 |
4 | def main():
5 | again = 'y'
6 | # Open a file for binary writing
7 | output_file = open('info.dat', 'wb')
8 |
9 | # get data until the user wants to stop
10 | while again.lower() == 'y':
11 | # Get data about a person and save it
12 | save_data(output_file)
13 | again = input('Enter more data? [Y/n]: ')
14 |
15 | output_file.close()
16 |
17 |
18 | # The save data function gets data about a person,
19 | # srtores it in a dictionary and then pickles the
20 | # dictionary to the specified file
21 | def save_data(file):
22 | # Create an empty dictionary
23 | person = {}
24 |
25 | # Get data for the person and store
26 | # it in the dictionary
27 | person['name'] = input('Name: ')
28 | person['age'] = int(input('Age: '))
29 | person['weight'] = float(input('Weight: '))
30 |
31 | # Pickle the dictionary
32 | pickle.dump(person, file)
33 |
34 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/Examples/set.py:
--------------------------------------------------------------------------------
1 | # This program demonstrates varoius set operations.
2 | baseball = set(['Jodi', 'Carmen', 'Aida', 'Alicia'])
3 | basketball = set(['Eva', 'Carmen', 'Alicia', 'Sarah'])
4 |
5 | # Display numbers of the baseball set.
6 | print('The following students are on the baseball team: ')
7 | for name in baseball:
8 | print(name)
9 |
10 | print()
11 |
12 | # Display numbers of the basketball set.
13 | print('The following students are on the basketball team: ')
14 | for name in basketball:
15 | print(name)
16 |
17 | print()
18 | # Demonstrates the intersection
19 | print('The following students play both baseball and basketball: ')
20 | for name in baseball.intersection(basketball):
21 | print(name)
22 |
23 | print()
24 | # Demonstrate union
25 | print('The following students play either baseball or basketball: ')
26 | for name in baseball.union(basketball):
27 | print(name)
28 |
29 | print()
30 | # Demonstarate the difference of baseball and basketball
31 | print('The following students play baseball, but not basketball: ')
32 | for name in baseball.difference(basketball):
33 | print(name)
34 |
35 | print()
36 | # Demonstarate the difference of basketball and baseball
37 | print('The following students play basketball , but not baseball: ')
38 | for name in basketball.difference(baseball):
39 | print(name)
40 |
41 | print()
42 | # Demonstarate the symmetric difference
43 | print('The following students play one sport, but not both: ')
44 | for name in baseball.symmetric_difference(basketball):
45 | print(name)
46 |
47 |
48 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/Examples/unpickle_objects.py:
--------------------------------------------------------------------------------
1 | # This program demonstrates object unpickling
2 | import pickle
3 |
4 | def main():
5 | end_of_file = False
6 | # Open a file for binary reading
7 | input_file = open('info.dat', 'rb')
8 | while not end_of_file:
9 | try:
10 | person = pickle.load(input_file)
11 | display_data(person)
12 | except EOFError:
13 | # Set the flag to indicate the end of the file
14 | # has been reached
15 | end_of_file = True
16 |
17 | input_file.close()
18 |
19 |
20 | def display_data(person):
21 | print('Name:', person['name'])
22 | print('Age:', person['age'])
23 | print('Weight:', person['weight'])
24 | print()
25 |
26 | main()
27 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/WorldSeries.txt:
--------------------------------------------------------------------------------
1 | Boston Americans
2 | World Series Not Played in 1904
3 | New York Giants
4 | Chicago White Sox
5 | Chicago Cubs
6 | Chicago Cubs
7 | Pittsburgh Pirates
8 | Philadelphia Athletics
9 | Philadelphia Athletics
10 | Boston Red Sox
11 | Philadelphia Athletics
12 | Boston Braves
13 | Boston Red Sox
14 | Boston Red Sox
15 | Chicago White Sox
16 | Boston Red Sox
17 | Cincinnati Reds
18 | Cleveland Indians
19 | New York Giants
20 | New York Giants
21 | New York Yankees
22 | Washington Senators
23 | Pittsburgh Pirates
24 | St. Louis Cardinals
25 | New York Yankees
26 | New York Yankees
27 | Philadelphia Athletics
28 | Philadelphia Athletics
29 | St. Louis Cardinals
30 | New York Yankees
31 | New York Giants
32 | St. Louis Cardinals
33 | Detroit Tigers
34 | New York Yankees
35 | New York Yankees
36 | New York Yankees
37 | New York Yankees
38 | Cincinnati Reds
39 | New York Yankees
40 | St. Louis Cardinals
41 | New York Yankees
42 | St. Louis Cardinals
43 | Detroit Tigers
44 | St. Louis Cardinals
45 | New York Yankees
46 | Cleveland Indians
47 | New York Yankees
48 | New York Yankees
49 | New York Yankees
50 | New York Yankees
51 | New York Yankees
52 | New York Giants
53 | Brooklyn Dodgers
54 | New York Yankees
55 | Milwaukee Braves
56 | New York Yankees
57 | Los Angeles Dodgers
58 | Pittsburgh Pirates
59 | New York Yankees
60 | New York Yankees
61 | Los Angeles Dodgers
62 | St. Louis Cardinals
63 | Los Angeles Dodgers
64 | Baltimore Orioles
65 | St. Louis Cardinals
66 | Detroit Tigers
67 | New York Mets
68 | Baltimore Orioles
69 | Pittsburgh Pirates
70 | Oakland Athletics
71 | Oakland Athletics
72 | Oakland Athletics
73 | Cincinnati Reds
74 | Cincinnati Reds
75 | New York Yankees
76 | New York Yankees
77 | Pittsburgh Pirates
78 | Philadelphia Phillies
79 | Los Angeles Dodgers
80 | St. Louis Cardinals
81 | Baltimore Orioles
82 | Detroit Tigers
83 | Kansas City Royals
84 | New York Mets
85 | Minnesota Twins
86 | Los Angeles Dodgers
87 | Oakland Athletics
88 | Cincinnati Reds
89 | Minnesota Twins
90 | Toronto Blue Jays
91 | World Series Not Played in 1994
92 | Toronto Blue Jays
93 | Atlanta Braves
94 | New York Yankees
95 | Florida Marlins
96 | New York Yankees
97 | New York Yankees
98 | New York Yankees
99 | Arizona Diamondbacks
100 | Anaheim Angels
101 | Florida Marlins
102 | Boston Red Sox
103 | Chicago White Sox
104 | St. Louis Cardinals
105 | Boston Red Sox
106 | Philadelphia Phillies
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/WorldSeriesWinners.txt:
--------------------------------------------------------------------------------
1 | Boston Americans
2 | World Series Not Played in 1904
3 | New York Giants
4 | Chicago White Sox
5 | Chicago Cubs
6 | Chicago Cubs
7 | Pittsburgh Pirates
8 | Philadelphia Athletics
9 | Philadelphia Athletics
10 | Boston Red Sox
11 | Philadelphia Athletics
12 | Boston Braves
13 | Boston Red Sox
14 | Boston Red Sox
15 | Chicago White Sox
16 | Boston Red Sox
17 | Cincinnati Reds
18 | Cleveland Indians
19 | New York Giants
20 | New York Giants
21 | New York Yankees
22 | Washington Senators
23 | Pittsburgh Pirates
24 | St. Louis Cardinals
25 | New York Yankees
26 | New York Yankees
27 | Philadelphia Athletics
28 | Philadelphia Athletics
29 | St. Louis Cardinals
30 | New York Yankees
31 | New York Giants
32 | St. Louis Cardinals
33 | Detroit Tigers
34 | New York Yankees
35 | New York Yankees
36 | New York Yankees
37 | New York Yankees
38 | Cincinnati Reds
39 | New York Yankees
40 | St. Louis Cardinals
41 | New York Yankees
42 | St. Louis Cardinals
43 | Detroit Tigers
44 | St. Louis Cardinals
45 | New York Yankees
46 | Cleveland Indians
47 | New York Yankees
48 | New York Yankees
49 | New York Yankees
50 | New York Yankees
51 | New York Yankees
52 | New York Giants
53 | Brooklyn Dodgers
54 | New York Yankees
55 | Milwaukee Braves
56 | New York Yankees
57 | Los Angeles Dodgers
58 | Pittsburgh Pirates
59 | New York Yankees
60 | New York Yankees
61 | Los Angeles Dodgers
62 | St. Louis Cardinals
63 | Los Angeles Dodgers
64 | Baltimore Orioles
65 | St. Louis Cardinals
66 | Detroit Tigers
67 | New York Mets
68 | Baltimore Orioles
69 | Pittsburgh Pirates
70 | Oakland Athletics
71 | Oakland Athletics
72 | Oakland Athletics
73 | Cincinnati Reds
74 | Cincinnati Reds
75 | New York Yankees
76 | New York Yankees
77 | Pittsburgh Pirates
78 | Philadelphia Phillies
79 | Los Angeles Dodgers
80 | St. Louis Cardinals
81 | Baltimore Orioles
82 | Detroit Tigers
83 | Kansas City Royals
84 | New York Mets
85 | Minnesota Twins
86 | Los Angeles Dodgers
87 | Oakland Athletics
88 | Cincinnati Reds
89 | Minnesota Twins
90 | Toronto Blue Jays
91 | World Series Not Played in 1994
92 | Toronto Blue Jays
93 | Atlanta Braves
94 | New York Yankees
95 | Florida Marlins
96 | New York Yankees
97 | New York Yankees
98 | New York Yankees
99 | Arizona Diamondbacks
100 | Anaheim Angels
101 | Florida Marlins
102 | Boston Red Sox
103 | Chicago White Sox
104 | St. Louis Cardinals
105 | Boston Red Sox
106 | Philadelphia Phillies
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/blackjack_simulation.py:
--------------------------------------------------------------------------------
1 | import random
2 |
3 | # deck_dict = {
4 | # 'Ace of Hearts': 1, '2 of Hearts': 2, '3 of Hearts': 3, '4 of Hearts': 4, '5 of Hearts': 5,
5 | # '6 of Hearts': 6, '7 of Hearts': 7, '8 of Hearts': 8, '9 of Hearts': 9, '10 of Hearts': 10,
6 | # 'Jack of Hearts': 10, 'Queen of Hearts': 10, 'King of Hearts': 10, 'Ace of Spades': 1,
7 | # '2 of Spades': 2, '3 of Spades': 3, '4 of Spades': 4, '5 of Spades': 5, '6 of Spades': 6,
8 | # '7 of Spades': 7, '8 of Spades': 8, '9 of Spades': 9, '10 of Spades': 10, 'Jack of Spades': 10,
9 | # 'Queen of Spades': 10, 'King of Spades': 10, 'Ace of Clubs': 1, '2 of Clubs': 2, '3 of Clubs': 3,
10 | # '4 of Clubs': 4, '5 of Clubs': 5, '6 of Clubs': 6, '7 of Clubs': 7, '8 of Clubs': 8, '9 of Clubs': 9,
11 | # '10 of Clubs': 10, 'Jack of Clubs': 10, 'Queen of Clubs': 10, 'King of Clubs': 10, 'Ace of Diamonds': 1,
12 | # '2 of Diamonds': 2, '3 of Diamonds': 3, '4 of Diamonds': 4, '5 of Diamonds': 5, '6 of Diamonds': 6,
13 | # '7 of Diamonds': 7, '8 of Diamonds': 8, '9 of Diamonds': 9, '10 of Diamonds': 10, 'Jack of Diamonds': 10,
14 | # 'Queen of Diamonds': 10, 'King of Diamonds': 10
15 | # }
16 |
17 | # print(len(deck_dict))
18 |
19 | def createdeck():
20 | # Another method to create the deck dictionary
21 | value = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
22 | suit = ('of Hearts', 'of Spades', 'of Clubs', 'of Diamonds')
23 | deck = dict()
24 | counter = 1
25 |
26 | for element in suit:
27 | for item in value:
28 | deck[item + ' ' + element] = counter
29 | if counter < 10:
30 | counter += 1
31 | else:
32 | counter = 10
33 | counter = 1
34 |
35 | return deck
36 |
37 |
38 | def deal_cards(a_deck):
39 | player_1_hand = 0
40 | player_2_hand = 0
41 | player_1_score = 0
42 | player_2_score = 0
43 |
44 | for count in range(len(a_deck) // 2):
45 | card1 = random.choice(list(a_deck.keys()))
46 | value1 = a_deck[card1]
47 | del a_deck[card1]
48 | print(card1)
49 | if card1.startswith('Ace') and (11 + player_1_hand) < 21:
50 | value1 = 11
51 | else:
52 | value1 = 1
53 | player_1_hand += value1
54 | print('Player 1:', player_1_hand)
55 |
56 | card2 = random.choice(list(a_deck.keys()))
57 | value2 = a_deck[card2]
58 | del a_deck[card2]
59 | print(card2)
60 | if card2.startswith('Ace') and (11 + player_2_hand) < 21:
61 | value2 = 11
62 | else:
63 | value2 = 1
64 | player_2_hand += value2
65 | print('Player 2:', player_2_hand)
66 |
67 | if player_1_hand > 21 and player_2_hand > 21:
68 | print('No one wins')
69 | player_1_hand = 0
70 | player_2_hand = 0
71 |
72 | elif player_1_hand > 21 and player_2_hand <= 21:
73 | print('Player 2 wins')
74 | player_2_score += 1
75 | player_1_hand = 0
76 | player_2_hand = 0
77 |
78 | elif player_2_hand > 21 and player_1_hand <= 21:
79 | print('Player 1 wins')
80 | player_1_score += 1
81 | player_1_hand = 0
82 | player_2_hand = 0
83 |
84 | else:
85 | print('Round continues')
86 |
87 | print('Player 1', player_1_score)
88 | print('Player 2', player_2_score)
89 |
90 | if player_1_score > player_2_score:
91 | print('Player 1 wins!')
92 | elif player_2_score > player_1_score:
93 | print('Player 2 wins!')
94 | else:
95 | print('It is a TIE!')
96 |
97 |
98 | def main():
99 | deck = createdeck()
100 | deal_cards(deck)
101 |
102 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/capital_quiz.py:
--------------------------------------------------------------------------------
1 | # This program creates a dictionary containing US states as
2 | # keys and their capitals as value. The program randomly quiz the
3 | # userby displaying the name of a state and asking the user to enter
4 | # that state capital.
5 |
6 | def main():
7 | # Create a dictionary
8 | state_and_their_capitals = {
9 | 'Abia':'Umaya', 'Adamawa':'Yola', 'Akwa Ibom': 'Uyo',
10 | 'Bauchi':'Bauchi', 'Delta':'Asaba', 'Lagos':'Ikeja',
11 | 'Niger':'Minna', 'Ogun':'Abeokuta', 'Ondo':'Akure',
12 | 'Oyo':'Ibadan', 'Osun':'Osogbo', 'River':'Portercort',
13 | 'Sokoto':'Sokoto', 'Kano':'Kano', 'Kaduna':'Kaduna',
14 | 'Kwara':'Ilorin', 'Edo':'Benin city','Ekiti':'Ado Ekiti',
15 | 'Kogi':'Lokoja','Imo':'Oweri','FCT':'Abuja'
16 | }
17 |
18 | count_right = 0 # count correct answers
19 | count_wrong = 0 # count wrong answers
20 |
21 | # create a means to control the loop
22 | again = 'y'
23 | while again.lower() == 'y':
24 | state, capital = state_and_their_capitals.popitem()
25 | print('What is the capital of', state, end='')
26 | ans = input(': ')
27 | if ans.lower() == capital.lower():
28 | print('Your answer is correct.')
29 | count_right += 1
30 | else:
31 | print('Wrong!!! The capital of', state, 'is', capital, '.')
32 | count_wrong += 1
33 |
34 | print()
35 |
36 | again = input('Do you wish to do more test? [Y/n]: ')
37 |
38 |
39 | print('You answered', count_right, 'questions correctly\nand you missed.',count_wrong, 'questions')
40 |
41 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/course_information.py:
--------------------------------------------------------------------------------
1 | # This program creates a dictionary containing
2 | # course numbers and the room numbers where the
3 | # courses meet. Also with the name of the instructors
4 | # that take each course.
5 |
6 | def main():
7 |
8 | course_info = {
9 | 'CS101': [3004, 'Haynes', '8:00 am'],
10 | 'CS102': [4501, 'Alvarado', '9:00 am'],
11 | 'CS103': [6755, 'Rich', '10:00 am'],
12 | 'NT110': [1244, 'Burke', '11:00 am'],
13 | 'CM241': [1411, 'Lee', '1:00 pm']
14 | }
15 |
16 | search_course = input('Enter a course name: ')
17 | # print()
18 | # print('This is the information of the course you searched for:')
19 | # print('The room number, The Lecturer and lecture time are...')
20 | print('This are the details for', search_course, '...')
21 | if search_course in course_info:
22 | print('Room Number:', course_info[search_course][0])
23 | print('Lecture Name:', course_info[search_course][1])
24 | print('Time:', course_info[search_course][2])
25 | else:
26 | print('That course is not found.')
27 | # print(course_info.get(search_course, 'That Course is not found'))
28 |
29 | # name_room = course_info.values()
30 | # name_room = list(name_room)
31 | # print(name_room)
32 | # for room_no in range(len(name_room)):
33 | # for name in
34 | # print(name_room[0][1])
35 | # for name in course_info.values():
36 | # print(name)
37 | # print('Course Name\t\tRoom | LecturerNames | LectureTime')
38 | # print('==================================================')
39 | # for course, info in course_info.items():
40 | # print(course, '\t\t\t', info)
41 |
42 | # print(course_info['CS101'][0])
43 | # print(course_info['CS103'][1])
44 | # print(course_info['CM241'][2])
45 |
46 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/decrypted_sampletext.txt:
--------------------------------------------------------------------------------
1 | Slavery was practiced throughout the American colonies in the 17th and 18th centuries,
2 | and African slaves helped build the new nation into an economic powerhouse through the
3 | production of lucrative crops such as tobacco and cotton. By the mid-19th century,
4 | Americas westward expansion and the abolition movement provoked a great debate over
5 | slavery that would tear the nation apart in the bloody Civil War. Though the Union victory
6 | freed the nations four million slaves, the legacy of slavery continued to influence
7 | American history, from the Reconstruction era to the civil rights movement that emerged
8 | a century after emancipation.
9 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/encrypted_sampletext.txt:
--------------------------------------------------------------------------------
1 | ?0@c),dGf@/G;,@^a4^)*Ga2,]b`2]baGa2)G!=),4^@[G^]0][4)/G4[Ga2)Ggja2G@[*GgUa2G^)[ab,4)/p
2 | @[*G!+,4^@[G/0@c)/G2)0;)*G$b40*Ga2)G[)fG[@a4][G4[a]G@[G)^][]=4^G;]f),2]b/)Ga2,]b`2Ga2)G
3 | ;,]*b^a4][G]+G0b^,@a4c)G^,];/G/b^2G@/Ga]$@^^]G@[*G^]aa][lG#dGa2)G=4*Lgua2G^)[ab,dp
4 | !=),4^@/Gf)/af@,*G)r;@[/4][G@[*Ga2)G@$]04a4][G=]c)=)[aG;,]c]8)*G@G`,)@aG*)$@a)G]c),G
5 | /0@c),dGa2@aGf]b0*Ga)@,Ga2)G[@a4][G@;@,aG4[Ga2)G$0]]*dG%4c40GF@,lGA2]b`2Ga2)GB[4][Gc4^a],dG
6 | +,))*Ga2)G[@a4][/G+]b,G=4004][G/0@c)/pGa2)G0)`@^dG]+G/0@c),dG^][a4[b)*Ga]G4[+0b)[^)G
7 | !=),4^@[G24/a],dpG+,]=Ga2)G<)^][/a,b^a4][G),@Ga]Ga2)G^4c40G,4`2a/G=]c)=)[aGa2@aG)=),`)*G
8 | @G^)[ab,dG@+a),G)=@[^4;@a4][l
9 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/exm.py:
--------------------------------------------------------------------------------
1 | # import random
2 |
3 | # names = ['Tunde', 'Shina', 'Wale', 'Toyosi']
4 | # leader = random.choice(names)
5 | # print(leader)
6 |
7 | # text = []
8 | # infile = open('sampletext.txt', 'r')
9 | # for line in infile:
10 | # line_text = line.rstrip('\n')
11 | # text.append(line_text)
12 | # print(line_text)
13 |
14 | # print()
15 | # print()
16 | # print(text)
17 | # infile.close()
18 |
19 | codes = {'A':'%', 'a':'9', 'B':'@', 'b':'l','C':'!', 'c':'1', 'D':'$',
20 | 'd':'5','E':'^','e':'7','F':'*','f':'4','G':'q','g':'6',
21 | 'H':'(','h':'3','I':'u','i':'0','J':'m','j':'y','K':'#',
22 | 'k':'b','L':')','l':'a','M':'t','m':'d','N':'[','n':'P',
23 | 'O':'n','o':';','P':'.','p':'/','Q':'r','q':'z','R':'e',
24 | 'r':':','S':'v','s':'|','T':'2','t':'+','U':'<','u':'_',
25 | 'V':'i','v':'>','W':'`','w':',','X':'~','x':'=','Y':'"',
26 | 'y':'{','Z':'j','z':'?'}
27 |
28 | def decryption(codes):
29 | # Open a file for binary writing
30 | infile = open('sampletext.txt', 'r')
31 | outfile = open('encryption_sample.txt', 'w')
32 |
33 | new_file = []
34 | infile_list = infile.readlines()
35 | for index in range(len(infile_list)):
36 | infile_list[index] = infile_list[index].rstrip('\n')
37 | file = list(infile_list[index])
38 | new_file.append(file)
39 |
40 | new_item2 = []
41 | for item in new_file:
42 | new_item = ''
43 | for ch in item:
44 | if ch != '-':
45 | new_item += codes[ch]
46 | new_item2.append(new_item)
47 |
48 | for item in new_item2:
49 | outfile.write(item + '\n')
50 |
51 | def encryption(codes):
52 | outfile = open('encrypted_sampletext.txt', 'r')
53 |
54 | file_list = outfile.readlines()
55 |
56 | new_item2 = []
57 | for item in range(len(file_list)):
58 | file_list[item] = file_list[item].rstrip('\n')
59 |
60 | new_item = ''
61 | codes_list = []
62 | for index in range(len(codes)):
63 | n = codes.items()
64 | m = list(n)
65 | o = list(m[index])
66 | codes_list.append(o)
67 | new_item2.append(new_item)
68 | for i in range(len(codes_list)):
69 | codes_list[i][0], codes_list[i][1] = codes_list[i][1], codes_list[i][0]
70 |
71 | new_item2 = []
72 | for item in file_list:
73 | new_item = ''
74 | for ch in item:
75 | for i in range(len(codes_list)):
76 | if ch in codes_list[i]:
77 | new_item += codes_list[i][1]
78 | new_item2.append(new_item)
79 | print(new_item)
80 |
81 |
82 | encryption(codes)
83 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/file1.txt:
--------------------------------------------------------------------------------
1 | Tunde Muhamed Engineering 29 Light FirstClass
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/file2.txt:
--------------------------------------------------------------------------------
1 | Shina Onilude Statistics 30 Dark FirstClass
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/file_analysis.py:
--------------------------------------------------------------------------------
1 | # This program reads the contents of two text files
2 | # And compares them in the following ways
3 | # 1) Display a list of all unique words contained in both files
4 | # 2) Display a list of all the words that appears in both files
5 | # 3) Display a list of words that appears in the first file but not in second
6 | # 4) Display a list of words that appears in the second file but not in first
7 | # 4) Display a list of words that appears in either the first file or second file but not both
8 |
9 | def main():
10 | # Create two output files and write words to them
11 | outfile1 = open('file1.txt', 'w')
12 | outfile2 = open('file2.txt', 'w')
13 |
14 | word1 = input('Enter the first word: ')
15 | word2 = input('Enter the second word: ')
16 |
17 | outfile1.write(word1)
18 | outfile2.write(word2)
19 |
20 | outfile1.close()
21 | outfile2.close()
22 |
23 |
24 | unique_list1, unique_list2 = set_compare()
25 | # All unique word in first file
26 | print('All unique words in first file:')
27 | for word in unique_list1:
28 | print(word)
29 | print()
30 |
31 | # All unique word in second file
32 | print('All unique words in second file:')
33 | for word in unique_list2:
34 | print(word)
35 | print()
36 |
37 | # All the unique words that appear in both files (intersection set)
38 | print('List of all unique words that appear in both files:')
39 | for word in unique_list1.intersection(unique_list2):
40 | print(word)
41 | print()
42 |
43 |
44 | # All the words that appear in both files (union set)
45 | print('List of all the words that appear in both files:')
46 | for word in unique_list1.union(unique_list2):
47 | print(word)
48 | print()
49 |
50 | # list of words that appears in the first file but not in second(difference set)
51 | print('Lists of words that appears in the first file but not in second:')
52 | for word in unique_list1.difference(unique_list2):
53 | print(word)
54 | print()
55 |
56 | # list of words that appears in the second file but not in first(difference set)
57 | print('Lists of words that appears in the second file but not in first:')
58 | for word in unique_list2.difference(unique_list1):
59 | print(word)
60 | print()
61 |
62 | # list of words that appears in either the first file or second file but not both(symmetric differene set)
63 | print('list of words that appears in either the first file or second file but not both:')
64 | for word in unique_list1.symmetric_difference(unique_list2):
65 | print(word)
66 | print()
67 |
68 |
69 | def set_compare():
70 | # Read the content of the two files
71 |
72 | infile1 = open('file1.txt', 'r')
73 | infile2 = open('file2.txt', 'r')
74 |
75 | word1 = infile1.read()
76 | word2 = infile2.read()
77 |
78 | word1_split = (word1.split())
79 | word2_split = (word2.split())
80 |
81 | # Unique List
82 | word1_set = set(word1_split)
83 | word2_set = set(word2_split)
84 |
85 | infile1.close()
86 | infile2.close()
87 |
88 | # print(word1_split)
89 | return word1_set, word2_set
90 |
91 | main()
92 |
93 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/file_encrypt.py:
--------------------------------------------------------------------------------
1 | import pickle
2 |
3 | def main():
4 | codes = {
5 | "A": "%",
6 | "a": "9",
7 | "B": "@",
8 | "b": "#",
9 | "C": ":",
10 | "c": ";",
11 | "D": "'",
12 | "E": "(",
13 | "e": ")",
14 | "F": "{",
15 | "f": "}",
16 | "G": "<",
17 | "g": ">",
18 | "H": "=",
19 | "h": "-",
20 | "I": "+",
21 | "i": "*",
22 | "J": "/",
23 | "j": "^",
24 | "K": "%",
25 | "k": "$",
26 | "L": "|",
27 | "l": "!",
28 | "M": "?",
29 | "m": "_",
30 | "N": "8",
31 | "n": "7",
32 | "O": "6",
33 | "o": "5",
34 | "P": "4",
35 | "p": "3",
36 | "Q": "2",
37 | "q": "1",
38 | "R": "0",
39 | "r": ".",
40 | "S": ",",
41 | "s": "~",
42 | "T": "¡",
43 | "t": "!",
44 | "U": "[",
45 | "u": "]",
46 | "V": "¿",
47 | "v": "®",
48 | "W": "¤",
49 | "w": "β",
50 | "X": "€",
51 | "x": "Δ",
52 | "Y": "¥",
53 | "y": "£",
54 | "Z": "™",
55 | "z": "π"
56 | }
57 | print(len(codes))
58 |
59 |
60 | # writing to a file function
61 | write_file()
62 |
63 | # reading the contents of the file
64 | file_contents = read_file()
65 |
66 | # using a set function to read the file contents into dictionary
67 | set_file = set(file_contents)
68 | dict_content = open("dict.txt", "w")
69 | # print(set_file)
70 | for ch in set_file:
71 | if ch in codes:
72 | dict_content.write(codes[ch])
73 |
74 | dict_content.close()
75 |
76 | # display the contents of the code
77 | display_content()
78 |
79 | # print(ch)
80 | # file_split = file_contents.split()
81 | # set_content = set(file_contents)
82 | # print(file_split)
83 |
84 | def write_file():
85 | outfile = open("text.txt", "w")
86 | user_str = input("Enter a string: ")
87 | outfile.write(user_str)
88 | outfile.close()
89 |
90 | def read_file():
91 | infile = open("text.txt", "r")
92 | contents = infile.read()
93 | infile.close()
94 |
95 | return contents
96 |
97 | def display_content():
98 | print("This is the coded version of your text.")
99 | infile = open("dict.txt", "r")
100 | content = infile.read()
101 | print(content)
102 | print()
103 |
104 |
105 | # print(contents)
106 |
107 | # output_file = open("file_encrypt.dat", "wb")
108 | # pickle.dump(codes, output_file)
109 | # output_file.close()
110 |
111 | # print("The codes has been written to file_encrypt.dat.")
112 |
113 | main()
114 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/file_encrypt2.py:
--------------------------------------------------------------------------------
1 | def main():
2 | encryption_dataset, decryption_dataset = encryption_rules()
3 | filename = input('Enter a txt file name: ')
4 | print()
5 | choice = int(input('Press (1) to encrypt, OR (2) to decrypt: '))
6 | if choice == 1:
7 | encrypt(filename, encryption_dataset)
8 | elif choice == 2:
9 | decrypt(filename, decryption_dataset)
10 | else:
11 | print('Not a valid choice.')
12 |
13 |
14 | def encryption_rules():
15 | encryption_dataset = dict()
16 | decryption_dataset = dict()
17 | characters = "!@#$%^&*()_+~`1234567890-={[}]:;>.<,?/AaBbCcFfRrDdTtGgYyHhJjUuKkOoLlp"
18 | letters = """AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz 1234567890’'"-.,"""
19 |
20 | for index in range(len(letters)):
21 | encryption_dataset[letters[index]] = characters[index]
22 | decryption_dataset[characters[index]] = letters[index]
23 |
24 | return encryption_dataset, decryption_dataset
25 | # print(len(characters))
26 | # print(len(letters))
27 |
28 |
29 | def encrypt(a_file, encryption_rules):
30 | infile = open(a_file, 'r')
31 | outfile = open('encrypted_' + a_file, 'w')
32 | text = []
33 | encrypted_text = []
34 |
35 | for line in infile:
36 | text.append(line.rstrip('\n'))
37 |
38 | for line in text:
39 | encrypted_line = ''
40 | for char in line:
41 | encrypted_line += encryption_rules.get(char, '')
42 | encrypted_text.append(encrypted_line)
43 |
44 | for line in encrypted_text:
45 | outfile.write(line + '\n')
46 |
47 | infile.close()
48 | outfile.close()
49 |
50 |
51 | def decrypt(a_file, decryption_rules):
52 | infile = open('encrypted_' + a_file, 'r')
53 | outfile = open('decrypted_' + a_file, 'w')
54 |
55 | encrypted_text = []
56 | decrypted_text = []
57 |
58 | for line in infile:
59 | encrypted_text.append(line.rstrip('\n'))
60 |
61 | for line in encrypted_text:
62 | decrypted_line = ''
63 | for char in line:
64 | decrypted_line += decryption_rules.get(char, '')
65 | decrypted_text.append(decrypted_line)
66 |
67 | for line in decrypted_text:
68 | outfile.write(line + '\n')
69 |
70 | infile.close()
71 | outfile.close()
72 |
73 |
74 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/index.txt:
--------------------------------------------------------------------------------
1 | 3D 12 13 15
2 | An 10
3 | Because 16
4 | For 11
5 | In 3 9
6 | OOP 9
7 | Object 8
8 | Reusability 8
9 | Sharon 11
10 | She 12
11 | The 4 6
12 | Tom, 14
13 | When 1 5
14 | a 5 10 11 12 12 12 14 16 16
15 | about 3 13 17
16 | access 1
17 | accidental 2
18 | addition 9
19 | addition, 3
20 | all 13
21 | also 6 9
22 | an 1 5 15
23 | and 1 9 12 14 16
24 | application 15
25 | architectural 15
26 | are 1 2 13
27 | attri- 1
28 | attributes 1 2
29 | attributes, 5
30 | been 10
31 | buildings. 15
32 | but 11
33 | butes 2
34 | by 10 11
35 | change. 7
36 | changes 5
37 | code 3 4 7 9
38 | code, 1
39 | coded 13
40 | computer 13 17
41 | computer’s 14
42 | corruption. 3
43 | data 1 1 2 5 9
44 | data. 4 6
45 | deadline 16
46 | deal 16
47 | developed 12
48 | display 15
49 | does 3 7 16
50 | edge 17
51 | encouraged 10
52 | example, 11
53 | firm, 15
54 | for 12 15
55 | format 3
56 | from 1 2
57 | graphics, 13 17
58 | great 16
59 | handle 14
60 | hardware. 14
61 | has 9 12
62 | he 6 16
63 | her 13
64 | hidden 1
65 | his 15
66 | however, 7
67 | images 15
68 | images. 12
69 | in 7
70 | interact 4
71 | interacts 7
72 | internal 4 5
73 | is 2 10 11 11 12 14 16
74 | its 11
75 | know 3
76 | knowl- 16
77 | knows 12
78 | lot 13
79 | math 12
80 | mathematical 14
81 | may 6
82 | methods 6
83 | methods, 2 7
84 | methods. 5
85 | modifies 6
86 | necessary 13
87 | need 3 11
88 | needs 4 15
89 | not 3 7 10 16
90 | object 3 10 10
91 | objects 12 13
92 | object’s 1 2 4 4 5 6
93 | of 4 5 9 9 10 12 13 15 16
94 | on 6
95 | only 4
96 | operate 6
97 | operations 14
98 | or 4 6
99 | outside 1 3 7
100 | perform 13
101 | possess 16
102 | problems 9
103 | program 15
104 | program, 10
105 | programmer 5 11
106 | programs 11
107 | properly 6
108 | protected 2
109 | rendering 12
110 | restricted 2
111 | reusability. 10
112 | separation, 9
113 | services. 11
114 | set 12
115 | she 6
116 | so 6 13
117 | solving 9
118 | stand-alone 10
119 | structure 4 5
120 | that 11
121 | the 1 2 2 3 3 3 4 4 5 6 6 7 9 9 10 13 14
122 | they 6
123 | tight 16
124 | to 1 2 3 4 9 13 15
125 | trend 10
126 | under 16
127 | use 9
128 | used 11
129 | video 14
130 | way 7
131 | which 7
132 | whiz 12
133 | who 11 14
134 | with 4 7
135 | working 16
136 | writing 14
137 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/name_email_address.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter09/ProgrammingExercises/name_email_address.py
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/sampletext.txt:
--------------------------------------------------------------------------------
1 | Slavery was practiced throughout the American colonies in the 17th and 18th centuries,
2 | and African slaves helped build the new nation into an economic powerhouse through the
3 | production of lucrative crops such as tobacco and cotton. By the mid-19th century,
4 | America’s westward expansion and the abolition movement provoked a great debate over
5 | slavery that would tear the nation apart in the bloody Civil War. Though the Union victory
6 | freed the nation’s four million slaves, the legacy of slavery continued to influence
7 | American history, from the Reconstruction era to the civil rights movement that emerged
8 | a century after emancipation.
9 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/text.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter09/ProgrammingExercises/text.txt
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/word_frequency.py:
--------------------------------------------------------------------------------
1 | def main():
2 | write_file()
3 | read_words()
4 |
5 | def write_file():
6 | outfile = open("words.txt", "w")
7 |
8 | user_str = input("Enter some words: ")
9 | outfile.write(user_str)
10 | outfile.close()
11 |
12 |
13 | def read_words():
14 | count_words = 1
15 | dict_words = {}
16 | found = False
17 |
18 | infile = open("words.txt", "r")
19 | content = infile.read()
20 | infile.close()
21 | # print(content)
22 |
23 | word_split = content.split()
24 | print(word_split)
25 | print()
26 |
27 | for item in word_split:
28 | if item == ',':
29 | continue
30 | elif item == '-':
31 | continue
32 | elif item not in dict_words:
33 | dict_words[item] = count_words
34 | else:
35 | found = True
36 | count_words = dict_words[item] + 1
37 | dict_words[item] = count_words
38 |
39 | count_words = 1
40 |
41 | print()
42 | print('Word\tFrequency')
43 | print('------------------')
44 | for word, freq in dict_words.items():
45 | print(word + '\t\t' + str(freq))
46 |
47 | # print(item)
48 | # print(word_split)
49 |
50 | # set_word = set(word_split)
51 | # print(set_word)
52 |
53 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/word_index.py:
--------------------------------------------------------------------------------
1 | def get_textname():
2 | name = input('For which file would you like to create a word index: ')
3 | return name
4 |
5 |
6 | def create_dictionary(filename):
7 | infile = open(filename, 'r')
8 | word_index = dict()
9 | counter = 0
10 | for line in infile:
11 | wordline_list = line.rstrip('\n').split()
12 | counter += 1
13 | for word in wordline_list:
14 | if word not in word_index:
15 | word_index[word] = [str(counter)]
16 | elif word in word_index:
17 | word_index[word].append(str(counter))
18 |
19 | infile.close()
20 | return word_index
21 | # print(word_index)
22 |
23 |
24 | def create_indexfile(dict):
25 | outfile = open('index.txt', 'w')
26 | a_list = []
27 | index = 0
28 | for key in dict.keys():
29 | a_list.append(key)
30 | for value in dict[key]:
31 | a_list[index] = a_list[index] + ' ' + value
32 | index += 1
33 | a_list.sort()
34 |
35 | for element in a_list:
36 | outfile.write(element + '\n')
37 | outfile.close()
38 |
39 |
40 | def main():
41 | print('This program creates a word index of the file you request:')
42 | print('----------------------------------------------------------')
43 | print()
44 | file = get_textname()
45 | dictionary = create_dictionary(file)
46 | create_indexfile(dictionary)
47 |
48 |
49 |
50 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/words.txt:
--------------------------------------------------------------------------------
1 | the the the the the man is a the the the the the the the the the the the the the the the the interal of the the the the the
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/world_series2.py:
--------------------------------------------------------------------------------
1 | def readfile():
2 | infile = open('WorldSeries.txt','r')
3 | timeswon = dict()
4 | teamwon = dict()
5 | year = 1903
6 | team = infile.readline()
7 | dontskip = True
8 | while team != '':
9 | team = team.rstrip('\n')
10 | if team in timeswon:
11 | timeswon[team] += 1
12 | elif team.startswith('World'):
13 | dontskip = False
14 | else:
15 | timeswon[team] = 1
16 | if dontskip:
17 | teamwon[year] = team
18 | year += 1
19 | team = infile.readline()
20 | dontskip = True
21 | return teamwon,timeswon
22 | def main():
23 | teamwon, timeswon = readfile()
24 | selection = int(input('Choose a year between 1903 and 2009: '))
25 | while selection == 1904 or selection == 1994:
26 | print('There was no world cup in',selection)
27 | selection = int(input('Choose another year:'))
28 | print(teamwon[selection],'won the World Cup in',selection)
29 | print('In total they won,',timeswon[teamwon[selection]],'times.')
30 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter09/ProgrammingExercises/world_series_winners.py:
--------------------------------------------------------------------------------
1 | def main():
2 | infile = open('WorldSeriesWinners.txt', 'r')
3 | line = infile.readlines()
4 | # Stripthe new line from the list
5 | for index in range(len(line)):
6 | line[index] = line[index].rstrip('\n')
7 | # print(line) Years list from 2009-1903
8 |
9 |
10 | # chron_line = line[-1::-1] # Years list from 1903-2009
11 | #print(chron_line)
12 |
13 | world_series_count = perf_func(line)
14 | result_dict = perf_func2(line, world_series_count)
15 |
16 | search_year = int(input('Enter a year between 1903 and 2009: '))
17 | while search_year == 1904 or search_year == 1994:
18 | print('There was no world cup in', search_year)
19 | search_year = int(input('Enter another year: '))
20 |
21 | if search_year in result_dict:
22 | print(result_dict[search_year], 'won in', search_year)
23 | print('They won a total of', world_series_count[result_dict[search_year]], 'times')
24 | else:
25 | print('That year was not found.')
26 |
27 |
28 | def perf_func(world_series_list):
29 | found = False
30 | world_series_dict = {}
31 | count_word = 1
32 |
33 | for item in world_series_list:
34 | if item not in world_series_dict:
35 | world_series_dict[item] = count_word
36 | else:
37 | found =True
38 | count_word = world_series_dict[item] + 1
39 | world_series_dict[item] = count_word
40 | count_word = 1
41 |
42 | #print(world_series_dict)
43 | return world_series_dict
44 | print()
45 |
46 |
47 | def perf_func2(reverse_chron_list, series_dict):
48 | new_dict = dict()
49 | skip = False
50 | year = 1903
51 | counter = 0
52 |
53 | for item in reverse_chron_list:
54 | if item.startswith('World'):
55 | # print(item)
56 | skip = True
57 | else:
58 | new_dict[year] = item
59 | year += 1
60 | skip = False
61 |
62 | # for index in range(len(reverse_chron_list)):
63 | # if reverse_chron_list[index].startswith('World'):
64 | # skip = True
65 | # new_dict[year] = reverse_chron_list[index]
66 | # year += 1
67 |
68 | return new_dict
69 |
70 |
71 | # print(new_dict)
72 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/Examples/__pycache__/contact.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter10/Examples/__pycache__/contact.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/Examples/contact.py:
--------------------------------------------------------------------------------
1 | # The contact class holds contact information
2 |
3 | class Contact:
4 | # The __init__ method initializes the attributes
5 | def __init__(self, name, phone, email):
6 | self.__name = name
7 | self.__phone = phone
8 | self.__email = email
9 |
10 | # The set_name method sets the name attributes
11 | def set_name(self, name):
12 | self.__name = name
13 |
14 | # The set_phone method sets the phone attributes
15 | def set_phone(self, phone):
16 | self.__phone = phone
17 |
18 | # The set_email method sets the email attributes
19 | def set_email(self, email):
20 | self.__email = email
21 |
22 | # The get_name method returns the name attributes
23 | def get_name(self):
24 | return self.__name
25 |
26 | # The get_phone method returns the phone attributes
27 | def get_phone(self):
28 | return self.__phone
29 |
30 | # The get_email method returns the email attributes
31 | def get_email(self):
32 | return self.__email
33 |
34 | # The __str__method returns the object's state
35 | def __str__(self):
36 | return 'Name: ' + self.__name + \
37 | '\nPhone: ' + self.__phone + \
38 | '\nEmail: ' + self.__email
39 |
40 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/Examples/contact_manager.py:
--------------------------------------------------------------------------------
1 | import contact
2 | import pickle
3 |
4 | # Global constants for menu choices
5 | LOOK_UP = 1
6 | ADD = 2
7 | CHANGE = 3
8 | DELETE = 4
9 | QUIT = 5
10 |
11 | # Global constants for the file name
12 | FILENAME = 'contacts.dat'
13 |
14 | def main():
15 | # Load the existing contacts dictionary
16 | # and ssign it to mycontacts
17 | mycontacts = load_contacts()
18 |
19 | choice = 0
20 | while choice != QUIT:
21 | choice = get_menu_choice()
22 |
23 | if choice == LOOK_UP:
24 | look_up(mycontacts)
25 | elif choice == ADD:
26 | add(mycontacts)
27 | elif choice == CHANGE:
28 | change(mycontacts)
29 | elif choice == DELETE:
30 | delete(mycontacts)
31 |
32 | # Sve the mycontacts dictionary to a file
33 | # print(mycontacts)
34 | save_contacts(mycontacts)
35 |
36 |
37 | def get_menu_choice():
38 | print()
39 | print('Menu')
40 | print('-----------------------------')
41 | print('1. Look up a contact')
42 | print('2. Add a new contact')
43 | print('3. Change an existing contact')
44 | print('4. Delete a contact')
45 | print('5. Quit the program.')
46 |
47 | choice = int(input('Enter your choice: '))
48 | # Validate the choice
49 | while choice < LOOK_UP or choice > QUIT:
50 | choice = int(input('Enter a valid choice: '))
51 | return choice
52 |
53 |
54 | def load_contacts():
55 | try:
56 | input_file = open(FILENAME, 'rb')
57 | contact_dct = pickle.load(input_file)
58 |
59 | input_file.close()
60 |
61 | except IOError:
62 | # Could not open the file, so create
63 | # an empty dictionary
64 | contact_dct = {}
65 |
66 | return contact_dct
67 |
68 |
69 | def look_up(mycontacts):
70 | name = input('Enter a name: ')
71 | print(mycontacts.get(name, 'That name is not found.'))
72 |
73 |
74 | def add(mycontacts):
75 | name = input('Name: ')
76 | phone = input('Phone: ')
77 | email = input('Email: ')
78 |
79 | # Create a contact object named entry
80 | entry = contact.Contact(name, phone, email)
81 |
82 | if name not in mycontacts:
83 | mycontacts[name] = entry
84 | print('The entry has been added.')
85 | else:
86 | print('That name already exists.')
87 |
88 |
89 | def change(mycontacts):
90 | name = input('Enter a name: ')
91 | if name in mycontacts:
92 | # Get a new phone number
93 | phone = input('Enter a new phone number: ')
94 | # Get a new email address
95 | email = input('Enter the new email address: ')
96 |
97 | # Create a contact object named entry
98 | entry = contact.Contact(name, phone, email)
99 | mycontacts[name] = entry
100 |
101 | print('Information updated.')
102 |
103 | else:
104 | print('That name is not found.')
105 |
106 |
107 | def delete(mycontacts):
108 | name = input('Enter a name: ')
109 | if name in mycontacts:
110 | del mycontacts[name]
111 | print('Entry deleted.')
112 | else:
113 | print('That name is not found.')
114 |
115 |
116 | def save_contacts(mycontacts):
117 | output_file = open(FILENAME, 'wb')
118 | pickle.dump(mycontacts, output_file)
119 | output_file.close()
120 |
121 |
122 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/Examples/contacts.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter10/Examples/contacts.dat
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/__pycache__/employee_class.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter10/ProgrammingExercises/__pycache__/employee_class.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/car_class.py:
--------------------------------------------------------------------------------
1 | class Car:
2 | def __init__(self, year_model, make, speed):
3 | self.__year_model = year_model
4 | self.__make = make
5 | self.__speed = speed
6 |
7 | def set_year_model(self, year_model):
8 | self.__year_model = year_model
9 |
10 | def set_make(self, make):
11 | self.__make = make
12 |
13 | def get_year_model(self):
14 | return self.__year_model
15 |
16 | def get_make(self):
17 | return self.__make
18 |
19 | def set_speed(self, speed):
20 | self.__speed = speed
21 |
22 | def accelerate(self):
23 | self.__speed += 5
24 |
25 | def brake(self):
26 | self.__speed -= 5
27 |
28 | def get_speed(self):
29 | return self.__speed
30 |
31 |
32 | def main():
33 | # Create the car object name my_car
34 | my_car = Car(2003, 'BMW', 100)
35 |
36 | # Set the curent speed to 0
37 | my_car.set_speed(0)
38 |
39 | # Call the accelerate method 5 times
40 | for i in range(5):
41 | my_car.accelerate()
42 | print('Current Speed Of the Car:', my_car.get_speed())
43 | print()
44 |
45 | # Call the brake method 5 times
46 | for j in range(5):
47 | my_car.brake()
48 | print('Current Speed Of the Car:', my_car.get_speed())
49 |
50 | main()
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/dictionary.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter10/ProgrammingExercises/dictionary.dat
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/employee_class.py:
--------------------------------------------------------------------------------
1 | # Create an employee class
2 | class Employee:
3 | def __init__(self, name, id_number, department, job_title):
4 | self.__name = name
5 | self.__id = id_number
6 | self.__dept = department
7 | self.__title = job_title
8 |
9 | # Create the mutator methods
10 | def set_name(self, name):
11 | self.__name = name
12 |
13 | def set_id(self, id_number):
14 | self.__id = id_number
15 |
16 | def set_department(self, department):
17 | self.__dept = department
18 |
19 | def set_title(self, job_title):
20 | self.__title = job_title
21 |
22 | # Create the accessor methods
23 | def get_name(self):
24 | return self.__name
25 |
26 | def get_id(self):
27 | return self.__id
28 |
29 | def get_department(self):
30 | return self.__dept
31 |
32 | def get_title(self):
33 | return self.__title
34 |
35 | def __str__(self):
36 | return 'Name: ' + self.__name + '\n' \
37 | 'ID Number: ' + self.__id + '\n' \
38 | 'Department: ' + self.__dept + '\n' \
39 | 'Job Title: ' + self.__title
40 |
41 |
42 | # def main():
43 | # # Create three employee objects
44 | # emp1 = Employee('Susam Meyers', '47899', 'Accounting', 'Vice President')
45 | # emp2 = Employee('Mark Jones', '39119', 'IT', 'Programmer')
46 | # emp3 = Employee('Joy Rogers', '81774', 'Manufacturing', 'Engineer')
47 |
48 | # # Display the data of each employee
49 |
50 | # print('Here are the datas of the employees...')
51 | # print('======================================')
52 | # print()
53 |
54 | # print('EMPLOYEE 1.')
55 | # print('-----------')
56 | # print('Name:', emp1.get_name())
57 | # print('ID Number:', emp1.get_id())
58 | # print('Department:', emp1.get_department())
59 | # print('Job Title:', emp1.get_title())
60 |
61 | # print()
62 | # print('EMPLOYEE 2.')
63 | # print('-----------')
64 | # print('Name:', emp2.get_name())
65 | # print('ID Number:', emp2.get_id())
66 | # print('Department:', emp2.get_department())
67 | # print('Job Title:', emp2.get_title())
68 |
69 | # print()
70 | # print('EMPLOYEE 3.')
71 | # print('-----------')
72 | # print('Name:', emp3.get_name())
73 | # print('ID Number:', emp3.get_id())
74 | # print('Department:', emp3.get_department())
75 | # print('Job Title:', emp3.get_title())
76 |
77 | # main()
78 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/employee_management.py:
--------------------------------------------------------------------------------
1 | import employee_class
2 | import pickle
3 |
4 | LOOK_UP = 1
5 | ADD = 2
6 | CHANGE = 3
7 | DELETE = 4
8 | QUIT = 5
9 |
10 | # Create a file name
11 | FILENAME = 'dictionary.dat'
12 |
13 | def main():
14 | # load the contents of the dictionary
15 | my_data = load_data()
16 |
17 | # Initialize choice
18 | choice = 0
19 | while choice != QUIT:
20 | choice = display_menu_choice()
21 | if choice == LOOK_UP:
22 | look_up(my_data)
23 | elif choice == ADD:
24 | add(my_data)
25 | elif choice == CHANGE:
26 | change(my_data)
27 | elif choice == DELETE:
28 | delete(my_data)
29 |
30 | # save the contents
31 | save_data(my_data)
32 |
33 |
34 | def load_data():
35 | try:
36 | # Read the contents of a binary file
37 | input_file = open(FILENAME, 'rb')
38 | # Load the content of the file
39 | dictionary_dct = pickle.load(input_file)
40 | input_file.close()
41 |
42 | except IOError:
43 | # If there is nothing inside the ditionary
44 | # then create an empty dictionary
45 | dictionary_dct = {}
46 |
47 | return dictionary_dct
48 |
49 |
50 | def display_menu_choice():
51 | print('MENU')
52 | print('--------------------------------')
53 | print('1. Look up an employee ID Number')
54 | print('2. Add an ID')
55 | print('3. Change an ID Number')
56 | print('4. Delete an ID')
57 | print('5. Quit the program.')
58 |
59 | choice = int(input('Enter Your Choice: '))
60 | # Validate the choice
61 | while choice < LOOK_UP or choice > QUIT:
62 | choice = int(input('Enter a valid choice: '))
63 |
64 | return choice
65 |
66 |
67 | # Look up function
68 | # Look up an id number in the dictionary
69 | def look_up(my_data):
70 | id_num = input('Enter an ID Number: ')
71 | print(my_data.get(id_num, 'ID not found.'))
72 |
73 |
74 | # add function adds data to the dictionary if not found
75 | def add(my_data):
76 | id_num = input('Enter an ID Number: ')
77 | name = input('Enter your name: ')
78 | dept = input('Enter the department: ')
79 | title = input('Enter the job title: ')
80 |
81 | # Create an instance of the employee class named entry
82 | entry = employee_class.Employee(name, id_num, dept, title)
83 |
84 | # If id num not in dictionary, add it as a key with
85 | # the entry object as value
86 | if id_num not in my_data:
87 | my_data[id_num] = entry
88 | print('The entry has been added.')
89 | else:
90 | print('That name already exists.')
91 |
92 |
93 | def change(my_data):
94 | id_num = input('Enter an ID: ')
95 | if id_num in my_data:
96 | name = input('Enter your name: ')
97 | dept = input('Enter the department: ')
98 | title = input('Enter the job title: ')
99 |
100 | entry = employee_class.Employee(name, id_num, dept, title)
101 | my_data[id_num] = entry
102 | print('Entry has been updated.')
103 | else:
104 | print('That ID was not found.')
105 |
106 |
107 | def delete(my_data):
108 | id_num = input('Enter an ID: ')
109 | if id_num in my_data:
110 | del my_data[id_num]
111 | print('Data has been deleted.')
112 | else:
113 | print('That ID was not found.')
114 |
115 |
116 | def save_data(my_data):
117 | output_file = open(FILENAME, 'wb')
118 | pickle.dump(my_data, output_file)
119 | output_file.close()
120 |
121 | main()
122 |
123 |
124 |
125 |
126 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/personal_information.py:
--------------------------------------------------------------------------------
1 | # Create a person class
2 | class Person:
3 | # Initialize the person attibutes
4 | def __init__(self, name, address, age, phone):
5 | self.__name = name
6 | self.__address = address
7 | self.__age = age
8 | self.__phone = phone
9 |
10 |
11 | # Create mutator methods for the attributes
12 | def set_name(self, name):
13 | self.__name = name
14 |
15 | def set_address(self, address):
16 | self.__address = address
17 |
18 | def set_age(self, age):
19 | self.__age = age
20 |
21 | def set_phone(self, phone):
22 | self.__phone = phone
23 |
24 | # Create thr mutator methods
25 | def get_name(self):
26 | return self.__name
27 |
28 | def get_address(self):
29 | return self.__address
30 |
31 | def get_age(self):
32 | return self.__age
33 |
34 | def get_phone(self):
35 | return self.__phone
36 |
37 | # Return the current state of the object
38 | def __str__(self):
39 | return 'Name: ' + self.__name + '\n' \
40 | 'Address: ' + self.__address + '\n' \
41 | 'Age: ' + str(self.__age) + '\n' \
42 | 'Phone: ' + self.__phone
43 |
44 |
45 | # Create the main function
46 | def main():
47 | # Create 3 objects, one for you, one for
48 | # your friend and one for your family
49 | my_personal_info = Person('Tunde Muhamed', 'tundemuhamed@gmail.com', 29, '070-3321-6997')
50 | my_fiend_info = Person('Shina Onilude', 'shinapee@gmail.com', 30, '081-3262-1388')
51 | my_family_info = Person('Abodunrin Bashiry', 'ILUPEJU 2, Mosobolatan House.', 63, '080-6076-5926')
52 |
53 | print('These are the details of the personal\ninformation you entered...')
54 | print('=====================================')
55 | print()
56 | print('My Personal Details')
57 | print('-------------------')
58 | print(my_personal_info)
59 |
60 | print()
61 | print('My Friend Details')
62 | print('-----------------')
63 | print(my_fiend_info)
64 |
65 | print()
66 | print('My Personal Member Details')
67 | print('--------------------------')
68 | print(my_family_info)
69 |
70 | main()
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter10/ProgrammingExercises/retail_item_class.py:
--------------------------------------------------------------------------------
1 | class RetailItem:
2 | def __init__(self, description, units_in_inventory, price):
3 | self.__descr = description
4 | self.__inventory = units_in_inventory
5 | self.__price = price
6 |
7 | def set_description(self, description):
8 | self.__descr = description
9 |
10 | def set_units_in_inventory(self, units_in_inventory):
11 | self.__inventory = units_in_inventory
12 |
13 | def set_price(self, price):
14 | self.__price = price
15 |
16 | def get_description(self):
17 | return self.__descr
18 |
19 | def get_units_in_inventory(self):
20 | return self.__inventory
21 |
22 | def get_price(self):
23 | return self.__price
24 |
25 | # Define the str method to return the state of the objects
26 | def __str__(self):
27 | return 'Description: ' + self.__descr + '\n' \
28 | 'Units In Inventory: ' + str(self.__inventory) + '\n' \
29 | 'Price: ' + str(self.__price)
30 |
31 |
32 | def main():
33 | item1 = RetailItem('Jacket', 12, 59.95)
34 | item2 = RetailItem('Designer Jeans', 40, 34.95)
35 | item3 = RetailItem('Shirt', 20, 24.95)
36 |
37 | print('These are the details of each item:')
38 | print('==================================')
39 | print()
40 |
41 | print('Item 1.')
42 | print('------')
43 | print(item1)
44 | print()
45 |
46 | print('Item 2.')
47 | print('------')
48 | print(item2)
49 | print()
50 |
51 | print('Item 3.')
52 | print('------')
53 | print(item3)
54 |
55 | main()
56 |
57 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Examples/__pycache__/animals.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter11/Examples/__pycache__/animals.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Examples/animals.py:
--------------------------------------------------------------------------------
1 | # The mammal class represents a generic mammal
2 | class Mammal:
3 |
4 | # The __init__ method accept arguments for
5 | # The mammal's species
6 | def __init__(self, species):
7 | self.__species = species
8 |
9 | # The show species method displays a message
10 | # indicating the mammal's species
11 | def show_species(self):
12 | print('I am a', self.__species)
13 |
14 | # The make sound method is the mammal's
15 | # way of making a generic sound
16 | def make_sound(self):
17 | print('Grrrrr')
18 |
19 |
20 | # The Dog class is a subclass of mammal class
21 | class Dog(Mammal):
22 | # The init method calls the superclass's
23 | # init method passing Dog as the species
24 | def __init__(self):
25 | Mammal.__init__(self, 'Dog')
26 |
27 | # the make sound method overrides the superclass's
28 | # make_sound method
29 | def make_sound(self):
30 | print('Woof! woof!')
31 |
32 |
33 | class Cat(Mammal):
34 | def __init__(self):
35 | Mammal.__init__(self, 'Cat')
36 |
37 | def make_sound(self):
38 | print('Meow')
39 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Examples/polymorphism_demo.py:
--------------------------------------------------------------------------------
1 | import animals
2 |
3 | def main():
4 | mammal = animals.Mammal('regular animal')
5 | dog = animals.Dog()
6 | cat = animals.Cat()
7 |
8 | print('Here are some animals and\nthe sound they make:')
9 | print('-------------------------')
10 |
11 | show_mammal_info(mammal)
12 | print()
13 |
14 | show_mammal_info(dog)
15 | print()
16 |
17 | show_mammal_info(cat)
18 |
19 |
20 | def show_mammal_info(creature):
21 | creature.show_species()
22 | creature.make_sound()
23 |
24 | main()
25 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Examples/polymorphism_demo2.py:
--------------------------------------------------------------------------------
1 | import animals
2 |
3 | def main():
4 | mammal = animals.Mammal('regular animal')
5 | dog = animals.Dog()
6 | cat = animals.Cat()
7 |
8 | print('Here are some animals and\nthe sound they make:')
9 | print('-------------------------')
10 |
11 | show_mammal_info(mammal)
12 | print()
13 |
14 | show_mammal_info(dog)
15 | print()
16 |
17 | show_mammal_info(cat)
18 | print()
19 |
20 | show_mammal_info('I am a string')
21 |
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()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Examples/wrong_type.py:
--------------------------------------------------------------------------------
1 | import animals
2 |
3 | def main():
4 | # mammal = animals.Mammal('regular animal')
5 | # dog = animals.Dog()
6 | # cat = animals.Cat()
7 |
8 | # print('Here are some animals and\nthe sound they make:')
9 | # print('-------------------------')
10 |
11 | # show_mammal_info(mammal)
12 | # print()
13 |
14 | # show_mammal_info(dog)
15 | # print()
16 |
17 | # show_mammal_info(cat)
18 | # print()
19 |
20 | # Pass a wrong object to the show_mammal function
21 | show_mammal_info('I am a string')
22 |
23 |
24 | def show_mammal_info(creature):
25 | creature.show_species()
26 | creature.make_sound()
27 |
28 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Programming Exercises/__pycache__/employee_production_worker.cpython-37.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/legendbabs/StartingOutWithPython/f52b8c4cd50049bb3802eeb274c6e4869de0058b/StartOutWithPython/Chapter11/Programming Exercises/__pycache__/employee_production_worker.cpython-37.pyc
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Programming Exercises/employee_production_supervisor_worker_demo.py:
--------------------------------------------------------------------------------
1 | import employee_production_worker
2 |
3 | # main function
4 | def main():
5 | name = input('Enter the production worker name: ')
6 | number = input('Enter the production worker number: ')
7 | shift = int(input('Enter the production worker shift number: '))
8 | payrate = float(input('Enter the hourly payrate of the worker: '))
9 |
10 | print()
11 | print('Enter The Shift Supervisor Info')
12 | name_supo = input('Enter the Shift Supervisor name: ')
13 | number_supo = input('Enter the Shift Supervisor number: ')
14 | salary = float(input('Enter the Shift Supervisor Annual Salary: '))
15 | bonus = float(input('Enter the Shift Supervisor Bonus: '))
16 |
17 |
18 |
19 | # Create an instance of ProductionWorker class
20 | production_worker = employee_production_worker.ProductionWorker(name, number, shift, payrate)
21 | shift_supo = employee_production_worker.ShiftSupervisor(name_supo, number_supo, salary, bonus)
22 | print()
23 |
24 | # Display the employee datas
25 | print('These are the ProductionWorker datas:')
26 | print('=====================================')
27 | print('Production Worker Name:', production_worker.get_employee_name())
28 | print('Production Worker Number:', production_worker.get_employee_number())
29 | # print('Shift Number:', production_worker.get_shift_number(), '===>', end='')
30 |
31 | # Display whether the employee has a day shift or night shift
32 | if production_worker.get_shift_number() == 1:
33 | print('YOU WORKED ON DAY SHIFT.')
34 | elif production_worker.get_shift_number() == 2:
35 | print('YOU WORKED ON NIGHT SHIFT.')
36 | else:
37 | print('Invalid shift number!')
38 |
39 | print('Production Worker Pay Rate: $', format(production_worker.get_hourly_payrate(), ',.2f'), sep='')
40 |
41 | print()
42 | print('These are the shift supervisor info:')
43 | print('====================================')
44 | print()
45 |
46 | print('Shift Supervisor Name:', shift_supo.get_employee_name())
47 | print('Shift Supervisor Number:', shift_supo.get_employee_number())
48 | print('Shift Supervisor Salary: $', shift_supo.get_annual_salary(), sep='')
49 | print('Shift Supervisor Bonus: $', shift_supo.get_annual_production_bonus(), sep='')
50 |
51 |
52 | main()
53 |
54 |
55 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Programming Exercises/employee_production_worker.py:
--------------------------------------------------------------------------------
1 | # Create an employee class
2 |
3 | class Employee:
4 | # initialize the attributes
5 | def __init__(self, employee_name, employee_number):
6 | self.__employee_name = employee_name
7 | self.__employee_number = employee_number
8 |
9 | # Create the mutator methods
10 | def set_employee_name(self, employee_name):
11 | self.__employee_name = employee_name
12 |
13 | def set_employee_number(self, employee_number):
14 | self.__employee_number = employee_number
15 |
16 | # create the accessor methods
17 | def get_employee_name(self):
18 | return self.__employee_name
19 | def get_employee_number(self):
20 | return self.__employee_number
21 |
22 |
23 | # Create a production worker class
24 | class ProductionWorker(Employee):
25 | def __init__(self, employee_name, employee_number, shift_number, hourly_pay):
26 |
27 | # Call the superclass init method
28 | Employee.__init__(self, employee_name, employee_number)
29 |
30 | # Initialize the producton class attributes
31 | self.__shift_number = shift_number
32 | self.__hourly_payrate = hourly_pay
33 |
34 | # Mutator methods
35 | def set_shift_number(self, shift_number):
36 | self.__shift_number = shift_number
37 |
38 | def set_hourly_payrate(self, hourly_pay):
39 | self.__hourly_payrate = hourly_pay
40 |
41 | # Gettor methods
42 | def get_shift_number(self):
43 | return self.__shift_number
44 |
45 | def get_hourly_payrate(self):
46 | return self.__hourly_payrate
47 |
48 |
49 | # Create a ShiftSupervisor class
50 | class ShiftSupervisor(Employee):
51 | def __init__(self, employee_name, employee_number, annual_salary, annual_production_bonus):
52 | # Call the Employee class __init__ method
53 | Employee.__init__(self, employee_name, employee_number)
54 |
55 | # Initialize the salary and bonus attributes
56 | self.__annual_salary = annual_salary
57 | self.__annual_production_bonus = annual_production_bonus
58 |
59 | # Create the settor method for salary and bonus
60 | def set_annual_salary(self, annual_salary):
61 | self.__annual_salary = annual_salary
62 |
63 | def set_annual_production_bonus(self, annual_production_bonus):
64 | self.__annual_production_bonus = annual_production_bonus
65 |
66 | # Create the gettor methods
67 | def get_annual_salary(self):
68 | return self.__annual_salary
69 |
70 | def get_annual_production_bonus(self):
71 | return self.__annual_production_bonus
72 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Programming Exercises/person_and_customer_classes.py:
--------------------------------------------------------------------------------
1 | # Create a person class
2 |
3 | class Person:
4 | def __init__(self, name, address, number):
5 | self.__name = name
6 | self.__address = address
7 | self.__number = number
8 |
9 | # Settor methods
10 | def set_name(self, name):
11 | self.__name = name
12 |
13 | def set_address(self, address):
14 | self.__address = address
15 |
16 | def set_number(self, number):
17 | self.__number = number
18 |
19 | # Gettor methods
20 | def get_name(self):
21 | return self.__name
22 |
23 | def get_address(self):
24 | return self.__address
25 |
26 | def get_number(self):
27 | return self.__number
28 |
29 |
30 | class Customer(Person):
31 | def __init__(self, name, address, number, wishes_to_be_on_a_mailing_list = False):
32 | Person.__init__(self, name, address, number)
33 |
34 | self.__wishes_to_be_on_a_mailing_list = wishes_to_be_on_a_mailing_list
35 |
36 | def set_wishes(self, wishes_to_be_on_a_mailing_list):
37 | self.__wishes_to_be_on_a_mailing_list = wishes_to_be_on_a_mailing_list
38 |
39 | def get_wishes(self):
40 | return self.__wishes_to_be_on_a_mailing_list
41 |
42 |
43 | def main():
44 |
45 | customer = Customer('Tunde Muhamed', 'tm@gmail.com', '070-3321-6997')
46 | print('Customer Name:', customer.get_name())
47 | print('Customer Address:', customer.get_address())
48 | print('Customer Number:', customer.get_number())
49 |
50 | # print('Do you wish to be on the mailing list? (Y/n):', end='')
51 | # response = input()
52 |
53 | # if response.lower() == 'y':
54 | if customer.get_wishes():
55 | print('You wish to be on the mailing list.')
56 | else:
57 | print('You wish not to be on the mailing list.')
58 |
59 |
60 | main()
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter11/Programming Exercises/shift_supervisor_demo.py:
--------------------------------------------------------------------------------
1 | import employee_production_worker
2 |
3 | def main():
4 | shift_supo = employee_production_worker.ShiftSupervisor('Tunde Muhamed', '070-3321-6997', 15000.0, 3500.0)
5 | print('These are the shift supervisor info:')
6 | print('====================================')
7 | print()
8 |
9 | print('Supervisor Name:', shift_supo.get_employee_name())
10 | print('Supervisor Number:', shift_supo.get_employee_number())
11 | print('Salary: $', shift_supo.get_annual_salary(), sep='')
12 | print('Bonus: $', shift_supo.get_annual_production_bonus(), sep='')
13 |
14 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Example/endless_recursion.py:
--------------------------------------------------------------------------------
1 | def main():
2 |
3 | message()
4 |
5 |
6 | def message():
7 | print('This is a recursive function.')
8 | # message()
9 |
10 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Example/recursive.py:
--------------------------------------------------------------------------------
1 | # This program has a recursive function
2 |
3 | def main():
4 | message(5)
5 |
6 | def message(times):
7 | if times > 0:
8 | print('This is a recursive function.')
9 | message(times-1)
10 |
11 |
12 | main()
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Example/try.py:
--------------------------------------------------------------------------------
1 | # def greetings(times):
2 | # if times > 0:
3 | # print('Hello world!')
4 | # greetings(times-1)
5 |
6 | # greetings(5)
7 |
8 | def main():
9 | factorial(n)
10 |
11 | def factorial(num):
12 | fact =
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Programming Exercise/largest_list_item.py:
--------------------------------------------------------------------------------
1 | def main():
2 | list_items = [3, 5, 6, 9, 8, 10, 15, 2, 1, 7]
3 |
4 | largest_list_items(list_items, 0, len(list_items)-1)
5 |
6 |
7 |
8 | def largest_list_items(items, start, end):
9 | if end > start:
10 | if items[start] > items[start+1]:
11 | del items[start+1]
12 | else:
13 | del items[start]
14 | largest_list_items(items, start, end-1)
15 |
16 | if end == 1:
17 | # return items[0]
18 | print('Largest Number Is:', items[0])
19 |
20 | main()
21 |
22 |
23 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Programming Exercise/recursive_lines.py:
--------------------------------------------------------------------------------
1 | # First method with the main function
2 | def main():
3 | number = int(input('Enter a number: '))
4 | recursive_line(number, 1)
5 |
6 | def recursive_line(n, start):
7 | if n > 0:
8 | print('*' * start)
9 | start += 1
10 | recursive_line(n-1, start)
11 |
12 | main()
13 |
14 |
15 | # Second Method Without the main function
16 | number = int(input('Enter a number: '))
17 | def recursive_line(n, start):
18 | if n > 0:
19 | print('*' * start)
20 | start += 1
21 | recursive_line(n-1, start)
22 |
23 | recursive_line(number, 1)
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Programming Exercise/recursive_list_sum.py:
--------------------------------------------------------------------------------
1 | # def main():
2 | # list_items = [3, 5, 6, 9, 8, 10, 15, 2, 1, 7]
3 |
4 | # total = recursive_list_sum(list_items, 0, len(list_items)-1)
5 | # print('Total Is:', total)
6 |
7 | # def recursive_list_sum(items, start, end):
8 | # if start > end:
9 | # return 0
10 | # else:
11 | # return items[start] + recursive_list_sum(items, start+1, end)
12 |
13 |
14 | # main()
15 |
16 | n = int(input('Enter a number: '))
17 | total = 0
18 |
19 | def sum_number(n, total):
20 | if n > 0:
21 | total += n
22 | sum_number(n-1, total)
23 | if n == 1:
24 | print(total)
25 |
26 | sum_number(n, total)
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Programming Exercise/recursive_multiplication.py:
--------------------------------------------------------------------------------
1 | def main():
2 | num1 = int(input('Enter a number: '))
3 | num2 = int(input('Enter another number: '))
4 |
5 | result = recursive_mul(num1, num2)
6 | print(num1, '*', num2, 'is:', result)
7 |
8 | def recursive_mul(x, y):
9 | if x > 0 and y > 0:
10 | return x + recursive_mul(x, y-1)
11 | else:
12 | return 0
13 |
14 | main()
15 |
16 |
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Programming Exercise/recursive_power.py:
--------------------------------------------------------------------------------
1 | x = int(input('Enter first number: '))
2 | y = int(input('Enter second number: '))
3 | result = 1
4 |
5 | def multiplication(y, x, result):
6 | if y > 0:
7 | result *= x
8 | multiplication(y-1, x, result)
9 | if y == 1:
10 | print(result)
11 |
12 | multiplication(y, x, result)
--------------------------------------------------------------------------------
/StartOutWithPython/Chapter12/Programming Exercise/recursive_printing.py:
--------------------------------------------------------------------------------
1 | # First method
2 | def main():
3 | number = int(input('Enter a number: '))
4 | recursive_printing(number)
5 |
6 |
7 | def recursive_printing(n):
8 | if n > 0:
9 | print(n)
10 | recursive_printing(n-1)
11 |
12 | main()
13 |
14 |
15 | # second method
16 | def main():
17 | number = int(input('Enter a number: '))
18 | recursive_printing(number, 1)
19 |
20 |
21 | def recursive_printing(n, start):
22 | if n > 0:
23 | print(start)
24 | start += 1
25 | recursive_printing(n-1, start)
26 |
27 | main()
28 |
--------------------------------------------------------------------------------