├── .gitignore ├── Chapter_01 └── hello_world.py ├── Chapter_02 ├── Exercises │ ├── 2-11.py │ ├── comment.py │ ├── name_case_2-3.py │ ├── name_case_2-4.py │ ├── name_case_2-5.py │ ├── name_case_2-6.py │ ├── name_case_2-7.py │ ├── number_case_2-8.py │ ├── number_case_2-9.py │ ├── simple_message.py │ └── simple_messages.py ├── apostrophe.py ├── hello_world.py └── name.py ├── Chapter_03 ├── Exercises │ ├── 3-1.py │ ├── 3-2.py │ ├── 3-3.py │ ├── 3-4.py │ ├── 3-5.py │ ├── 3-6.py │ ├── 3-7.py │ ├── 3-8.py │ └── 3-9.py ├── bicycles.py ├── cars.py └── motorcycles.py ├── Chapter_04 ├── Exercises │ ├── 4-1.py │ ├── 4-10.py │ ├── 4-11.py │ ├── 4-12.py │ ├── 4-13.py │ ├── 4-2.py │ ├── 4-3.py │ ├── 4-4.py │ ├── 4-5.py │ ├── 4-6.py │ ├── 4-7.py │ ├── 4-8.py │ └── 4-9.py ├── dimensions.py ├── even_numbers.py ├── foods.py ├── magicians.py ├── numbers.py ├── players.py └── squares.py ├── Chapter_05 ├── Exercises │ ├── 5-1.py │ ├── 5-10.py │ ├── 5-11.py │ ├── 5-2.py │ ├── 5-3.py │ ├── 5-4.py │ ├── 5-5.py │ ├── 5-6.py │ ├── 5-7.py │ ├── 5-8.py │ └── 5-9.py ├── amusement_park.py ├── banned_users.py ├── cars.py ├── magic_number.py ├── toppings.py └── voting.py ├── Chapter_06 ├── Exercises │ ├── 6-1.py │ ├── 6-10.py │ ├── 6-2.py │ ├── 6-3.py │ ├── 6-4.py │ ├── 6-5.py │ ├── 6-6.py │ ├── 6-7.py │ ├── 6-8.py │ └── 6-9.py ├── alien.py ├── aliens.py ├── favorite_languages.py ├── many_users.py ├── pizza.py └── user.py ├── Chapter_07 ├── Exercises │ ├── 7-1.py │ ├── 7-10.py │ ├── 7-2.py │ ├── 7-3.py │ ├── 7-4.py │ ├── 7-5.py │ ├── 7-6.py │ ├── 7-7.py │ ├── 7-8.py │ └── 7-9.py ├── age.py ├── cities.py ├── confirmed_users.py ├── counting.py ├── even_or_odd.py ├── greeter.py ├── mountain_poll.py ├── parrot.py ├── pets.py └── rollercoaster.py ├── Chapter_08 ├── Exercises │ ├── 8-1.py │ ├── 8-10.py │ ├── 8-11.py │ ├── 8-12.py │ ├── 8-13.py │ ├── 8-14.py │ ├── 8-15.py │ ├── 8-16.py │ ├── 8-2.py │ ├── 8-3.py │ ├── 8-4.py │ ├── 8-5.py │ ├── 8-6.py │ ├── 8-7.py │ ├── 8-8.py │ ├── 8-9.py │ └── single_function.py ├── formatted_name.py ├── greeter.py ├── making_pizza.py ├── person.py ├── pets.py ├── pizza.py ├── printing_models.py └── user_profile.py ├── Chapter_09 ├── Exercises │ ├── 9-1.py │ ├── 9-10.py │ ├── 9-11.py │ ├── 9-12.py │ ├── 9-13-solution-2.py │ ├── 9-13.py │ ├── 9-14.py │ ├── 9-2.py │ ├── 9-3.py │ ├── 9-4.py │ ├── 9-5.py │ ├── 9-6.py │ ├── 9-7.py │ ├── 9-8.py │ ├── 9-9.py │ ├── admin.py │ ├── privileges.py │ └── restaurant.py ├── car.py ├── dog.py ├── electric_car.py ├── favorite.languages.py ├── my_car.py └── my_electric_car.py ├── Chapter_10 ├── Exercises │ ├── 10-1.py │ ├── 10-10.py │ ├── 10-11.py │ ├── 10-12.py │ ├── 10-13.py │ ├── 10-2.py │ ├── 10-3.py │ ├── 10-4.py │ ├── 10-5.py │ ├── 10-6.py │ ├── 10-7.py │ ├── 10-8.py │ ├── 10-9.py │ ├── cats.txt │ ├── favorite_number.json │ ├── guest.txt │ ├── guest_book.txt │ ├── gutenberg.txt │ ├── learning_python.txt │ ├── programming_reasons.txt │ └── username.json ├── alice.py ├── alice.txt ├── division.py ├── file_reader.py ├── greet_me.py ├── number.json ├── number_reader.py ├── number_writer.py ├── pi_digits.txt ├── pi_million_digits.txt ├── pi_string.py ├── programing .txt ├── remenber_me.py ├── username.json ├── word_count.py └── write_message.py ├── Chapter_11 ├── Exercises │ ├── cities.py │ ├── employee.py │ ├── test_cities.py │ └── test_employee.py ├── language_survey.py ├── name_function.py ├── names.py ├── survey.py ├── test_name_function.py └── test_survey.py ├── Chapter_15 ├── README.md ├── dice_visual.py ├── die.py ├── die_visual.py ├── different_dice.py ├── figures │ ├── crash_course15-01.png │ ├── crash_course15-02.png │ ├── crash_course15-03.png │ ├── crash_course15-04.png │ ├── crash_course15-05.png │ ├── crash_course15-06.png │ ├── crash_course15-07.png │ ├── crash_course15-08.png │ ├── crash_course15-09.png │ ├── crash_course15-10.png │ ├── crash_course15-11.png │ ├── crash_course15-12.png │ └── crash_course15-13.png ├── mpl_squares.py ├── pygal2_update │ ├── dice_visual.py │ ├── dice_visual.svg │ ├── die.py │ ├── die_visual.py │ └── different_dice.py ├── random_walk.py ├── rw_visual.py └── scatter_squares.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-egg/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .nox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | .pytest_cache/ 50 | 51 | # Jupyter Notebook 52 | .ipynb_checkpoints 53 | 54 | # IPython 55 | profile_default/ 56 | ipython_config.py 57 | 58 | # pyenv 59 | .python-version 60 | 61 | # pytype static type analyzer 62 | .pytype/ 63 | 64 | # mypy 65 | .mypy_cache/ 66 | .dmypy.json 67 | dmypy.json 68 | 69 | # Pyre type checker 70 | .pyre/ 71 | 72 | # PyCharm 73 | .idea/ 74 | 75 | # Environments 76 | .env 77 | .venv 78 | env/ 79 | venv/ 80 | ENV/ 81 | env.bak/ 82 | venv.bak/ 83 | 84 | # Spyder project settings 85 | .spyderproject 86 | .spyproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # mkdocs documentation 92 | /site 93 | 94 | # celery beat schedule file 95 | celerybeat-schedule 96 | 97 | # SageMath parsed files 98 | *.sage.py 99 | 100 | # dotenv 101 | .env* 102 | 103 | # Virtualenv 104 | # Refer to https://github.com/pypa/virtualenv/blob/master/src/virtualenv.py#L925 105 | # for list of supported file extensions for built-in discovery (as of v20.0.10) 106 | lib/ 107 | lib64/ 108 | Include/ 109 | Scripts/ 110 | pyvenv.cfg 111 | -------------------------------------------------------------------------------- /Chapter_01/hello_world.py: -------------------------------------------------------------------------------- 1 | print("Hello World!") 2 | -------------------------------------------------------------------------------- /Chapter_02/Exercises/2-11.py: -------------------------------------------------------------------------------- 1 | import this -------------------------------------------------------------------------------- /Chapter_02/Exercises/comment.py: -------------------------------------------------------------------------------- 1 | # Hello my friend 2 | print("Hello python people!") 3 | 4 | -------------------------------------------------------------------------------- /Chapter_02/Exercises/name_case_2-3.py: -------------------------------------------------------------------------------- 1 | name = "Eric" 2 | print("Hello " + name + ", Would you like to learn some python today?") -------------------------------------------------------------------------------- /Chapter_02/Exercises/name_case_2-4.py: -------------------------------------------------------------------------------- 1 | name = "ASH Eric" 2 | # Lowercase 3 | print(name.lower()) 4 | # Uppercase 5 | print(name.upper()) 6 | # Title 7 | print(name.title()) -------------------------------------------------------------------------------- /Chapter_02/Exercises/name_case_2-5.py: -------------------------------------------------------------------------------- 1 | print("Albert Einstein once said,“A person who never made a mistake never tried anything new.”") -------------------------------------------------------------------------------- /Chapter_02/Exercises/name_case_2-6.py: -------------------------------------------------------------------------------- 1 | famous_person = "Albert Einstein" 2 | message = "A person who never made a mistake never tried anything new." 3 | 4 | print(famous_person + " said: " + message) 5 | -------------------------------------------------------------------------------- /Chapter_02/Exercises/name_case_2-7.py: -------------------------------------------------------------------------------- 1 | full_name = (" \taSh Eric\n ") 2 | print(full_name) 3 | print(full_name.lstrip()) 4 | print(full_name.rstrip()) 5 | print(full_name.strip()) -------------------------------------------------------------------------------- /Chapter_02/Exercises/number_case_2-8.py: -------------------------------------------------------------------------------- 1 | print(3+5) 2 | print(16/2) 3 | print(10-2) 4 | print(2*4) 5 | -------------------------------------------------------------------------------- /Chapter_02/Exercises/number_case_2-9.py: -------------------------------------------------------------------------------- 1 | number = "66" 2 | print(str(number) + " is my lucky number!") -------------------------------------------------------------------------------- /Chapter_02/Exercises/simple_message.py: -------------------------------------------------------------------------------- 1 | message = "message" 2 | print(message) 3 | -------------------------------------------------------------------------------- /Chapter_02/Exercises/simple_messages.py: -------------------------------------------------------------------------------- 1 | message = "Hello" 2 | print(message) 3 | message = "World" 4 | print(message) -------------------------------------------------------------------------------- /Chapter_02/apostrophe.py: -------------------------------------------------------------------------------- 1 | message = "OneofPython'sstrengthsisitsdiversecommunity." 2 | print(message) 3 | 4 | # message='OneofPython'sstrengthsisitsdiversecommunity.' #mistake -------------------------------------------------------------------------------- /Chapter_02/hello_world.py: -------------------------------------------------------------------------------- 1 | message = "Hello Python World!" 2 | print(message) 3 | 4 | message = "Hello Python Crash Course world!" 5 | print(message) -------------------------------------------------------------------------------- /Chapter_02/name.py: -------------------------------------------------------------------------------- 1 | name = "ada lovelace" 2 | print(name.title()) 3 | print(name.lower()) 4 | print(name.upper()) 5 | 6 | first_name = "ada" 7 | last_name = "lovelace" 8 | full_name = first_name + " " +last_name 9 | print(full_name) 10 | print("Hello, "+full_name.title()+"!") 11 | 12 | message = "Hello, "+full_name.title()+"!" 13 | print(message) -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-1.py: -------------------------------------------------------------------------------- 1 | names = ['Eric','Ash','Leroy','Yu'] 2 | print(names[0]) 3 | print(names[1]) 4 | print(names[2]) 5 | print(names[3]) -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-2.py: -------------------------------------------------------------------------------- 1 | names = ['Eric','Ash','Leroy','Yu'] 2 | print("Hi! How are you? " + names[0] + " !") 3 | print("Hi! How are you? " + names[1] + " !") 4 | print("Hi! How are you? " + names[2] + " !") 5 | print("Hi! How are you? " + names[3] + " !") -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-3.py: -------------------------------------------------------------------------------- 1 | commute_modes = ["motorcycle", "car", "bicycle", "bus", "subway", "walking"] 2 | 3 | print("I like " + commute_modes[0] + ".It makes me fun!") 4 | print("I like " + commute_modes[1] + ".It makes me fun!") 5 | print("I like " + commute_modes[2] + ".It makes me fun!") 6 | print("I like " + commute_modes[3] + ".It makes me fun!") 7 | print("I like " + commute_modes[4] + ".It makes me fun!") 8 | print("I like " + commute_modes[5] + ".It makes me fun!") -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-4.py: -------------------------------------------------------------------------------- 1 | guest = ['Mom','Dad','Dude'] 2 | print("Hi "+guest[0]+", Do u wanna go to my lunch?") 3 | print("Hi "+guest[1]+", Do u wanna go to my lunch?") 4 | print("Hi "+guest[2]+", Do u wanna go to my lunch?") -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-5.py: -------------------------------------------------------------------------------- 1 | guest = ['Mom','Dad','Dude'] 2 | 3 | print(guest[-1] + " fail to come to lunch") 4 | guest[-1] = "Shui" 5 | 6 | print("Hi "+guest[0]+", Do u wanna go to my lunch?") 7 | print("Hi "+guest[1]+", Do u wanna go to my lunch?") 8 | print("Hi "+guest[2]+", Do u wanna go to my lunch?") -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-6.py: -------------------------------------------------------------------------------- 1 | guest = ['Mom','Dad','Dude'] 2 | 3 | print('I found a bigger table.') 4 | guest.insert(0,'Shui') 5 | guest.insert(1,'Ker') 6 | guest.append('Snow') 7 | 8 | print(guest[0]+" I hope you can go to my lunch tonight") 9 | print(guest[1]+" I hope you can go to my lunch tonight") 10 | print(guest[2]+" I hope you can go to my lunch tonight") 11 | print(guest[3]+" I hope you can go to my lunch tonight") 12 | print(guest[4]+" I hope you can go to my lunch tonight") 13 | print(guest[5] + " I hope you can go to my lunch tonight") 14 | -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-7.py: -------------------------------------------------------------------------------- 1 | guest = ['Mom','Dad','Dude'] 2 | 3 | print('I found a bigger table.') 4 | guest.insert(0,'Shui') 5 | guest.insert(1,'Ker') 6 | guest.append('Snow') 7 | 8 | print(guest[0]+" I hope you can go to my lunch tonight") 9 | print(guest[1]+" I hope you can go to my lunch tonight") 10 | print(guest[2]+" I hope you can go to my lunch tonight") 11 | print(guest[3]+" I hope you can go to my lunch tonight") 12 | print(guest[4]+" I hope you can go to my lunch tonight") 13 | print(guest[5] + " I hope you can go to my lunch tonight") 14 | 15 | print(guest[-1]+",sorry,i cant invited you today") 16 | guest.pop() 17 | print(guest[-1]+",sorry,i cant invited you today") 18 | guest.pop() 19 | print(guest[-1]+",sorry,i cant invited you today") 20 | guest.pop() 21 | print(guest[-1]+",sorry,i cant invited you today") 22 | guest.pop() 23 | 24 | print(guest[0]+", "+ guest[1] + " you all still in list") 25 | del guest[0] 26 | del guest[0] 27 | print(guest) -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-8.py: -------------------------------------------------------------------------------- 1 | city = ["Suzhou","Chengdu","Bejing","Fujian","Shenzhen"] 2 | print(city) 3 | print(sorted(city)) 4 | print(city) 5 | 6 | sorted_city = sorted(city) 7 | sorted_city.reverse() 8 | print(sorted_city) 9 | 10 | print(city) 11 | city.reverse() 12 | print(city) 13 | city.reverse() 14 | print(city) 15 | city.sort() 16 | print(city) 17 | 18 | city.sort(reverse=True) 19 | print(city) 20 | -------------------------------------------------------------------------------- /Chapter_03/Exercises/3-9.py: -------------------------------------------------------------------------------- 1 | guest = ['Mom','Dad','Dude'] 2 | guest_lenght = len(guest) 3 | print("There has "+ str(guest_lenght) + " people go to my lunch.") -------------------------------------------------------------------------------- /Chapter_03/bicycles.py: -------------------------------------------------------------------------------- 1 | bicycles = ['trek','cannondale','redline','specialized'] 2 | print(bicycles) 3 | print(bicycles[0]) 4 | print(bicycles[0].title()) 5 | print(bicycles[3]) 6 | print(bicycles[-1]) 7 | 8 | print("My first bycycle is " + bicycles[0].title() + ".") -------------------------------------------------------------------------------- /Chapter_03/cars.py: -------------------------------------------------------------------------------- 1 | cars = ['bnw','audi','toyota','subaru'] 2 | 3 | # Sort 4 | cars.sort() 5 | print(cars) 6 | 7 | # Reverse in sort 8 | cars = ['bnw','audi','toyota','subaru'] 9 | cars.sort(reverse=True) 10 | print(cars) 11 | 12 | # Sorted 13 | cars = ['bnw','audi','toyota','subaru'] 14 | print("Here is the original list") 15 | print(cars) 16 | print("Here is the sorted list") 17 | print(sorted(cars)) 18 | print("Here is the original list again") 19 | print(cars) 20 | 21 | # Reverse 22 | cars = ['bnw','audi','toyota','subaru'] 23 | print(cars) 24 | cars.reverse() 25 | print(cars) 26 | 27 | # Lenght 28 | print(len(cars)) -------------------------------------------------------------------------------- /Chapter_03/motorcycles.py: -------------------------------------------------------------------------------- 1 | motorcycles = ['honda','yamaha','suzuki'] 2 | print(motorcycles) 3 | # Update element 4 | motorcycles[0] = 'ducati' 5 | print(motorcycles) 6 | # Append element 7 | motorcycles.append('ducati') 8 | print(motorcycles) 9 | 10 | # Using Append() create list 11 | motorcycles = [] 12 | motorcycles.append('honda') 13 | motorcycles.append('yamaha') 14 | motorcycles.append('suzuki') 15 | 16 | print(motorcycles) 17 | 18 | # Insert element 19 | motorcycles.insert(0,'ducati') 20 | print(motorcycles) 21 | 22 | # Del element 23 | motorcycles = ['honda','yamaha','suzuki'] 24 | del motorcycles[0] 25 | print(motorcycles) 26 | 27 | # Pop element 28 | motorcycles = ['honda','yamaha','suzuki'] 29 | last_owned = motorcycles.pop() 30 | print(motorcycles) 31 | print(last_owned) 32 | first_owned = motorcycles.pop(0) 33 | print(first_owned) 34 | print(motorcycles) 35 | 36 | # Remove element 37 | motorcycles = ['honda','yamaha','suzuki','ducati'] 38 | print(motorcycles) 39 | motorcycles.remove('ducati') 40 | print(motorcycles) 41 | 42 | motorcycles = ['honda','yamaha','suzuki','ducati'] 43 | too_expensive = 'ducati' 44 | motorcycles.remove(too_expensive) 45 | print(motorcycles) 46 | print("\nA "+ too_expensive.title()+" is too expensive for me") 47 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-1.py: -------------------------------------------------------------------------------- 1 | pizzas = ['beef pizza','chicken pizza','lamb pizza'] 2 | for pizza in pizzas: 3 | print("I love "+ pizza) 4 | print("I really love pizza!") -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-10.py: -------------------------------------------------------------------------------- 1 | my_foods = ['pizza','falafel','carrot','cake','cannoli','ice cream','apple'] 2 | print('The first three items in the list are') 3 | print(my_foods[:3]) 4 | print('The iteams from the middle of the list are') 5 | start_index = len(my_foods) // 2 - 1 6 | end_index = start_index + 3 7 | print(my_foods[start_index:end_index]) 8 | print('Thelast threeitems in thelistare:') 9 | print(my_foods[-3:]) 10 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-11.py: -------------------------------------------------------------------------------- 1 | pizzas = ['beef pizza','chicken pizza','lamb pizza'] 2 | friend_pizza = pizzas[:] 3 | pizzas.append("fish pizza") 4 | friend_pizza.append("rabbit pizza") 5 | 6 | print("My favorite pizza are:") 7 | for pizza in pizzas: 8 | print(pizza) 9 | print("Friend's favorite pizza are:") 10 | for pizza in friend_pizza: 11 | print(pizza) 12 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-12.py: -------------------------------------------------------------------------------- 1 | my_foods = ['pizza','falafel','carrot','cake'] 2 | friend_foods = my_foods[:] 3 | 4 | my_foods.append('cannoli') 5 | friend_foods.append('ice cream') 6 | 7 | print("My favorite foods are:") 8 | for pizza in my_foods: 9 | print(pizza) 10 | print("My friend's favorite foods are:") 11 | for pizza in friend_foods: 12 | print(pizza) 13 | 14 | 15 | my_foods = ['pizza','falafel','carrot','cake'] 16 | friend_foods = my_foods 17 | my_foods.append('cannoli') 18 | friend_foods.append('ice cream') 19 | 20 | print("My favorite foods are:") 21 | for pizza in my_foods: 22 | print(pizza) 23 | print("My friend's favorite foods are:") 24 | for pizza in friend_foods: 25 | print(pizza) -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-13.py: -------------------------------------------------------------------------------- 1 | foods = ('apple','beef','lamb','fish','hotdog') 2 | for food in foods: 3 | print(food) 4 | 5 | # foods[0] = 'cheese' 6 | 7 | foods = ('noodles','rice','lamb','fish','hotdog') 8 | for food in foods: 9 | print(food) 10 | 11 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-2.py: -------------------------------------------------------------------------------- 1 | animals = ["dog","cat","pig"] 2 | 3 | for animal in animals: 4 | print(animal) 5 | 6 | for animal in animals: 7 | print(f"{animal} would make a great pet.") 8 | 9 | print("Any of these animals would make a great pet!") -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-3.py: -------------------------------------------------------------------------------- 1 | for value in range(1,21): 2 | print(value) -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-4.py: -------------------------------------------------------------------------------- 1 | numbers = list(range(1,1000001)) 2 | print(numbers) -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-5.py: -------------------------------------------------------------------------------- 1 | numbers = list(range(1,1000001)) 2 | print(min(numbers)) 3 | print(max(numbers)) 4 | print(sum(numbers)) 5 | 6 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-6.py: -------------------------------------------------------------------------------- 1 | odd_numbers = list(range(1,21,2)) 2 | for value in odd_numbers: 3 | print(value) -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-7.py: -------------------------------------------------------------------------------- 1 | numbers = range(3,31,3) 2 | for value in numbers: 3 | print(value) 4 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-8.py: -------------------------------------------------------------------------------- 1 | number_list = [] 2 | 3 | for value in range(1,11): 4 | number_list.append(value**3) 5 | print(value**3) 6 | print(number_list) 7 | 8 | -------------------------------------------------------------------------------- /Chapter_04/Exercises/4-9.py: -------------------------------------------------------------------------------- 1 | number_list = list(value**3 for value in range(1,11)) 2 | print(number_list) 3 | -------------------------------------------------------------------------------- /Chapter_04/dimensions.py: -------------------------------------------------------------------------------- 1 | dimensions = (200,50) 2 | print(dimensions[0]) 3 | print(dimensions[1]) 4 | 5 | # dimensions[0] = 250 # Tuple object does not support item assignment 6 | 7 | for dimension in dimensions: 8 | print(dimension) 9 | 10 | dimensions = (400,100) 11 | print("Modified dimensions") 12 | for dimension in dimensions: 13 | print(dimension) -------------------------------------------------------------------------------- /Chapter_04/even_numbers.py: -------------------------------------------------------------------------------- 1 | even_number = list(range(2,11,2)) 2 | print(even_number) -------------------------------------------------------------------------------- /Chapter_04/foods.py: -------------------------------------------------------------------------------- 1 | my_foods = ['pizza','falafel','carrot','cake'] 2 | friend_foods = my_foods[:] 3 | 4 | my_foods.append('cannoli') 5 | friend_foods.append('ice cream') 6 | 7 | print("My favorite foods are:") 8 | print(my_foods) 9 | 10 | print("My friend's favorite foods are:") 11 | print(friend_foods) 12 | 13 | 14 | my_foods = ['pizza','falafel','carrot','cake'] 15 | friend_foods = my_foods 16 | my_foods.append('cannoli') 17 | friend_foods.append('ice cream') 18 | 19 | print("My favorite foods are:") 20 | print(my_foods) 21 | 22 | print("My friend's favorite foods are:") 23 | print(friend_foods) -------------------------------------------------------------------------------- /Chapter_04/magicians.py: -------------------------------------------------------------------------------- 1 | magicians = ['alice','david','carolina'] 2 | for magician in magicians: 3 | print(magician.title() + ", that was a great trick") 4 | print("I cant't wait to see you next trick, "+magician.title() + ".") 5 | 6 | print('Thank you, everyone. That was a great magic show!') 7 | -------------------------------------------------------------------------------- /Chapter_04/numbers.py: -------------------------------------------------------------------------------- 1 | for value in range(1,5): 2 | print(value) 3 | 4 | for value in range(1,6): 5 | print(value) 6 | 7 | numbers = list(range(1,6)) 8 | print(numbers) -------------------------------------------------------------------------------- /Chapter_04/players.py: -------------------------------------------------------------------------------- 1 | players = ['charles','martina','michael','florence','eli'] 2 | 3 | print(players[0:3]) 4 | print(players[1:4]) 5 | print(players[:4]) 6 | print(players[2:]) 7 | print(players[-3:]) 8 | 9 | print("Here are the first three players on my team") 10 | for player in players[:3]: 11 | print(player) 12 | -------------------------------------------------------------------------------- /Chapter_04/squares.py: -------------------------------------------------------------------------------- 1 | squares = [] 2 | for value in range(1,11): 3 | square = value**2 4 | squares.append(square) 5 | 6 | print(squares) 7 | 8 | # for value in range(1,11): 9 | # squares.append(value ** 2) 10 | 11 | # print(squares) 12 | 13 | digits = [1,2,3,4,5,6,7,8,9,0] 14 | print(min(digits)) 15 | print(max(digits)) 16 | print(sum(digits)) 17 | 18 | squares = [value**2 for value in range(1,11)] 19 | print(squares) -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-1.py: -------------------------------------------------------------------------------- 1 | car = 'subaru' 2 | print(car == 'subaru') # True 3 | print(car != 'subaru') # False 4 | print(car == 'Subaru') # False 5 | print(car != 'Subaru') # True 6 | print(car == 'Audi') # False 7 | print(car != 'Audi') # True 8 | print(car == 'Toyota')# Flase 9 | print(car == 'A6')# Flase 10 | print(car != 'Toyota')# True 11 | print(car != 'A6')# True 12 | 13 | 14 | -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-10.py: -------------------------------------------------------------------------------- 1 | current_users = ['asheone18','kawaiiash','newplayer','forever18','gggonext'] 2 | new_users = ['asheone18','newbro','forever18','123456','okgg'] 3 | 4 | for new_user in new_users: 5 | if new_user in current_users: 6 | print(f"username {new_user} already use.") 7 | else: 8 | print(f"username {new_user} is fine!") -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-11.py: -------------------------------------------------------------------------------- 1 | numbers = range(1,10) 2 | 3 | for number in numbers: 4 | if number == 1: 5 | print(str(number) + "st") 6 | elif number == 2: 7 | print(str(number) + "nd") 8 | elif number == 3: 9 | print(str(number) + "rd") 10 | else: 11 | print(str(number) + "th") -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-2.py: -------------------------------------------------------------------------------- 1 | car = 'toyota' 2 | print(car.title() == 'Toyota')# True 3 | print(car.lower() == 'toyota')# True 4 | 5 | number1 = 10 6 | number2 = 20 7 | 8 | print(number1 < number2)# True 9 | print(number1 <= number2)# True 10 | print(number1 == number2)# False 11 | print(number1 >= number2)# False 12 | print(number1 > number2)# False 13 | 14 | print(number1 == 10 and number2 == 20)#True 15 | print(number1 == 10 or number2 == 21)#True 16 | 17 | foods = ['pizza','apple','beef'] 18 | print('lamb' in foods)# False 19 | print('lamb' not in foods)# True -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-3.py: -------------------------------------------------------------------------------- 1 | alien_color = 'green' 2 | if alien_color == 'green': 3 | print("you get 5 points") 4 | if alien_color == 'red': 5 | print("you get 5 points") 6 | -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-4.py: -------------------------------------------------------------------------------- 1 | alien_color = 'red' 2 | 3 | if alien_color == 'green': 4 | print('You get 5 points') 5 | else: 6 | print('You get 10 points') 7 | -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-5.py: -------------------------------------------------------------------------------- 1 | alien_color = 'green' 2 | 3 | if alien_color == 'green': 4 | print('You get 5 points!') 5 | elif alien_color == 'yellow': 6 | print('You get 10 points!') 7 | elif alien_color == 'red': 8 | print('You get 15 points!') 9 | else: 10 | print('Color error') 11 | 12 | -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-6.py: -------------------------------------------------------------------------------- 1 | age = 20 2 | 3 | if age < 0: 4 | print("Not a human XD.") 5 | elif age >= 0 and age < 2: 6 | print("He is a baby.") 7 | elif age < 4: 8 | print("He is walk unsteadily.") 9 | elif age < 13: 10 | print("He is a children.") 11 | elif age < 20: 12 | print("He is a teenager.") 13 | elif age < 65: 14 | print("He is an adult.") 15 | else: 16 | print("He is a oldder.") -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-7.py: -------------------------------------------------------------------------------- 1 | favorate_fruits = ['Apple','Watermelon','Orange'] 2 | 3 | if 'Bananas' in favorate_fruits: 4 | print('You really like bananas!') 5 | 6 | if 'Cucumber' in favorate_fruits: 7 | print('You really like cucumber!') 8 | 9 | if 'Apple' in favorate_fruits: 10 | print('You really like apple!') 11 | 12 | if 'Watermelon' in favorate_fruits: 13 | print('You really like watermelon!') 14 | 15 | if 'Orange' in favorate_fruits: 16 | print('You really like orange!') -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-8.py: -------------------------------------------------------------------------------- 1 | usernames = ['admin','jane','jack','leroy','ash'] 2 | 3 | for username in usernames: 4 | if username == 'admin': 5 | print(f"Hello {username}! Would you like to see a status report?") 6 | else: 7 | print(f"Hello {username}! thank you for logging in again.") 8 | -------------------------------------------------------------------------------- /Chapter_05/Exercises/5-9.py: -------------------------------------------------------------------------------- 1 | usernames = [] 2 | 3 | if usernames: 4 | print("User list is not empty.") 5 | else: 6 | print("We need to find some user.") -------------------------------------------------------------------------------- /Chapter_05/amusement_park.py: -------------------------------------------------------------------------------- 1 | age = 12 2 | 3 | if age < 4: 4 | price = 0 5 | elif age < 18: 6 | price = 5 7 | else: 8 | price = 10 9 | 10 | print(f"Your admission cost is ${price}.") 11 | 12 | age = 17 13 | if age < 4: 14 | price = 0 15 | elif age < 18: 16 | price = 5 17 | elif age < 65: 18 | price = 10 19 | else: 20 | price = 5 21 | 22 | print(f"Your admission cost is ${price}.") -------------------------------------------------------------------------------- /Chapter_05/banned_users.py: -------------------------------------------------------------------------------- 1 | banned_user = ['andrew','carolina','david'] 2 | user = 'marie' 3 | 4 | if user not in banned_user: 5 | print(user.title() + ", you can post a response if you wish.") 6 | -------------------------------------------------------------------------------- /Chapter_05/cars.py: -------------------------------------------------------------------------------- 1 | cars = ['audi','bnw','subaru','toyota'] 2 | 3 | for car in cars: 4 | if car == 'bnw': 5 | print(car.upper()) 6 | else: 7 | print(car.title()) 8 | 9 | car = 'Audi' 10 | print(car.lower() == 'audi') -------------------------------------------------------------------------------- /Chapter_05/magic_number.py: -------------------------------------------------------------------------------- 1 | answer = 17 2 | 3 | if answer != 42: 4 | print("That is not the correct answer. Please try again!") 5 | 6 | -------------------------------------------------------------------------------- /Chapter_05/toppings.py: -------------------------------------------------------------------------------- 1 | requested_topping = 'mushrooms' 2 | 3 | if requested_topping != 'anchovies': 4 | print("Hold the anchovies!") 5 | 6 | requested_toppings = ['mushrooms','onions','pineapple'] 7 | print('mushrooms' in requested_toppings) 8 | print('pepperoni' in requested_toppings) 9 | 10 | requested_toppings = ['mushrooms','extra cheese'] 11 | if 'mushrooms' in requested_toppings: 12 | print("Adding mushrooms") 13 | if 'pepperoni' in requested_toppings: 14 | print("Adding pepperoni") 15 | if 'extra cheese' in requested_toppings: 16 | print("Adding extra cheese") 17 | 18 | print("Finished making your pizza!") 19 | 20 | requested_toppings = ['mushrooms','green peppers','extra cheese'] 21 | for requested_topping in requested_toppings: 22 | print("Adding " + requested_topping + ".") 23 | print("Finished making your pizza!") 24 | 25 | for requested_topping in requested_toppings: 26 | if requested_topping == 'green peppers': 27 | print("Sorry, we are out of green peppers right now.") 28 | else: 29 | print("Adding " + requested_topping + ".") 30 | print("Finished making pizza!") 31 | 32 | requested_toppings = [] 33 | if requested_toppings: 34 | for requested_topping in requested_toppings: 35 | print("Adding " + requested_topping + ".") 36 | print("Finished making your pizza!") 37 | else: 38 | print("Are you sure want a plain pizza?") 39 | 40 | available_toppings = ['mushrooms','olives','green peppers', 41 | 'pepperoni','pineapple','extra cheese'] 42 | 43 | requested_toppings = ['mushrooms','french fries','extra cheese'] 44 | 45 | for requested_topping in requested_toppings: 46 | if requested_topping in available_toppings: 47 | print("Adding " + requested_topping + ".") 48 | else: 49 | print("Sorry, We dont have " + requested_topping + ".") 50 | print("Finished make your pizza!") -------------------------------------------------------------------------------- /Chapter_05/voting.py: -------------------------------------------------------------------------------- 1 | age = 17 2 | if age >= 18: 3 | print("You are old enough to vote!") 4 | print("Have you registered to vote yet?") 5 | else: 6 | print("Sorry, you are too young to vote.") 7 | print("Please register to vote as soon as you turn 18!") 8 | -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-1.py: -------------------------------------------------------------------------------- 1 | best_friend = {'first_name':'Jiang', 2 | 'last_name':'ZhuangShui', 3 | 'age':21, 4 | 'city':'NewYork'} 5 | 6 | print("My best friend is "+ 7 | best_friend['last_name'] + " " 8 | + best_friend['first_name'] + "." + 9 | "He is " + str(best_friend['age']) + 10 | ".live in " + best_friend['city'] + ".") 11 | -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-10.py: -------------------------------------------------------------------------------- 1 | cities = { 2 | 'cheng du':{ 3 | 'country':'china', 4 | 'population':10000000, 5 | 'fact':'Chengdu is the capital city of the Chinese province of Sichuan.' 6 | }, 7 | 'new york':{ 8 | 'country':'united state', 9 | 'population':66856889, 10 | 'fact':'New York, often called New York City or NYC, is the most populous city in the United States.' 11 | } 12 | } 13 | 14 | for city,details in cities.items(): 15 | print(city.title()) 16 | country = details['country'] 17 | population = details['population'] 18 | fact = details['fact'] 19 | 20 | print(f"{city.title()} is a part of {country} which has a population of {population} people. The information about this city is: {fact}\n") 21 | -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-2.py: -------------------------------------------------------------------------------- 1 | favorite_number = { 2 | 'ash':18, 3 | 'zhou':20, 4 | 'shui':22, 5 | 'jack':24, 6 | 'los':26 7 | } 8 | 9 | for name,number in favorite_number.items(): 10 | print(name.title() + "favorite number is:" + str(number) + ".") 11 | -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-3.py: -------------------------------------------------------------------------------- 1 | dict = { 2 | 'C':'Top 1 programming language', 3 | 'Python':'Top 2 programming language', 4 | 'React': 'Javascript library', 5 | 'Django': 'Web framework' 6 | } 7 | 8 | for word,meaning in dict.items(): 9 | print("Word: " + word + " Meaning: " + meaning) 10 | -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-4.py: -------------------------------------------------------------------------------- 1 | dict = { 2 | 'C':'Top 1 programming language', 3 | 'Python':'Top 2 programming language', 4 | 'React': 'Javascript library', 5 | 'Django': 'Web framework', 6 | 'Print()': 'A function', 7 | 'Set()': 'A function', 8 | 'For': 'Forloop', 9 | 'While': 'Whileloop' 10 | } 11 | 12 | for word,meaning in dict.items(): 13 | print("Word: " + word.title() + ", Meaning: " + meaning.title()) -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-5.py: -------------------------------------------------------------------------------- 1 | rivers = {} 2 | rivers['nile'] = 'egypt' 3 | rivers['yellow'] = 'china' 4 | rivers['amazon'] = 'brazil' 5 | 6 | for river,country in rivers.items(): 7 | print(f"The {river} runs through {country}.") 8 | print(f"The river full name is {river} river.") 9 | print(f"The river of country is {country}.\n") -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-6.py: -------------------------------------------------------------------------------- 1 | participants_with_languages = { 2 | 'jen': 'python', 3 | 'sarah': 'c', 4 | 'edward': 'ruby', 5 | 'phil': 'python', 6 | } 7 | 8 | invited_people_list = ['jen', 'ash', 'sarah'] 9 | 10 | for person in invited_people_list: 11 | if person in participants_with_languages: 12 | print(person.title() + ", thank you for taking the poll!") 13 | else: 14 | print(person.title() + ", please take the poll!") 15 | -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-7.py: -------------------------------------------------------------------------------- 1 | friend1 = {'first_name':'ZhuangShui', 2 | 'last_name':'Jiang', 3 | 'age':21, 4 | 'city':'NewYork'} 5 | friend2 = {'first_name':'Yin', 6 | 'last_name':'Lin', 7 | 'age':22, 8 | 'city':'LOS'} 9 | friend3 = {'first_name':'Er', 10 | 'last_name':'Jiu', 11 | 'age':27, 12 | 'city':'Chengdu'} 13 | people = [friend1,friend2,friend3] 14 | for friend in people: 15 | print("Friend's full name is: " + friend['last_name'] + friend['first_name'] + 16 | "He is " + str(friend['age']) + " years old. live in " + friend['city']) -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-8.py: -------------------------------------------------------------------------------- 1 | dog = { 2 | 'type':'dog', 3 | 'onwer':'ash', 4 | } 5 | 6 | bird = { 7 | 'type':'bird', 8 | 'onwer':'ash', 9 | } 10 | 11 | cat = { 12 | 'type':'cat', 13 | 'onwer':'ash', 14 | } 15 | 16 | pets = [dog,bird,cat] 17 | 18 | for pet in pets: 19 | print("The type of pet is " + pet['type'].title() + " Onwer is: " + pet['onwer'].title() + ".") -------------------------------------------------------------------------------- /Chapter_06/Exercises/6-9.py: -------------------------------------------------------------------------------- 1 | favorite_place = { 2 | 'Shui':['Chengdu','Xian','Shanghai'], 3 | 'Ash':['US','NY','LA'], 4 | 'Guadra':['Suzhou','Fujian','YelloRiver'] 5 | } 6 | 7 | for person,places in favorite_place.items(): 8 | print(person.title() + "'s favorite place is:") 9 | for place in places: 10 | print(place) 11 | print() 12 | -------------------------------------------------------------------------------- /Chapter_06/alien.py: -------------------------------------------------------------------------------- 1 | alien_0 = {'color':'green','points':5} 2 | 3 | print(alien_0['color']) 4 | print(alien_0['points']) 5 | 6 | new_points = alien_0['points'] 7 | print("You just earned " + str(new_points) + " points!") 8 | 9 | alien_0 = {'color':'green','points':5} 10 | print(alien_0) 11 | 12 | alien_0['x_position'] = 0 13 | alien_0['y_position'] = 25 14 | print(alien_0) 15 | 16 | alien_0 = {} 17 | alien_0['color'] = 'green' 18 | alien_0['points'] = 5 19 | 20 | print(alien_0) 21 | 22 | alien_0 = {'color':'green'} 23 | print("The alien is " + alien_0['color'] + ".") 24 | alien_0['color'] = 'yellow' 25 | print("The alien is now " + alien_0['color'] + ".") 26 | 27 | alien_0 = {'x_position':0,'y_position':25,'speed':'fast'} 28 | print("Original x-position: " + str(alien_0['x_position'])) 29 | 30 | # Let alien move to right 31 | if alien_0['speed'] == 'slow': 32 | x_increment = 1 33 | elif alien_0['speed'] == 'medium': 34 | x_increment = 2 35 | else: 36 | # The speed of alien must be fast 37 | x_increment = 3 38 | 39 | alien_0['x_position'] = alien_0['x_position'] + x_increment 40 | 41 | print("New x-position: " + str(alien_0['x_position'])) 42 | 43 | alien_0 = {'color':'green','points':5} 44 | print(alien_0) 45 | 46 | del alien_0['color'] 47 | print(alien_0) 48 | 49 | -------------------------------------------------------------------------------- /Chapter_06/aliens.py: -------------------------------------------------------------------------------- 1 | aline_0 = {'color':'green','points':5} 2 | aline_1 = {'color':'yellow','points':10} 3 | aline_2 = {'color':'red','points':15} 4 | 5 | aliens = [aline_0,aline_1,aline_2] 6 | 7 | for alien in aliens: 8 | print(alien) 9 | 10 | aliens = [] 11 | 12 | for alien_number in range(0,30): 13 | new_alien = {'color':'green', 14 | 'points':5, 15 | 'speed':'slow'} 16 | aliens.append(new_alien) 17 | 18 | for alien in aliens[:3]: 19 | if alien['color'] == 'green': 20 | alien['color'] = 'yellow' 21 | alien['speed'] = 'medium' 22 | alien['points'] = 10 23 | 24 | for alien in aliens[:5]: 25 | print(alien) 26 | 27 | print("......") 28 | 29 | print("Total number of aliens: " + str(len(aliens))) 30 | -------------------------------------------------------------------------------- /Chapter_06/favorite_languages.py: -------------------------------------------------------------------------------- 1 | favorite_languages = { 2 | 'jen':'python', 3 | 'sarah':'c', 4 | 'edward':'ruby', 5 | 'phil':'python', 6 | } 7 | 8 | print("Sarah's favorite language is " + 9 | favorite_languages['sarah'] + 10 | ".") 11 | 12 | for name,language in favorite_languages.items(): 13 | print("\nName: " + name + ", Language: " + language) 14 | 15 | for name in favorite_languages.keys(): 16 | print("\nName: " + name.title()) 17 | 18 | friends = ['phil','sarah'] 19 | for name in favorite_languages.keys(): 20 | print(name + ". ") 21 | if name in friends: 22 | print(" Hi " + name.title() + 23 | ", I see your favorite language is " + 24 | favorite_languages[name].title() + ".") 25 | 26 | if 'erin' not in favorite_languages.keys(): 27 | print("Erin, please take our poll!") 28 | 29 | 30 | for name in sorted(favorite_languages.keys()): 31 | print(name.title() + ", Thank you for talking the poll!") 32 | 33 | print("The following languages have been mentioned:") 34 | for language in favorite_languages.values(): 35 | print(language.title()) 36 | 37 | print("The following languages have been mentioned:") 38 | for language in set(favorite_languages.values()): 39 | print(language.title()) 40 | 41 | favorite_languages = { 42 | 'jen': ['python','ruby'], 43 | 'sarah':['c'], 44 | 'edward':['ruby','go'], 45 | 'phil':['python','haskell'] 46 | } 47 | 48 | for name,languages in favorite_languages.items(): 49 | print(name.title() + "'s favorite languages are:") 50 | for language in languages: 51 | print(language.title()) -------------------------------------------------------------------------------- /Chapter_06/many_users.py: -------------------------------------------------------------------------------- 1 | users = { 2 | 'aeinstein': { 3 | 'first':'albert', 4 | 'last':'einstein', 5 | 'location':'princeton', 6 | }, 7 | 'mcurie':{ 8 | 'first':'marie', 9 | 'last':'cure', 10 | 'location':'paris', 11 | } 12 | } 13 | 14 | for username,user_info, in users.items(): 15 | print("Username: " + username) 16 | full_name = user_info['last'] + " " + user_info['first'] 17 | location = user_info['location'] 18 | 19 | print("Fullname: " + full_name.title()) 20 | print("Location: " + location.title()) 21 | -------------------------------------------------------------------------------- /Chapter_06/pizza.py: -------------------------------------------------------------------------------- 1 | pizza = { 2 | 'crust':'thick', 3 | 'toppings': ['mushrooms','extra cheese'] 4 | } 5 | 6 | print("You ordered a " + pizza['crust'] + "-crust pizza " + 7 | "with the following toppings:") 8 | 9 | for topping in pizza['toppings']: 10 | print(topping) -------------------------------------------------------------------------------- /Chapter_06/user.py: -------------------------------------------------------------------------------- 1 | user_0 = { 2 | 'username':'efermi', 3 | 'first':'enrico', 4 | 'last':'fermi', 5 | } 6 | 7 | for key,value in user_0.items(): 8 | print("\nKey:" + key) 9 | print("Value:" + value) 10 | 11 | -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-1.py: -------------------------------------------------------------------------------- 1 | request_car = input("What kind of car do you want to lease?") 2 | print("Let me see if i can find your " + request_car + ".") 3 | -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-10.py: -------------------------------------------------------------------------------- 1 | dream_vacation_spots = {} 2 | poll_active = True 3 | while poll_active: 4 | print("If you could visit one place in the world,where would you go?") 5 | username = input("What is your username?") 6 | desired_destination = input("Where you wanna go?") 7 | dream_vacation_spots[username] = desired_destination 8 | 9 | repeat = input("You wanna quit? (yes or no)") 10 | if repeat == 'yes': 11 | break 12 | 13 | for username,desired_destination in dream_vacation_spots.items(): 14 | print(f"{username} wanna go {desired_destination}" + ".") 15 | -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-2.py: -------------------------------------------------------------------------------- 1 | person_number = int(input("What is the number of diners?")) 2 | if person_number > 8: 3 | print("There are no tables available. sorry !") 4 | else: 5 | print("There's a table, Welcome!") -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-3.py: -------------------------------------------------------------------------------- 1 | number = int(input("Please enter a number.")) 2 | if number % 10 == 0: 3 | print("It's an integer multiple of 10.") 4 | else: 5 | print("It's not an integer multiple of 10.") -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-4.py: -------------------------------------------------------------------------------- 1 | toppings = [] 2 | 3 | while True: 4 | topping = input("Please enter your desired pizza toppings (Enter 'quit' to end): ") 5 | if topping == 'quit': 6 | break 7 | else: 8 | toppings.append(topping) 9 | print(topping + " Added!") 10 | 11 | if len(toppings) > 0: 12 | print("Your toppings:") 13 | for topping in toppings: 14 | print(topping) 15 | else: 16 | print("No topping") -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-5.py: -------------------------------------------------------------------------------- 1 | while True: 2 | age = input("May I ask your age?(Enter quit to end program!)") 3 | if age.lower() == 'quit': 4 | break 5 | 6 | if not age.isdigit(): 7 | print("Please enter a age or 'quit' to exit.") 8 | continue 9 | 10 | age = int(age) 11 | 12 | if age >= 0 and age < 3: 13 | print("The price is free.") 14 | elif age >= 3 and age <= 12: 15 | print("The price is $10.") 16 | else: 17 | print("The price is $15.") 18 | 19 | -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-6.py: -------------------------------------------------------------------------------- 1 | active = True 2 | 3 | while active: 4 | age = input("May I ask your age? (Enter 'quit' to end the program!) ") 5 | 6 | if age.lower() == 'quit': 7 | active = False 8 | break 9 | 10 | if not age.isdigit(): 11 | print("Please enter a valid age or 'quit' to exit.") 12 | continue 13 | 14 | age = int(age) 15 | 16 | if age < 3: 17 | print("The price is free.") 18 | elif age <= 12: 19 | print("The price is $10.") 20 | else: 21 | print("The price is $15.") 22 | -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-7.py: -------------------------------------------------------------------------------- 1 | x = 0 2 | while x < 2: 3 | print(x) -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-8.py: -------------------------------------------------------------------------------- 1 | sandwich_orders = ['Beef sandwich','Tuna sandwich','Lamb sandwich'] 2 | finished_sandwiches = [] 3 | while sandwich_orders: 4 | current_sandwich = sandwich_orders.pop() 5 | print(f"I made your {current_sandwich}") 6 | finished_sandwiches.append(current_sandwich) 7 | 8 | print("All sandwich are done........") 9 | for finished_sandwich in finished_sandwiches: 10 | print(finished_sandwich) -------------------------------------------------------------------------------- /Chapter_07/Exercises/7-9.py: -------------------------------------------------------------------------------- 1 | sandwich_orders = ['Beef sandwich','Pastrami sandwich','Tuna sandwich' 2 | ,'Pastrami sandwich','Lamb sandwich','Pastrami sandwich'] 3 | finished_orders = [] 4 | print("All Pastrami sandwich are out of stock.......") 5 | 6 | while 'Pastrami sandwich' in sandwich_orders: 7 | sandwich_orders.remove('Pastrami sandwich') 8 | 9 | while sandwich_orders: 10 | current_sandwich = sandwich_orders.pop() 11 | finished_orders.append(current_sandwich) 12 | 13 | print("Sandwich_orders list:", sandwich_orders) 14 | print("Finished_orders list:", finished_orders) 15 | -------------------------------------------------------------------------------- /Chapter_07/age.py: -------------------------------------------------------------------------------- 1 | age = input("How old are you?") 2 | print(age) 3 | 4 | if int(age) > 18: 5 | print("age > 18 is True") -------------------------------------------------------------------------------- /Chapter_07/cities.py: -------------------------------------------------------------------------------- 1 | prompt="\nPlease enter the name of a city you have visited:" 2 | prompt += "\n(Enter quit' when you are finished.)" 3 | 4 | while True: 5 | city = input(prompt) 6 | if city == 'quit': 7 | break 8 | else: 9 | print("I'd love to go to " + city.title() + ".") -------------------------------------------------------------------------------- /Chapter_07/confirmed_users.py: -------------------------------------------------------------------------------- 1 | unconfirmed_users = ['alice','brian','candace'] 2 | confirmed_users = [] 3 | 4 | while unconfirmed_users: 5 | current_user = unconfirmed_users.pop() 6 | print("Verifying user: " + current_user.title()) 7 | confirmed_users.append(current_user) 8 | 9 | print("\nThe following users have been confirmed.") 10 | for confirmed_user in confirmed_users: 11 | print(confirmed_user.title()) -------------------------------------------------------------------------------- /Chapter_07/counting.py: -------------------------------------------------------------------------------- 1 | # current_number = 1 2 | # while current_number <= 5: 3 | # print(current_number) 4 | # current_number += 1 5 | 6 | # current_number = 0 7 | # while current_number < 10: 8 | # current_number += 1 9 | 10 | # if current_number % 2 == 0: 11 | # continue 12 | 13 | # print(current_number) 14 | 15 | x = 1 16 | while x < 5: 17 | print(x) 18 | x += 1 19 | 20 | -------------------------------------------------------------------------------- /Chapter_07/even_or_odd.py: -------------------------------------------------------------------------------- 1 | number = int(input("Enter a number, and I'll tell you if it's even or odd.")) 2 | 3 | if number % 2 == 0: 4 | print("\nThe number " + str(number) + " is even.") 5 | else: 6 | print("\nThe number " + str(number) + " is odd.") -------------------------------------------------------------------------------- /Chapter_07/greeter.py: -------------------------------------------------------------------------------- 1 | # name = input("Please enter your name:") 2 | # print("Hello, " + name + "!") 3 | 4 | prompt = "If you tell us who you are, we can personalize the messages you see." 5 | prompt += "\nWhat is your first name?" 6 | 7 | name = input(prompt) 8 | print("\nHello, " + name + "!") -------------------------------------------------------------------------------- /Chapter_07/mountain_poll.py: -------------------------------------------------------------------------------- 1 | responses = {} 2 | 3 | polling_active = True 4 | 5 | while polling_active: 6 | name = input("\nWhat is your name?") 7 | response = input("Which mountain would you like to climb sameday?") 8 | 9 | responses[name] = response 10 | 11 | repeat = input("Would you like to let another person respond? (yes / no)") 12 | if repeat == 'no': 13 | polling_active = False 14 | 15 | print("\n---Poll Results ---") 16 | for name,response in responses.items(): 17 | print(name + " would like to climb " + response) 18 | 19 | print(responses) -------------------------------------------------------------------------------- /Chapter_07/parrot.py: -------------------------------------------------------------------------------- 1 | # message = input("Tell me something, and I will repeat it back to you: ") 2 | # print(message) 3 | 4 | prompt = "\nTell me something, and I will repeat it back to you!" 5 | prompt += "\nEnter quit to end the program." 6 | 7 | active = True 8 | while active: 9 | message = input(prompt) 10 | if message == 'quit': 11 | active = False 12 | else: 13 | print(message) 14 | -------------------------------------------------------------------------------- /Chapter_07/pets.py: -------------------------------------------------------------------------------- 1 | pets=['dog','cat','dog','goldfish','cat','rabbit','cat'] 2 | 3 | while 'cat' in pets: 4 | pets.remove('cat') 5 | 6 | print(pets) -------------------------------------------------------------------------------- /Chapter_07/rollercoaster.py: -------------------------------------------------------------------------------- 1 | height = input("How tall are you, in inches?") 2 | height = int(height) 3 | 4 | if height >= 36: 5 | print("\nYou're tall enough to ride!") 6 | else: 7 | print("\nYou'll be able to ride when you're a little older.") 8 | 9 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-1.py: -------------------------------------------------------------------------------- 1 | def display_message(): 2 | print("I am learning function in Chapter 8.") 3 | 4 | display_message() -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-10.py: -------------------------------------------------------------------------------- 1 | def make_great(magicians): 2 | return ['The great ' + magician for magician in magicians] 3 | 4 | def show_magicians(magicians): 5 | for magician in magicians: 6 | print(magician) 7 | 8 | magicians = ['Houdini', 'Dynamo', 'Penn Jillette'] 9 | magicians = make_great(magicians) 10 | show_magicians(magicians) 11 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-11.py: -------------------------------------------------------------------------------- 1 | def make_great(magicians): 2 | return ["The great " + magician for magician in magicians[:]] 3 | 4 | def show_magicians(magicians): 5 | for magician in magicians: 6 | print(magician) 7 | 8 | magicians = ['Houdini', 'Dynamo', 'Penn Jillette'] 9 | new_magicians_list = make_great(magicians) 10 | show_magicians(magicians) 11 | show_magicians(new_magicians_list) -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-12.py: -------------------------------------------------------------------------------- 1 | def add_toppings(*toppings): 2 | print("Your sandwich include following toppings:") 3 | for topping in toppings: 4 | print("- " + topping) 5 | 6 | add_toppings('Mushrooms','Extra cheese','Beef') 7 | add_toppings('Hotdog','Extra cheese','Lamb') 8 | add_toppings('Coin','Extra cheese','Fish') -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-13.py: -------------------------------------------------------------------------------- 1 | def build_profile(first,last,**user_info): 2 | user_profile = {} 3 | user_profile['first'] = first 4 | user_profile['last'] = last 5 | for key,value in user_info.items(): 6 | user_profile[key] = value 7 | return user_profile 8 | 9 | my_profile = build_profile('Ash','Kawaii',hobby='Coding',gender='male',age=21) 10 | print(my_profile) 11 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-14.py: -------------------------------------------------------------------------------- 1 | def save_car_info(manufacturer,model_number,**parameter): 2 | car_info = {} 3 | car_info['manufacturer'] = manufacturer 4 | car_info['model_number'] = model_number 5 | for key,value in parameter.items(): 6 | car_info[key] = value 7 | return car_info 8 | 9 | print() -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-15.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append('../') # Add the parent directory to the path 3 | 4 | from printing_models import print_models 5 | from printing_models import show_models 6 | 7 | unprinted_designs = ['iphone case','robot pendant','dodecahedron'] 8 | completed_models = [] 9 | 10 | print_models(unprinted_designs,completed_models) 11 | show_models(completed_models) -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-16.py: -------------------------------------------------------------------------------- 1 | import single_function 2 | import single_function as sf 3 | from single_function import show_sum 4 | from single_function import show_sum as ss 5 | from single_function import * 6 | 7 | single_function.show_sum(1,2) 8 | sf.show_sum(1,2) 9 | show_sum(1,2) 10 | ss(1,2) 11 | single_function.show_sum(1,2) 12 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-2.py: -------------------------------------------------------------------------------- 1 | def favorite_book(book): 2 | print(f"One of my favorite book is {book.title()}.") 3 | 4 | favorite_book('c++ primer') 5 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-3.py: -------------------------------------------------------------------------------- 1 | def make_shirt(size,text): 2 | print(f"The size of T shirt is {size} and has the text {text}.") 3 | 4 | make_shirt('XL','LV') 5 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-4.py: -------------------------------------------------------------------------------- 1 | def make_shirt(size = 'XL',text = 'I love python'): 2 | print(f"The size of T shirt is {size} and has the text {text}.") 3 | 4 | make_shirt() 5 | make_shirt('X') 6 | make_shirt('S','I love Java') -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-5.py: -------------------------------------------------------------------------------- 1 | def describe_city(city,country = "United State"): 2 | print(f"{city} is in {country}.") 3 | 4 | describe_city('NewYork') 5 | describe_city('LA') 6 | describe_city('Chengdu','China') 7 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-6.py: -------------------------------------------------------------------------------- 1 | def city_country(city,country): 2 | return city.title() + ", " + country 3 | 4 | new_york = city_country('new york','united states') 5 | print(new_york) 6 | los_angeles = city_country('los angeles','united states') 7 | print(los_angeles) 8 | cheng_du = city_country('cheng du','china') 9 | print(cheng_du) 10 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-7.py: -------------------------------------------------------------------------------- 1 | def make_album(singer_name,album_name,song_number=""): 2 | album_info = {'singer name'.title():singer_name.title(), 3 | 'album name'.title():album_name.title()} 4 | if song_number: 5 | album_info['song number'.title()] = song_number 6 | return album_info 7 | 8 | album_info = make_album("Jay",'Love Confession') 9 | print(album_info) 10 | album_info = make_album("Jay",'Love Confession',10) 11 | print(album_info) -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-8.py: -------------------------------------------------------------------------------- 1 | def make_album(singer_name,album_name,song_number=""): 2 | album_info = {'singer name'.title():singer_name.title(), 3 | 'album name'.title():album_name.title()} 4 | if song_number: 5 | album_info['song number'.title()] = song_number 6 | return album_info 7 | 8 | while True: 9 | message = "(Enter 'q' to end the program.)" 10 | print(message) 11 | singer_name = input("Please enter singer's name:") 12 | if singer_name == 'q': 13 | break 14 | album_name = input("Please enter album's name:") 15 | if album_name == 'q': 16 | break 17 | song_number = input("Please enter song_number(options):") 18 | if song_number == 'q': 19 | break 20 | if song_number.isdigit(): 21 | song_number = int(song_number) 22 | album_info = make_album(singer_name,album_name,song_number) 23 | print(album_info) 24 | -------------------------------------------------------------------------------- /Chapter_08/Exercises/8-9.py: -------------------------------------------------------------------------------- 1 | def show_magicians(magicians): 2 | for magician in magicians: 3 | print(magician) 4 | 5 | magicians = ['Houdini', 'Dynamo', 'Penn Jillette'] 6 | show_magicians(magicians) -------------------------------------------------------------------------------- /Chapter_08/Exercises/single_function.py: -------------------------------------------------------------------------------- 1 | def show_sum(a, b): 2 | a_str,b_str = str(a),str(b) 3 | if a_str.isdigit() and b_str.isdigit(): 4 | print(int(a_str) + int (b_str)) 5 | else: 6 | print("Error. Please provide 2 numbers.") 7 | -------------------------------------------------------------------------------- /Chapter_08/formatted_name.py: -------------------------------------------------------------------------------- 1 | def get_formatted_name(first_name,last_name,middle_name = ""): 2 | if middle_name: 3 | full_name = first_name + " " + middle_name + " " + last_name 4 | else: 5 | full_name = first_name + " " + last_name 6 | return full_name.title() 7 | 8 | musician = get_formatted_name('jimi','hendrix','lee') 9 | print(musician) 10 | musician = get_formatted_name('jimi','hendrix') 11 | print(musician) -------------------------------------------------------------------------------- /Chapter_08/greeter.py: -------------------------------------------------------------------------------- 1 | def greet_user(): 2 | print("Hello!") 3 | 4 | greet_user() 5 | 6 | def greet_user(username): 7 | print("Hello! " + username.title() + ".") 8 | 9 | greet_user('ash') 10 | 11 | 12 | def get_formatted_name(first_name,last_name): 13 | full_name = first_name + " " + last_name 14 | return full_name.title() 15 | 16 | while True: 17 | print("Please tell me your name: ") 18 | print("Enter 'q' to quit.") 19 | first_name = input("First name:") 20 | 21 | if first_name == 'q': 22 | break 23 | 24 | last_name = input("Last_name:") 25 | 26 | if last_name == 'q': 27 | break 28 | 29 | formatted_name = get_formatted_name(first_name,last_name) 30 | print("Hello, " + formatted_name + "!") -------------------------------------------------------------------------------- /Chapter_08/making_pizza.py: -------------------------------------------------------------------------------- 1 | import pizza # commonly used approaches 2 | from pizza import make_pizza # commonly used approaches 3 | from pizza import make_pizza as mp 4 | import pizza as p 5 | from pizza import * 6 | # import pizza 7 | pizza.make_pizza(16,'pepperoni') 8 | pizza.make_pizza(16,'pepperoni','mashrooms','beef') 9 | # from pizza import make_pizza 10 | make_pizza(16,'pepperoni') 11 | make_pizza(16,'pepperoni','mashrooms','beef') 12 | # from pizza import make_pizza as mp 13 | mp(16,'pepperoni') 14 | mp(16,'pepperoni','mashrooms','beef') 15 | # import pizza as p 16 | p.make_pizza(16,'pepperoni') 17 | p.make_pizza(16,'pepperoni','mashrooms','beef') 18 | # from pizza import * 19 | make_pizza(16,'pepperoni') 20 | make_pizza(16,'pepperoni','mashrooms','beef') -------------------------------------------------------------------------------- /Chapter_08/person.py: -------------------------------------------------------------------------------- 1 | def build_person(first_name,last_name,age=''): 2 | person = {'first':first_name,'last':last_name} 3 | if age: 4 | person['age'] = age 5 | return person 6 | 7 | musician = build_person('jimi','hendrix',27) 8 | print(musician) -------------------------------------------------------------------------------- /Chapter_08/pets.py: -------------------------------------------------------------------------------- 1 | def describe_pet(animal_type='dog',pet_name='willie'): 2 | print("\nI have a " + animal_type + ".") 3 | print("My " + animal_type + "'s name is " + pet_name.title() + ".") 4 | 5 | describe_pet('hamster','harry') 6 | describe_pet('dog','willie') 7 | describe_pet(animal_type='hamster',pet_name='harry') 8 | describe_pet() -------------------------------------------------------------------------------- /Chapter_08/pizza.py: -------------------------------------------------------------------------------- 1 | """ 2 | def make_pizza(*toppings): 3 | print("\nMaking a pizza with the following toppings:") 4 | for topping in toppings: 5 | print("- " + topping) 6 | 7 | make_pizza('pepperoni') 8 | make_pizza('mushrooms','green peppers','extra cheese') 9 | """ 10 | 11 | def make_pizza(size,*toppings): 12 | print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") 13 | 14 | for topping in toppings: 15 | print("- " + topping) -------------------------------------------------------------------------------- /Chapter_08/printing_models.py: -------------------------------------------------------------------------------- 1 | def print_models(unprinted_designs,completed_models): 2 | while unprinted_designs: 3 | current_design = unprinted_designs.pop() 4 | print("Printing model: " + current_design) 5 | completed_models.append(current_design) 6 | 7 | def show_models(completed_models): 8 | print("The following models have been printed:") 9 | for completed_model in completed_models: 10 | print(completed_model) 11 | 12 | unprinted_designs = ['iphone case','robot pendant','dodecahedron'] 13 | completed_models = [] 14 | 15 | print_models(unprinted_designs,completed_models) 16 | # print_models(unprinted_designs[:],completed_models) 17 | show_models(completed_models) 18 | # show_models(unprinted_designs) -------------------------------------------------------------------------------- /Chapter_08/user_profile.py: -------------------------------------------------------------------------------- 1 | def build_profile(first,last,**user_info): 2 | profile = {} 3 | profile['first_name'] = first 4 | profile['last_name'] = last 5 | for key, value in user_info.items(): 6 | profile[key] = value 7 | return profile 8 | 9 | user_profile = build_profile('albert','einstein', 10 | location='princeton', 11 | field='physics') 12 | 13 | print(user_profile) -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-1.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | def __init__(self,restaurant_name,cuisine_type): 3 | self.restaurant_name = restaurant_name 4 | self.cuisine_type = cuisine_type 5 | 6 | def describe_restaurant(self): 7 | print(self.restaurant_name + ". " + self.cuisine_type) 8 | 9 | def open_restaurant(self): 10 | print("Restaurant opening...") 11 | 12 | my_restaurant = Restaurant('Happy Pizza','Pizza') 13 | 14 | my_restaurant.describe_restaurant() 15 | my_restaurant.open_restaurant() -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-10.py: -------------------------------------------------------------------------------- 1 | from restaurant import Restaurant 2 | 3 | my_restaurant = Restaurant("Ash's restaurant") 4 | my_restaurant.open_restaurant() -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-11.py: -------------------------------------------------------------------------------- 1 | from admin import * 2 | 3 | # 在其中创建一个Admin 实例 4 | # 并对其调用方法show_privileges() ,以确认一切都能正确地运行。 5 | 6 | admin_privileges = Privileges() 7 | 8 | admin_user = Admin('Jack','Liu',admin_privileges,gender = 'age', age = 21) 9 | admin_user.privileges.show_privileges(admin_user.first_name) -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-12.py: -------------------------------------------------------------------------------- 1 | from privileges import Privileges 2 | from admin import Admin 3 | 4 | web_admin_privileges = Privileges() 5 | web_admin = Admin('Jack','Li',web_admin_privileges) 6 | web_admin.privileges.show_privileges(web_admin.first_name) -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-13-solution-2.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | data = { 4 | 'C':'Top 1 programming language', 5 | 'Python':'Top 2 programming language', 6 | 'React': 'Javascript library', 7 | 'Django': 'Web framework', 8 | 'Print()': 'A function', 9 | 'Set()': 'A function', 10 | 'For': 'Forloop', 11 | 'While': 'Whileloop' 12 | } 13 | 14 | dict = OrderedDict(data) 15 | 16 | for name,meaning in data.items(): 17 | print(name.title() + " is " + meaning.title() + ".") 18 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-13.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | dict = OrderedDict() 4 | 5 | data = { 6 | 'C':'Top 1 programming language', 7 | 'Python':'Top 2 programming language', 8 | 'React': 'Javascript library', 9 | 'Django': 'Web framework', 10 | 'Print()': 'A function', 11 | 'Set()': 'A function', 12 | 'For': 'Forloop', 13 | 'While': 'Whileloop' 14 | } 15 | 16 | for name,meaning in data.items(): 17 | dict[name] = meaning 18 | 19 | for name,meaning in data.items(): 20 | print(name.title() + " is " + meaning.title() + ".") 21 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-14.py: -------------------------------------------------------------------------------- 1 | # 请创建一个Die 类,它包含一个名为sides 的属性,该属性的默认值为6。 2 | # 编写一个名为roll_die() 的方法,它打印位于1和骰子面数之间的随机数 3 | # 创建一个6面的骰子,再掷10次。 创建一个10面的骰子和一个20面的骰子,并将它们都掷10次。 4 | from random import randint 5 | 6 | class Die(): 7 | def __init__(self,sides = 6): 8 | self.sides = sides 9 | 10 | def roll_die(self): 11 | return randint(1,self.sides) 12 | 13 | six_side_die = Die() 14 | for _ in range(10): 15 | print(six_side_die.roll_die()) 16 | 17 | ten_side_die = Die(10) 18 | for _ in range(10): 19 | print(ten_side_die.roll_die()) 20 | 21 | twenty_side_die = Die(20) 22 | for _ in range(10): 23 | print(twenty_side_die.roll_die()) -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-2.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | def __init__(self,restaurant_name,cuisine_type): 3 | self.restaurant_name = restaurant_name 4 | self.cuisine_type = cuisine_type 5 | 6 | def describe_restaurant(self): 7 | print(self.restaurant_name + ". " + self.cuisine_type) 8 | 9 | def open_restaurant(self): 10 | print("Restaurant opening...") 11 | 12 | my_restaurant = Restaurant('Happy Pizza','Pizza') 13 | your_restaurant = Restaurant('Happy Pizza','Pizza') 14 | their_restaurant = Restaurant('Happy Pizza','Pizza') 15 | 16 | my_restaurant.open_restaurant() 17 | your_restaurant.open_restaurant() 18 | their_restaurant.open_restaurant() 19 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-3.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | def __init__(self,first_name,last_name,**informations): 3 | self.first_name = first_name 4 | self.last_name = last_name 5 | self.informations = informations 6 | for key,value in informations.items(): 7 | setattr(self,key,value) 8 | 9 | def describe_user(self): 10 | print(self.first_name + " " + self.last_name) 11 | for key, value in self.informations.items(): 12 | print(key + ": " + str(value)) 13 | 14 | def greet_user(self): 15 | print("Hi ! " + self.first_name + ". How are you?") 16 | 17 | ash = User('Ash','One',age = 21,gender = 'male') 18 | ash.greet_user() 19 | ash.describe_user() 20 | 21 | da = User('Da','Lao',age = 39,gender = 'male') 22 | da.greet_user() 23 | da.describe_user() -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-4.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | def __init__(self,restaurant_name,cuisine_type): 3 | self.restaurant_name = restaurant_name 4 | self.cuisine_type = cuisine_type 5 | self.number_served = 0 6 | 7 | def describe_restaurant(self): 8 | print(self.restaurant_name + ". " + self.cuisine_type) 9 | print("There has " + str(self.number_served) + " person rate......") 10 | 11 | def open_restaurant(self): 12 | print("Restaurant opening...") 13 | 14 | def set_number_served(self,number): 15 | self.number_served = number 16 | 17 | def increment_number_served(self,estimated_number): 18 | self.number_served += estimated_number 19 | 20 | my_restaurant = Restaurant('Happy Pizza','Pizza') 21 | 22 | my_restaurant.open_restaurant() 23 | my_restaurant.set_number_served(20) 24 | my_restaurant.increment_number_served(50) 25 | my_restaurant.describe_restaurant() 26 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-5.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | def __init__(self,first_name,last_name,**informations): 3 | self.first_name = first_name 4 | self.last_name = last_name 5 | self.informations = informations 6 | self.login_attempts = 0 7 | for key,value in informations.items(): 8 | setattr(self,key,value) 9 | 10 | def describe_user(self): 11 | print(self.first_name + " " + self.last_name + " Login attempts: " + str(self.login_attempts)) 12 | for key, value in self.informations.items(): 13 | print(key + ": " + str(value)) 14 | 15 | def greet_user(self): 16 | print("Hi ! " + self.first_name + ". How are you?") 17 | 18 | def increment_login_attempts(self): 19 | self.login_attempts += 1 20 | 21 | def reset_login_attempts(self): 22 | self.login_attempts = 0 23 | 24 | ash = User('Ash','One',age = 21,gender = 'male') 25 | ash.greet_user() 26 | ash.describe_user() 27 | ash.increment_login_attempts() 28 | ash.describe_user() 29 | ash.reset_login_attempts() 30 | ash.describe_user() 31 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-6.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | def __init__(self,restaurant_name,cuisine_type): 3 | self.restaurant_name = restaurant_name 4 | self.cuisine_type = cuisine_type 5 | 6 | def describe_restaurant(self): 7 | print(self.restaurant_name + ". " + self.cuisine_type) 8 | 9 | def open_restaurant(self): 10 | print("Restaurant opening...") 11 | 12 | 13 | class IceCreamStand(Restaurant): 14 | def __init__(self,restaurant_name,cuisine_type,flavours): 15 | super().__init__(restaurant_name,cuisine_type) 16 | self.flavours = flavours 17 | 18 | def show_flavors(self): 19 | for flavour in self.flavours: 20 | print(flavour) 21 | 22 | flavours = ['chocolate','original','bannana','milk'] 23 | my_ice_cream = IceCreamStand('Ice Cream Corner','Ice Cream',flavours) 24 | my_ice_cream.show_flavors() -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-7.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | def __init__(self,first_name,last_name,**informations): 3 | self.first_name = first_name 4 | self.last_name = last_name 5 | self.informations = informations 6 | for key,value in informations.items(): 7 | setattr(self,key,value) 8 | 9 | def describe_user(self): 10 | print(self.first_name + " " + self.last_name) 11 | for key, value in self.informations.items(): 12 | print(key + ": " + str(value)) 13 | 14 | def greet_user(self): 15 | print("Hi ! " + self.first_name + ". How are you?") 16 | 17 | class Admin(User): 18 | def __init__(self, first_name, last_name, privileges ,**informations): 19 | super().__init__(first_name, last_name, **informations) 20 | self.privileges = privileges 21 | 22 | def show_privileges(self): 23 | for privilege in self.privileges: 24 | print(f"{self.first_name}" + " " + privilege) 25 | 26 | privileges = ['can add post','can delete post','can ban user'] 27 | web_admin = Admin('Ash','One',privileges ,gender = 'Male') 28 | web_admin.show_privileges() 29 | 30 | 31 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-8.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | def __init__(self,first_name,last_name,**informations): 3 | self.first_name = first_name 4 | self.last_name = last_name 5 | self.informations = informations 6 | for key,value in informations.items(): 7 | setattr(self,key,value) 8 | 9 | def describe_user(self): 10 | print(self.first_name + " " + self.last_name) 11 | for key, value in self.informations.items(): 12 | print(key + ": " + str(value)) 13 | 14 | def greet_user(self): 15 | print("Hi ! " + self.first_name + ". How are you?") 16 | 17 | class Admin(User): 18 | def __init__(self, first_name, last_name ,privileges,**informations): 19 | super().__init__(first_name, last_name, **informations) 20 | self.privileges = privileges 21 | 22 | class Privileges(): 23 | def __init__(self): 24 | self.privileges = ["can add post","can delete post","can ban user"] 25 | 26 | def show_privileges(self,admin_instance): 27 | for privilege in self.privileges: 28 | print(admin_instance + " " + privilege) 29 | 30 | admin_privileges = Privileges() 31 | 32 | web_admin = Admin('Ash','One',admin_privileges,gender = 'Male') 33 | web_admin.privileges.show_privileges(web_admin.first_name) 34 | -------------------------------------------------------------------------------- /Chapter_09/Exercises/9-9.py: -------------------------------------------------------------------------------- 1 | class Battery(): 2 | def __init__(self,bettery_size = 60): 3 | self.battery_size = bettery_size 4 | 5 | def describe_battery(self): 6 | print("This car has a " + str(self.battery_size) + "-kWh battery.") 7 | 8 | def get_range(self): 9 | if self.battery_size == 60: 10 | range = 240 11 | elif self.battery_size == 85: 12 | range = 270 13 | 14 | message = "This car can go approximately " + str(range) 15 | message += " miles on a full charge." 16 | print(message) 17 | 18 | def upgrade_battery(self): 19 | if self.battery_size != 85: 20 | self.battery_size = 85 21 | print("Upgraded the battery to 85 kWh!") 22 | else: 23 | print("The battery is already 85 kWh.") 24 | 25 | class ElectricCar(): 26 | 27 | def __init__(self, make, model, year): 28 | self.make = make 29 | self.model = model 30 | self.year = year 31 | self.battery = Battery() 32 | 33 | def describe_car(self): 34 | long_name = str(self.year) + ' ' + self.make + ' ' + self.model 35 | return long_name.title() 36 | 37 | my_tesla = ElectricCar('tesla', 'model s', 2022) 38 | 39 | print(my_tesla.describe_car()) 40 | my_tesla.battery.get_range() 41 | 42 | my_tesla.battery.upgrade_battery() 43 | my_tesla.battery.get_range() -------------------------------------------------------------------------------- /Chapter_09/Exercises/admin.py: -------------------------------------------------------------------------------- 1 | class User(): 2 | def __init__(self,first_name,last_name,**informations): 3 | self.first_name = first_name 4 | self.last_name = last_name 5 | self.informations = informations 6 | for key,value in informations.items(): 7 | setattr(self,key,value) 8 | 9 | def describe_user(self): 10 | print(self.first_name + " " + self.last_name) 11 | for key, value in self.informations.items(): 12 | print(key + ": " + str(value)) 13 | 14 | def greet_user(self): 15 | print("Hi ! " + self.first_name + ". How are you?") 16 | 17 | class Admin(User): 18 | def __init__(self, first_name, last_name ,privileges,**informations): 19 | super().__init__(first_name, last_name, **informations) 20 | self.privileges = privileges 21 | 22 | class Privileges(): 23 | def __init__(self): 24 | self.privileges = ["can add post","can delete post","can ban user"] 25 | 26 | def show_privileges(self,admin_instance): 27 | for privilege in self.privileges: 28 | print(admin_instance + " " + privilege) 29 | 30 | # Comment for 9-12.py program running. 31 | # admin_privileges = Privileges() 32 | 33 | # web_admin = Admin('Ash','One',admin_privileges,gender = 'Male') 34 | # web_admin.privileges.show_privileges(web_admin.first_name) -------------------------------------------------------------------------------- /Chapter_09/Exercises/privileges.py: -------------------------------------------------------------------------------- 1 | class Privileges(): 2 | def __init__(self): 3 | self.privileges = ["can add post","can delete post","can ban user"] 4 | 5 | def show_privileges(self,admin_instance): 6 | for privilege in self.privileges: 7 | print(admin_instance + " " + privilege) -------------------------------------------------------------------------------- /Chapter_09/Exercises/restaurant.py: -------------------------------------------------------------------------------- 1 | class Restaurant(): 2 | def __init__(self,name): 3 | self.name = name 4 | 5 | def open_restaurant(self): 6 | print("Restaurant is opening......") -------------------------------------------------------------------------------- /Chapter_09/car.py: -------------------------------------------------------------------------------- 1 | class Car(): 2 | def __init__(self,make,model,year): 3 | self.make = make 4 | self.model = model 5 | self.year = year 6 | self.odometer_reading = 0 7 | 8 | def get_descriptive_name(self): 9 | long_name = str(self.year) + ' ' + self.make + ' ' + self.model 10 | return long_name.title() 11 | 12 | def update_odometer(self,mileage): 13 | if mileage >= self.odometer_reading: 14 | self.odometer_reading = mileage 15 | else: 16 | print("You can't roll back an odometer.") 17 | 18 | def read_odometer(self): 19 | print("This car has " + str(self.odometer_reading) + " miles on it.") 20 | 21 | def increment_odometer(self,miles): 22 | self.odometer_reading += miles 23 | 24 | class Battery(): 25 | def __init__(self,battery_size = 60): 26 | self.battery_size = battery_size 27 | 28 | def describe_battery(self): 29 | print("This car has a " + str(self.battery_size) + "-kWh battery.") 30 | 31 | def get_range(self): 32 | range = 210 33 | if self.battery_size == 70: 34 | range = 240 35 | elif self.battery_size == 85: 36 | range = 270 37 | message = "This car can go approximately " + str(range) 38 | message += " miles on a full charge." 39 | print(message) 40 | 41 | class Electric_car(Car): 42 | 43 | def __init__(self,make,model,year): 44 | super().__init__(make,model,year) 45 | self.battery = Battery() 46 | -------------------------------------------------------------------------------- /Chapter_09/dog.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | def __init__(self,name,age): 3 | self.name = name 4 | self.age = age 5 | 6 | def sit(self): 7 | print(self.name.title() + " is now sitting.") 8 | 9 | def roll_over(self): 10 | print(self.name.title() + " rolled over!") 11 | 12 | my_dog = Dog('willie',5) 13 | your_dog = Dog('lucy',3) 14 | 15 | print("My dog's name is " + my_dog.name.title() + ".") 16 | print("My dog is " + str(my_dog.age) + " years old.") 17 | my_dog.sit() 18 | my_dog.roll_over() 19 | 20 | print("Your dog's name is " + your_dog.name + ".") 21 | print("Your dog is " + str(your_dog.age) + " years old.") 22 | your_dog.sit() 23 | your_dog.roll_over() -------------------------------------------------------------------------------- /Chapter_09/electric_car.py: -------------------------------------------------------------------------------- 1 | from car import Car 2 | 3 | class Battery(): 4 | def __init__(self,battery_size = 60): 5 | self.battery_size = battery_size 6 | 7 | def describe_battery(self): 8 | print("This car has a " + str(self.battery_size) + "-kWh battery.") 9 | 10 | def get_range(self): 11 | range = 210 12 | if self.battery_size == 70: 13 | range = 240 14 | elif self.battery_size == 85: 15 | range = 270 16 | message = "This car can go approximately " + str(range) 17 | message += " miles on a full charge." 18 | print(message) 19 | 20 | class Electric_car(Car): 21 | 22 | def __init__(self,make,model,year): 23 | super().__init__(make,model,year) 24 | self.battery = Battery() 25 | -------------------------------------------------------------------------------- /Chapter_09/favorite.languages.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | favorite_languages = OrderedDict() 4 | 5 | favorite_languages['jen'] = 'python' 6 | favorite_languages['sarah'] = 'c' 7 | favorite_languages['edward'] = 'ruby' 8 | favorite_languages['phil'] = 'python' 9 | 10 | for name,language in favorite_languages.items(): 11 | print(name.title() + "'s favorite language is " + language.title()) 12 | -------------------------------------------------------------------------------- /Chapter_09/my_car.py: -------------------------------------------------------------------------------- 1 | from car import Car 2 | from electric_car import Electric_car 3 | 4 | my_beetle = Car('volkswagen', 'beetle', 2016) 5 | print(my_beetle.get_descriptive_name()) 6 | my_tesla = Electric_car('tesla', 'roadster', 2016) 7 | print(my_tesla.get_descriptive_name()) -------------------------------------------------------------------------------- /Chapter_09/my_electric_car.py: -------------------------------------------------------------------------------- 1 | from car import Electric_car 2 | 3 | my_tesla = Electric_car('tesla','model s',2016) 4 | 5 | print(my_tesla.get_descriptive_name()) 6 | my_tesla.battery.describe_battery() 7 | my_tesla.battery.get_range() -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-1.py: -------------------------------------------------------------------------------- 1 | file_name = 'learning_python.txt' 2 | with open(file_name) as file_object: 3 | contents = file_object.read() 4 | print(contents.rstrip()) 5 | print("----------------------------") 6 | with open(file_name) as file_object: 7 | for line in file_object: 8 | print(line.rstrip()) 9 | print("----------------------------") 10 | with open(file_name) as file_object: 11 | lines = file_object.readlines() 12 | 13 | for line in lines: 14 | print(line.rstrip()) -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-10.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | filename = 'favorite_number.json' 4 | 5 | try: 6 | with open(filename,'w',encoding='UTF-8') as file_object: 7 | favorite_number = int(input("What is your favorite number?")) 8 | json.dump(favorite_number,file_object) 9 | except ValueError: 10 | print("Please enter a int number.") 11 | 12 | try: 13 | with open(filename,'r',encoding='UTF-8') as file_object: 14 | favorite_number = json.load(file_object) 15 | except (FileNotFoundError,json.JSONDecodeError): 16 | print("File not found.") 17 | else: 18 | print("I know your favorite number! It's " + str(favorite_number) + ".") -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-11.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | favorite_number = input("Please enter your favorite number.") 4 | 5 | filename = 'favorite_number.json' 6 | with open(filename, 'w') as f: 7 | json.dump(favorite_number, f) 8 | 9 | filename = 'favorite_number.json' 10 | try: 11 | with open(filename) as f: 12 | favorite_number = json.load(f) 13 | except FileNotFoundError: 14 | print("File not found.") 15 | else: 16 | # 打印消息 17 | print(f"I know your favorite number! It's {favorite_number}.") -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-12.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | def store_favorite_number(filename): 5 | try: 6 | with open(filename,'w',encoding='UTF-8') as file_object: 7 | favorite_number = int(input("What is your favorite number?")) 8 | json.dump(favorite_number,file_object) 9 | except ValueError: 10 | print("Please input a int number.") 11 | 12 | def read_favorite_number(filename): 13 | try: 14 | with open(filename,'r',encoding='UTF-8') as file_object: 15 | return json.load(file_object) 16 | except FileNotFoundError: 17 | print("File not found!") 18 | except json.JSONDecodeError: 19 | print("Json decode error!") 20 | 21 | 22 | filename = 'favorite_number.json' 23 | favorite_number = read_favorite_number(filename) 24 | if favorite_number: 25 | print(favorite_number) 26 | else: 27 | favorite_number = read_favorite_number(filename) 28 | store_favorite_number(filename) 29 | if favorite_number: 30 | print(favorite_number) -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-13.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | def get_new_username(filename): 5 | username = input("What is your name? ") 6 | with open(filename, 'w', encoding='UTF-8') as file_object: 7 | json.dump(username, file_object) 8 | return username 9 | 10 | def get_stored_username(filename): 11 | try: 12 | with open(filename, 'r', encoding='UTF-8') as file_object: 13 | return json.load(file_object) 14 | except FileNotFoundError: 15 | return None 16 | except json.JSONDecodeError: 17 | return None 18 | 19 | def greet_user(filename): 20 | username = get_stored_username(filename) 21 | if username: 22 | correct = input(f"Are you {username}? (yes/no) ") 23 | if correct.lower() == 'yes': 24 | print(f"Welcome back, {username}!") 25 | else: 26 | username = get_new_username(filename) 27 | print(f"We'll remember you when you come back, {username}!") 28 | else: 29 | username = get_new_username(filename) 30 | print(f"We'll remember you when you come back, {username}!") 31 | 32 | filename = 'username.json' 33 | greet_user(filename) 34 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-2.py: -------------------------------------------------------------------------------- 1 | file_name = 'learning_python.txt' 2 | text = '' 3 | 4 | with open(file_name) as file_object: 5 | lines = file_object.readlines() 6 | 7 | for line in lines: 8 | text = line.replace('Python','C++') 9 | 10 | print(text) -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-3.py: -------------------------------------------------------------------------------- 1 | filename = 'guest.txt' 2 | active = '' 3 | with open(filename,'a') as file_object: 4 | while True: 5 | guest_name = input("Please enter a guest's name.(enter quit to end the program)") 6 | if guest_name.title() == 'Quit': 7 | break 8 | else: 9 | file_object.write(guest_name + "\n") 10 | print("Thank you! " + guest_name.title() + " has been added.") 11 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-4.py: -------------------------------------------------------------------------------- 1 | # Same as 10-3.py 2 | filename = 'guest_book.txt' 3 | active = '' 4 | with open(filename,'a') as file_object: 5 | while True: 6 | guest_name = input("Please enter a guest's name.(enter quit to end the program)") 7 | if guest_name.title() == 'Quit': 8 | break 9 | else: 10 | file_object.write(guest_name + "\n") 11 | print("Thank you! " + guest_name.title() + " has been added.") 12 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-5.py: -------------------------------------------------------------------------------- 1 | filename = 'programming_reasons.txt' 2 | programming_reasons = {} 3 | 4 | while True: 5 | # 询问并获取用户名 6 | username = input("Please enter your name (or 'quit' to exit): ") 7 | 8 | if username.lower() == 'quit': 9 | break 10 | 11 | reason = input(f"Hello, {username.title()}! Why do you like programming? ") 12 | 13 | programming_reasons[username] = reason 14 | 15 | # 将原因写入文件 16 | with open(filename, 'a') as file: 17 | file.write(f"{username}: {reason}\n") 18 | print(f"Thanks, {username.title()}! Your reason has been added to {filename}.") 19 | 20 | for name, reason in programming_reasons.items(): 21 | print(f"{name.title()}: {reason}") 22 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-6.py: -------------------------------------------------------------------------------- 1 | while True: 2 | try: 3 | number_1 = int(input("Please enter number1.")) 4 | number_2 = int(input("Please enter number1.")) 5 | except ValueError: 6 | print("Please enter int number!!!") 7 | else: 8 | sum = number_1 + number_2 9 | print(f"The sum of {number_1} and {number_2} is {sum}.") 10 | 11 | choice = input("Do you want to try again? (yes/no): ").lower() 12 | if choice != 'yes': 13 | break -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-7.py: -------------------------------------------------------------------------------- 1 | def print_file(filename): 2 | try: 3 | with open(filename,'r') as file_object: 4 | contents = file_object.read() 5 | except FileNotFoundError: 6 | print(filename.title() + " not found!") 7 | else: 8 | print(contents.rstrip()) 9 | 10 | filenames = ['cats.txt','dogs.txt'] 11 | for filename in filenames: 12 | print_file(filename) -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-8.py: -------------------------------------------------------------------------------- 1 | def print_file(filename): 2 | try: 3 | with open(filename,'r') as file_object: 4 | contents = file_object.read() 5 | except FileNotFoundError: 6 | pass 7 | else: 8 | print(contents.rstrip()) 9 | 10 | filenames = ['cats.txt','dogs.txt'] 11 | for filename in filenames: 12 | print_file(filename) -------------------------------------------------------------------------------- /Chapter_10/Exercises/10-9.py: -------------------------------------------------------------------------------- 1 | def count_word(filename): 2 | try: 3 | with open(filename,'r',encoding='UTF-8') as file_object: 4 | contents = file_object.read() 5 | except FileNotFoundError: 6 | print("File not found!") 7 | else: 8 | word_count = contents.lower().count('the') 9 | print("The number of 'the' is " + str(word_count) + ".") 10 | 11 | count_word('gutenberg.txt') -------------------------------------------------------------------------------- /Chapter_10/Exercises/cats.txt: -------------------------------------------------------------------------------- 1 | Jack 2 | Ash 3 | Lin -------------------------------------------------------------------------------- /Chapter_10/Exercises/favorite_number.json: -------------------------------------------------------------------------------- 1 | "12" -------------------------------------------------------------------------------- /Chapter_10/Exercises/guest.txt: -------------------------------------------------------------------------------- 1 | Jack 2 | Ash 3 | Zhou 4 | Jay 5 | JJ 6 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/guest_book.txt: -------------------------------------------------------------------------------- 1 | JJ king 2 | SKY 3 | THE SHY 4 | 55 KAI 5 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/gutenberg.txt: -------------------------------------------------------------------------------- 1 | In the heart of the town named Greensville, there lay a mysterious mansion known to the locals as the ‘Whispering House’. Nobody knew why it was named so, or who lived there, but stories about it passed down through generations, giving it an aura of mystique. 2 | 3 | In 1902, the mansion was owned by Lord Harrington, a nobleman known for his extravagant parties. Guests from all over the region would flock to the Whispering House to be part of these grand events. With chandeliers hanging from the ceilings, intricate paintings adorning the walls, and golden cutlery laid out on the tables, the mansion was a symbol of opulence. 4 | 5 | However, as the years went by, Lord Harrington started to change. Those who met him spoke of a distant look in his eyes, as if he was constantly lost in thought. Soon, the parties stopped. The mansion, once lively, fell silent. 6 | 7 | One fateful night, the town folks saw a bright light emanating from the mansion. The next day, Lord Harrington was nowhere to be found. The Whispering House was deserted. As days turned into weeks and weeks into months, the stories began. People claimed to hear faint whispers coming from the mansion, especially on full moon nights. 8 | 9 | Catherine, an inquisitive journalist, had recently moved to Greensville. She was fascinated by the mansion's story and decided to investigate. With a notebook in hand, she approached the mansion one evening. 10 | 11 | The main gate creaked open. Inside, the once-beautiful garden was now overgrown with weeds. As Catherine stepped into the mansion, she felt a cold breeze. The grand hall, which once echoed with laughter and chatter, was now filled with an eerie silence. 12 | 13 | Catherine started exploring room by room. In the ballroom, she saw the remnants of the last party; glasses half-filled with wine and plates with morsels of food, now covered in a thick layer of dust. In Lord Harrington's study, books lay scattered everywhere, and a lone diary rested on the desk. 14 | 15 | Curiosity piqued, Catherine started reading the diary. The entries spoke of Lord Harrington's discovery of a mysterious artifact during his travels to Egypt. It was a pendant with a bright blue gemstone. According to local legends, the gemstone had magical powers that could grant wishes but at a great cost. 16 | 17 | As Catherine read on, she realized that Lord Harrington had started wearing the pendant constantly. He wrote of hearing voices, which grew louder with each passing day. The last entry was particularly chilling. It read, “The voices won't stop. They are demanding a price I cannot pay." -------------------------------------------------------------------------------- /Chapter_10/Exercises/learning_python.txt: -------------------------------------------------------------------------------- 1 | In Python, you can easily create and manipulate lists, which are versatile data structures for storing collections of items. 2 | In Python, you can define functions using the def keyword, allowing you to encapsulate reusable blocks of code. 3 | In Python, you can work with object-oriented programming (OOP) principles, defining classes and creating objects to model real-world entities. -------------------------------------------------------------------------------- /Chapter_10/Exercises/programming_reasons.txt: -------------------------------------------------------------------------------- 1 | Ash: Love 2 | Jack: Love 3 | Li: Love 4 | -------------------------------------------------------------------------------- /Chapter_10/Exercises/username.json: -------------------------------------------------------------------------------- 1 | "jack" -------------------------------------------------------------------------------- /Chapter_10/alice.py: -------------------------------------------------------------------------------- 1 | filename = 'alice.txt' 2 | 3 | try: 4 | with open(filename) as file_object: 5 | contents = file_object.read() 6 | except FileNotFoundError: 7 | msg = "Sorry, the file " + filename + " does not exist." 8 | print(msg) 9 | else: 10 | words = contents.split() 11 | print(type(words)) 12 | num_words = len(words) 13 | print("The file " + filename + " has about " + str(num_words) + " words.") -------------------------------------------------------------------------------- /Chapter_10/division.py: -------------------------------------------------------------------------------- 1 | try: 2 | print(5/0) 3 | except ZeroDivisionError: 4 | print("You can't divine by zero!") 5 | 6 | print("Give me two numbers. and I'll divine them.") 7 | print("Enter 'q' to quit.") 8 | 9 | while True: 10 | first_number = int(input("\nFirst number:")) 11 | if first_number == 'q': 12 | break 13 | second_number = int(input("\nFirst number:")) 14 | if second_number == 'q': 15 | break 16 | try: 17 | answer = int(first_number) / int(second_number) 18 | except ZeroDivisionError: 19 | print("You can't divine by 0.") 20 | else: 21 | print(answer) 22 | -------------------------------------------------------------------------------- /Chapter_10/file_reader.py: -------------------------------------------------------------------------------- 1 | file_name = 'pi_digits.txt' 2 | 3 | with open(file_name) as file_object: 4 | contents = file_object.read() 5 | print(contents.rstrip()) 6 | 7 | with open(file_name) as file_object: 8 | for line in file_object: 9 | print(line.rstrip()) 10 | 11 | with open(file_name) as file_object: 12 | lines = file_object.readlines() 13 | for line in lines: 14 | print(line.rstrip()) -------------------------------------------------------------------------------- /Chapter_10/greet_me.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_10/greet_me.py -------------------------------------------------------------------------------- /Chapter_10/number.json: -------------------------------------------------------------------------------- 1 | [2, 3, 5, 7, 11, 13] -------------------------------------------------------------------------------- /Chapter_10/number_reader.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | filename = 'number.json' 4 | with open(filename,'r') as file_object: 5 | numbers = json.load(file_object) 6 | 7 | print(numbers) -------------------------------------------------------------------------------- /Chapter_10/number_writer.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | numbers = [2,3,5,7,11,13] 4 | 5 | filename = 'number.json' 6 | with open(filename,'w') as file_object: 7 | json.dump(numbers,file_object) -------------------------------------------------------------------------------- /Chapter_10/pi_digits.txt: -------------------------------------------------------------------------------- 1 | 3.1415926535 2 | 8979323846 3 | 2643383279 -------------------------------------------------------------------------------- /Chapter_10/pi_string.py: -------------------------------------------------------------------------------- 1 | file_name = 'pi_digits.txt' 2 | 3 | with open(file_name) as file_object: 4 | lines = file_object.readlines() 5 | 6 | pi_string = '' 7 | for line in lines: 8 | pi_string += line.strip() 9 | 10 | print(pi_string) 11 | print(len(pi_string)) 12 | 13 | 14 | file_name = 'pi_million_digits.txt' 15 | with open(file_name) as file_object: 16 | lines = file_object.readlines() 17 | 18 | pi_string = '' 19 | for line in lines: 20 | pi_string += line.strip() 21 | 22 | print(pi_string[:52] + "...") 23 | print(len(pi_string)) 24 | 25 | with open(file_name) as file_object: 26 | lines = file_object.readlines() 27 | pi_string = '' 28 | 29 | for line in lines: 30 | pi_string += line 31 | 32 | birthday = input("Enter your birthday, in the mmddyy") 33 | if birthday in pi_string: 34 | print("Your birthday appears in the first million digits of pi!") 35 | else: 36 | print("Your birthday does not appear in the first million digits of pi.") -------------------------------------------------------------------------------- /Chapter_10/programing .txt: -------------------------------------------------------------------------------- 1 | I love programing. 2 | I love creating new game. 3 | I love sleep. 4 | I love music. 5 | -------------------------------------------------------------------------------- /Chapter_10/remenber_me.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | def get_stored_username(): 4 | filename = 'username.json' 5 | try: 6 | with open(filename,'r',encoding='UTF-8') as file_object: 7 | username = json.load(file_object) 8 | except (FileNotFoundError,json.JSONDecodeError): 9 | return None 10 | else: 11 | return username 12 | 13 | def get_new_username(): 14 | username = input("What is your name?") 15 | filename = 'username.json' 16 | with open(filename,'w',encoding='UTF-8') as file_object: 17 | json.dump(username,file_object) 18 | return username 19 | 20 | def greet_user(): 21 | username = get_stored_username() 22 | if username: 23 | print("Welcome back, " + username + "!") 24 | else: 25 | username = get_new_username() 26 | print("We'll remember you when you come back, " + username + "!") 27 | 28 | greet_user() -------------------------------------------------------------------------------- /Chapter_10/username.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_10/username.json -------------------------------------------------------------------------------- /Chapter_10/word_count.py: -------------------------------------------------------------------------------- 1 | def count_word(filename): 2 | try: 3 | with open(filename) as file_object: 4 | contents = file_object.read() 5 | except FileNotFoundError: 6 | msg = "Sorry, the file " + filename + " does not exist." 7 | print(msg) 8 | else: 9 | words = contents.split() 10 | num_words = len(words) 11 | print("The file " + filename + " has about " + str(num_words) + " words.") 12 | 13 | filenames = ['alice.txt','pi_digits.txt','pi_million_digits.txt'] 14 | for filename in filenames: 15 | count_word(filename) -------------------------------------------------------------------------------- /Chapter_10/write_message.py: -------------------------------------------------------------------------------- 1 | filename = 'programing .txt' 2 | 3 | with open(filename,'a') as file_object: 4 | file_object.write("I love sleep.\n") 5 | file_object.write("I love music.\n") -------------------------------------------------------------------------------- /Chapter_11/Exercises/cities.py: -------------------------------------------------------------------------------- 1 | def get_city_info(city,country,population = ''): 2 | if population: 3 | return city.title() + ", " + country.title() + " - population " + str(population) 4 | else: 5 | return city.title() + ", " + country.title() -------------------------------------------------------------------------------- /Chapter_11/Exercises/employee.py: -------------------------------------------------------------------------------- 1 | class Employee(): 2 | def __init__(self, first_name, last_name, annual_salary=5000): 3 | self.first_name = first_name 4 | self.last_name = last_name 5 | self.annual_salary = annual_salary 6 | 7 | def give_raise(self, amount): 8 | self.annual_salary += amount 9 | -------------------------------------------------------------------------------- /Chapter_11/Exercises/test_cities.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from cities import get_city_info 3 | 4 | 5 | class Cities_Test(unittest.TestCase): 6 | 7 | def test_city_info(self): 8 | city_info = get_city_info('santiago', 'chile') 9 | self.assertEqual(city_info, 'Santiago, Chile') 10 | 11 | def test_city_info_population(self): 12 | city_info = get_city_info('santiago', 'chile', '50000') 13 | self.assertEqual(city_info, 'Santiago, Chile - population 50000') 14 | 15 | def test_city_info_no_population(self): 16 | city_info = get_city_info('santiago', 'chile') 17 | self.assertEqual(city_info, 'Santiago, Chile') 18 | 19 | 20 | if __name__ == '__main__': 21 | unittest.main() -------------------------------------------------------------------------------- /Chapter_11/Exercises/test_employee.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from employee import Employee 3 | 4 | 5 | class MyTestCase(unittest.TestCase): 6 | def setUp(self): 7 | self.new_employee = Employee('Ash', 'Liu') 8 | 9 | def test_give_default_raise(self): 10 | self.assertEqual(self.new_employee.annual_salary, 5000) 11 | 12 | def test_give_custom_raise(self): 13 | self.new_employee.give_raise(10000) 14 | self.assertEqual(self.new_employee.annual_salary, 15000) 15 | 16 | 17 | if __name__ == '__main__': 18 | unittest.main() 19 | -------------------------------------------------------------------------------- /Chapter_11/language_survey.py: -------------------------------------------------------------------------------- 1 | from survey import AnonymousSurvey 2 | 3 | question = "What language did you first learn to speak?" 4 | my_survey = AnonymousSurvey(question) 5 | 6 | my_survey.show_question() 7 | print("Enter 'q' at any time to quit\n") 8 | 9 | while True: 10 | response = input("Language:") 11 | if response == 'q': 12 | break 13 | my_survey.store_response(response) 14 | 15 | my_survey.show_results() -------------------------------------------------------------------------------- /Chapter_11/name_function.py: -------------------------------------------------------------------------------- 1 | def get_formatted_name(first,last,middle = ''): 2 | if middle: 3 | full_name = first + ' ' + middle + ' ' + last 4 | else: 5 | full_name = first + ' ' + last 6 | return full_name.title() 7 | 8 | -------------------------------------------------------------------------------- /Chapter_11/names.py: -------------------------------------------------------------------------------- 1 | from name_function import get_formatted_name 2 | 3 | print("Enter 'q' at any time to quit.") 4 | 5 | while True: 6 | first = input("\nPlease give me a first name:") 7 | if first.lower() == 'q': 8 | break 9 | last = input("Please give me a last name:") 10 | if last.lower() == 'q': 11 | break 12 | 13 | formatted_name = get_formatted_name(first,last) 14 | print("\nNeatly formatted name:"+ formatted_name + '.') 15 | -------------------------------------------------------------------------------- /Chapter_11/survey.py: -------------------------------------------------------------------------------- 1 | class AnonymousSurvey(): 2 | def __init__(self,question): 3 | self.question = question 4 | self.responses = [] 5 | 6 | def show_question(self): 7 | print(self.question) 8 | 9 | def store_response(self,new_response): 10 | self.responses.append(new_response) 11 | 12 | def show_results(self): 13 | print("Survey results:") 14 | for response in self.responses: 15 | print('- ',response) -------------------------------------------------------------------------------- /Chapter_11/test_name_function.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from name_function import get_formatted_name 3 | 4 | 5 | class NameTestCase(unittest.TestCase): 6 | 7 | def test_first_last_name(self): 8 | formatted_name = get_formatted_name('janis', 'joplin') 9 | self.assertEqual(formatted_name, 'Janis Joplin') 10 | 11 | def test_first_middle_last_name(self): 12 | formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus') 13 | self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart') 14 | 15 | 16 | if __name__ == '__main__': 17 | unittest.main() 18 | -------------------------------------------------------------------------------- /Chapter_11/test_survey.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from survey import AnonymousSurvey 3 | 4 | 5 | class TestAnonymousSurvey(unittest.TestCase): 6 | 7 | def setUp(self): 8 | question = "What language did you first learn to speak?" 9 | self.my_survey = AnonymousSurvey(question) 10 | self.responses = ['English', 'C++', 'Java'] 11 | 12 | def test_store_single_response(self): 13 | self.my_survey.store_response(self.responses[0]) 14 | self.assertIn('English', self.my_survey.responses) 15 | 16 | def test_store_three_response(self): 17 | question = "What language did you first learn to speak?" 18 | my_survey = AnonymousSurvey(question) 19 | for response in self.responses: 20 | my_survey.store_response(response) 21 | self.assertIn(response, my_survey.responses) 22 | 23 | 24 | if __name__ == '__main__': 25 | unittest.main() -------------------------------------------------------------------------------- /Chapter_15/README.md: -------------------------------------------------------------------------------- 1 | Chapter 15 2 | === 3 | 4 | - [Installing matplotlib](#installing-matplotlib) 5 | - [Checking if matplotlib is already installed](#checking-if-matplotlib-is-already-installed) 6 | - [Installing matplotlib on Linux](#installing-matplotlib-on-linux) 7 | - [Installing matplotlib on OS X](#installing-matplotlib-on-os-x) 8 | - [Installing matplotlib on Windows](#installing-matplotlib-on-windows) 9 | - [Installing Pygal](#installing-pygal) 10 | - [Updates](#updates) 11 | 12 | Installing matplotlib 13 | --- 14 | 15 | There are many different ways to install matplotlib to your system. In this section, I'll recommend one method for each operating system. If you'd like to see the kinds of visualizations you can make with matplotlib, see the official matplotlib [sample gallery](http://matplotlib.org/gallery.html). When you click a visualization in the gallery, you can see the code used to generate the plot. 16 | 17 | ### Checking if matplotlib is already installed 18 | 19 | First, check if matplotlib is already installed on your system: 20 | 21 | $ python 22 | >>> import matplotlib 23 | >>> 24 | 25 | If you don't see an error message, then matplotlib is already installed on your system and you should be able to get started right away on this chapter's projects. If you get an error message, read the appropriate section below for help installing matplotlib on your operating system. 26 | 27 | Installing matplotlib on Linux 28 | --- 29 | 30 | If you're using the version of Python that came with your system, you can use your system's package manager to install matplotlib in one line. For Python 3, this is: 31 | 32 | $ sudo apt-get install python3-matplotlib 33 | 34 | If you're using Python 2.7, this is: 35 | 36 | $ sudo apt-get install python-matplotlib 37 | 38 | If you installed a newer version of Python, you'll have to install several libraries that matplotlib depends on: 39 | 40 | $ sudo apt-get install python3.5-dev python3.5-tk tk-dev 41 | $ sudo apt-get install libfreetype6-dev g++ 42 | 43 | Then use pip to install matplotlib: 44 | 45 | $ pip install --user matplotlib 46 | 47 | If you need help using pip, see the instructions in Chapter 12. 48 | 49 | [top](#) 50 | 51 | Installing matplotlib on OS X 52 | --- 53 | 54 | Aple includes matplotlib with its standard Python installation, so make sure you check if it's already installed before installing it yourself. 55 | 56 | If matplotlib is not already installed and you used Homebrew to install Python, install it like this: 57 | 58 | $ pip install --user matplotlib 59 | 60 | If you need help using pip, see the instructions in Chapter 12. If you have trouble installing matplotlib using pip, try leaving off the `--user` flag. 61 | 62 | [top](#) 63 | 64 | Installing matplotlib on Windows 65 | --- 66 | 67 | To install matplotlib on Windows you'll first need to install Visual Studio, which will help your system install the packages that matplotlib depends on. Go to [https://dev.windows.com/](https://dev.windows.com/), click [**Downloads**](https://dev.windows.com/downloads), and look for *Visual Studio Community*. This is a free set of developer tools for Windows. Download and run the installer. 68 | 69 | Next you'll need an installer for matplotlib. Go to [https://pypi.python.org/pypi/matplotlib/](https://pypi.python.org/pypi/matplotlib/) and look for a wheel file (a file ending in *.whl*) that matches the version of Python you’re using. For example, if you’re using a 32-bit version of Python 3.5, you’ll need to download *matplotlib-1.4.3-cp35-none-win32.whl*. 70 | 71 | If you don't see a file matching your installed version of Python, look at what’s available at [http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib](http://www.lfd.uci.edu/~gohlke/pythonlibs/#matplotlib). This site tends to release installers a little earlier than the official matplotlib site. 72 | 73 | Copy the *.whl* file to your project folder, open a command window, and navigate to the project folder. Then use pip to install matplotlib: 74 | 75 | > cd python_work 76 | python_work> python -m pip install --user matplotlib-1.4.3-cp35-none-win32.whl 77 | 78 | If you need help using pip, see the instructions in Chapter 12. 79 | 80 | [top](#) 81 | 82 | Installing Pygal 83 | --- 84 | Pygal has been updated recently, which is a good thing; you're learning a library that's being steadily improved. This also means you have two choices about how to install Pygal. You can install version 1.7 which supports the code in the book exactly as it's written, or you can install the most recent version of Pygal and modify some of the code in the book. If you install the most recent version there are some slight changes you'll need to make for the code in the second half of chapters 15 and 16, and chapter 17. 85 | 86 | ### Running Pygal code exactly as it appears in the book 87 | 88 | Pygal 1.7 allows the code to run exactly as it appears in the book. To do this, modify the command for installing pygal so pip will install version 1.7 (page 340): 89 | 90 | $ pip install --user pygal==1.7 91 | 92 | On Windows, this would be: 93 | 94 | > python -m pip install --user pygal==1.7 95 | 96 | If you've already installed Pygal you can see which version was installed by running the command `pip freeze`: 97 | 98 | $ pip freeze 99 | pygal==2.1.1 100 | 101 | If you installed Pygal 2.0 or later and want to install 1.7 instead, uninstall Pygal first: 102 | 103 | $ pip uninstall pygal 104 | $ pip install --user pygal==1.7 105 | 106 | ### Using the latest version of Pygal 107 | 108 | The latest version of Pygal is version 2.1.1. This is the version that will be installed if you don't specify a version for pip to install: 109 | 110 | $ pip install --user pygal 111 | 112 | or 113 | 114 | $ python -m pip install --user pygal 115 | 116 | If you use the latest version, you'll need to make some slight changes to the code in chapter 16 and chapter 17: 117 | 118 | - [Updates to Chapter 16 Pygal code](../../pcc/chapter_16/README.md#updates) 119 | - [Updates to Chapter 17 Pygal code](../../pcc/chapter_17/README.md#updates) 120 | 121 | [top](#) 122 | 123 | Updates 124 | --- 125 | 126 | Pygal has been updated to version 2; make sure you've read the notes about [installing Pygal](#installing-pygal) above. 127 | 128 | If you're using Pygal version 2.0 or higher you'll need to add one line to each file in order to render the charts correctly. Pygal has changed the way tooltips are displayed, so if you don't add this line you won't see any tooltips when you hover over the bars on a chart. 129 | 130 | Each time you make a chart in Pygal, add a line that tells Pygal to make an SVG file that renders correctly in a browser. For example: 131 | 132 | hist = pygal.Bar() 133 | hist.force_uri_protocol = 'http' 134 | 135 | This causes Pygal to configure the SVG rendering engine to work correctly for displaying the files in a browser. 136 | 137 | Page by page updates 138 | --- 139 | 140 | Code that appears in bold is new, or is modified from what appears in the book. 141 | 142 | ### p. 342, die_visual.py 143 | 144 |
145 | hist = pygal.Bar() 146 | hist.force_uri_protocol = 'http' 147 |148 | 149 | ### p. 343-344, dice_visual.py 150 | 151 |
152 | hist = pygal.Bar() 153 | hist.force_uri_protocol = 'http' 154 |155 | 156 | ### p. 345, different_dice.py 157 | 158 |
159 | hist = pygal.Bar() 160 | hist.force_uri_protocol = 'http' 161 |-------------------------------------------------------------------------------- /Chapter_15/dice_visual.py: -------------------------------------------------------------------------------- 1 | import pygal 2 | 3 | from die import Die 4 | 5 | # Create two D6 dice. 6 | die_1 = Die() 7 | die_2 = Die() 8 | 9 | # Make some rolls, and store results in a list. 10 | results = [] 11 | for roll_num in range(1000): 12 | result = die_1.roll() + die_2.roll() 13 | results.append(result) 14 | 15 | # Analyze the results. 16 | frequencies = [] 17 | max_result = die_1.num_sides + die_2.num_sides 18 | for value in range(2, max_result+1): 19 | frequency = results.count(value) 20 | frequencies.append(frequency) 21 | 22 | # Visualize the results. 23 | hist = pygal.Bar() 24 | 25 | hist.title = "Results of rolling two D6 dice 1000 times." 26 | hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] 27 | hist.x_title = "Result" 28 | hist.y_title = "Frequency of Result" 29 | 30 | hist.add('D6 + D6', frequencies) 31 | hist.render_to_file('dice_visual.svg') 32 | -------------------------------------------------------------------------------- /Chapter_15/die.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | class Die(): 4 | """A class representing a single die.""" 5 | 6 | def __init__(self, num_sides=6): 7 | """Assume a six-sided die.""" 8 | self.num_sides = num_sides 9 | 10 | def roll(self): 11 | """"Return a random value between 1 and number of sides.""" 12 | return randint(1, self.num_sides) 13 | -------------------------------------------------------------------------------- /Chapter_15/die_visual.py: -------------------------------------------------------------------------------- 1 | import pygal 2 | 3 | from die import Die 4 | 5 | # Create a D6. 6 | die = Die() 7 | 8 | # Make some rolls, and store results in a list. 9 | results = [] 10 | for roll_num in range(1000): 11 | result = die.roll() 12 | results.append(result) 13 | 14 | # Analyze the results. 15 | frequencies = [] 16 | for value in range(1, die.num_sides+1): 17 | frequency = results.count(value) 18 | frequencies.append(frequency) 19 | 20 | # Visualize the results. 21 | hist = pygal.Bar() 22 | 23 | hist.title = "Results of rolling one D6 1000 times." 24 | hist.x_labels = ['1', '2', '3', '4', '5', '6'] 25 | hist.x_title = "Result" 26 | hist.y_title = "Frequency of Result" 27 | 28 | hist.add('D6', frequencies) 29 | hist.render_to_file('die_visual.svg') 30 | -------------------------------------------------------------------------------- /Chapter_15/different_dice.py: -------------------------------------------------------------------------------- 1 | from die import Die 2 | 3 | import pygal 4 | 5 | # Create a D6 and a D10. 6 | die_1 = Die() 7 | die_2 = Die(10) 8 | 9 | # Make some rolls, and store results in a list. 10 | results = [] 11 | for roll_num in range(50000): 12 | result = die_1.roll() + die_2.roll() 13 | results.append(result) 14 | 15 | # Analyze the results. 16 | frequencies = [] 17 | max_result = die_1.num_sides + die_2.num_sides 18 | for value in range(2, max_result+1): 19 | frequency = results.count(value) 20 | frequencies.append(frequency) 21 | 22 | # Visualize the results. 23 | hist = pygal.Bar() 24 | 25 | hist.title = "Results of rolling a D6 and a D10 50,000 times." 26 | hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 27 | '13', '14', '15', '16'] 28 | hist.x_title = "Result" 29 | hist.y_title = "Frequency of Result" 30 | 31 | hist.add('D10 + D10', frequencies) 32 | hist.render_to_file('dice_visual.svg') 33 | -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-01.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-02.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-03.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-04.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-04.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-05.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-06.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-06.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-07.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-07.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-08.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-09.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-09.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-10.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-11.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-12.png -------------------------------------------------------------------------------- /Chapter_15/figures/crash_course15-13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KawaiiAsh/pythoncrashcourse-exercises/9593a9b4ff2384275149b063153e0164b1920e63/Chapter_15/figures/crash_course15-13.png -------------------------------------------------------------------------------- /Chapter_15/mpl_squares.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | input_values = [1, 2, 3, 4, 5] 4 | squares = [1, 4, 9, 16, 25] 5 | plt.plot(input_values, squares, linewidth=5) 6 | 7 | # Set chart title and label axes. 8 | plt.title("Square Numbers", fontsize=24) 9 | plt.xlabel("Value", fontsize=14) 10 | plt.ylabel("Square of Value", fontsize=14) 11 | 12 | # Set size of tick labels. 13 | plt.tick_params(axis='both', labelsize=14) 14 | 15 | plt.show() 16 | -------------------------------------------------------------------------------- /Chapter_15/pygal2_update/dice_visual.py: -------------------------------------------------------------------------------- 1 | import pygal 2 | 3 | from die import Die 4 | 5 | # Create two D6 dice. 6 | die_1 = Die() 7 | die_2 = Die() 8 | 9 | # Make some rolls, and store results in a list. 10 | results = [] 11 | for roll_num in range(1000): 12 | result = die_1.roll() + die_2.roll() 13 | results.append(result) 14 | 15 | # Analyze the results. 16 | frequencies = [] 17 | max_result = die_1.num_sides + die_2.num_sides 18 | for value in range(2, max_result+1): 19 | frequency = results.count(value) 20 | frequencies.append(frequency) 21 | 22 | # Visualize the results. 23 | hist = pygal.Bar() 24 | hist.force_uri_protocol = 'http' 25 | 26 | hist.title = "Results of rolling two D6 dice 1000 times." 27 | hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] 28 | hist.x_title = "Result" 29 | hist.y_title = "Frequency of Result" 30 | 31 | hist.add('D6 + D6', frequencies) 32 | hist.render_to_file('dice_visual.svg') 33 | -------------------------------------------------------------------------------- /Chapter_15/pygal2_update/dice_visual.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Chapter_15/pygal2_update/die.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | class Die(): 4 | """A class representing a single die.""" 5 | 6 | def __init__(self, num_sides=6): 7 | """Assume a six-sided die.""" 8 | self.num_sides = num_sides 9 | 10 | def roll(self): 11 | """"Return a random value between 1 and number of sides.""" 12 | return randint(1, self.num_sides) 13 | -------------------------------------------------------------------------------- /Chapter_15/pygal2_update/die_visual.py: -------------------------------------------------------------------------------- 1 | import pygal 2 | 3 | from die import Die 4 | 5 | # Create a D6. 6 | die = Die() 7 | 8 | # Make some rolls, and store results in a list. 9 | results = [] 10 | for roll_num in range(1000): 11 | result = die.roll() 12 | results.append(result) 13 | 14 | # Analyze the results. 15 | frequencies = [] 16 | for value in range(1, die.num_sides+1): 17 | frequency = results.count(value) 18 | frequencies.append(frequency) 19 | 20 | # Visualize the results. 21 | hist = pygal.Bar() 22 | hist.force_uri_protocol = 'http' 23 | 24 | hist.title = "Results of rolling one D6 1000 times." 25 | hist.x_labels = ['1', '2', '3', '4', '5', '6'] 26 | hist.x_title = "Result" 27 | hist.y_title = "Frequency of Result" 28 | 29 | hist.add('D6', frequencies) 30 | hist.render_to_file('die_visual.svg') 31 | -------------------------------------------------------------------------------- /Chapter_15/pygal2_update/different_dice.py: -------------------------------------------------------------------------------- 1 | from die import Die 2 | 3 | import pygal 4 | 5 | # Create a D6 and a D10. 6 | die_1 = Die() 7 | die_2 = Die(10) 8 | 9 | # Make some rolls, and store results in a list. 10 | results = [] 11 | for roll_num in range(50000): 12 | result = die_1.roll() + die_2.roll() 13 | results.append(result) 14 | 15 | # Analyze the results. 16 | frequencies = [] 17 | max_result = die_1.num_sides + die_2.num_sides 18 | for value in range(2, max_result+1): 19 | frequency = results.count(value) 20 | frequencies.append(frequency) 21 | 22 | # Visualize the results. 23 | hist = pygal.Bar() 24 | hist.force_uri_protocol = 'http' 25 | 26 | hist.title = "Results of rolling a D6 and a D10 50,000 times." 27 | hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 28 | '13', '14', '15', '16'] 29 | hist.x_title = "Result" 30 | hist.y_title = "Frequency of Result" 31 | 32 | hist.add('D10 + D10', frequencies) 33 | hist.render_to_file('dice_visual.svg') 34 | -------------------------------------------------------------------------------- /Chapter_15/random_walk.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | class RandomWalk(): 4 | """A class to generate random walks.""" 5 | 6 | def __init__(self, num_points=5000): 7 | """Initialize attributes of a walk.""" 8 | self.num_points = num_points 9 | 10 | # All walks start at (0, 0). 11 | self.x_values = [0] 12 | self.y_values = [0] 13 | 14 | def fill_walk(self): 15 | """Calculate all the points in the walk.""" 16 | 17 | # Keep taking steps until the walk reaches the desired length. 18 | while len(self.x_values) < self.num_points: 19 | 20 | # Decide which direction to go, and how far to go in that direction. 21 | x_direction = choice([1, -1]) 22 | x_distance = choice([0, 1, 2, 3, 4]) 23 | x_step = x_direction * x_distance 24 | 25 | y_direction = choice([1, -1]) 26 | y_distance = choice([0, 1, 2, 3, 4]) 27 | y_step = y_direction * y_distance 28 | 29 | # Reject moves that go nowhere. 30 | if x_step == 0 and y_step == 0: 31 | continue 32 | 33 | # Calculate the next x and y values. 34 | next_x = self.x_values[-1] + x_step 35 | next_y = self.y_values[-1] + y_step 36 | 37 | self.x_values.append(next_x) 38 | self.y_values.append(next_y) 39 | 40 | -------------------------------------------------------------------------------- /Chapter_15/rw_visual.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | from random_walk import RandomWalk 4 | 5 | # Keep making new walks, as long as the program is active. 6 | while True: 7 | # Make a random walk, and plot the points. 8 | rw = RandomWalk(50000) 9 | rw.fill_walk() 10 | 11 | # Set the size of the plotting window. 12 | plt.figure(dpi=128, figsize=(10, 6)) 13 | 14 | point_numbers = list(range(rw.num_points)) 15 | plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, 16 | edgecolor='none', s=1) 17 | 18 | # Emphasize the first and last points. 19 | plt.scatter(0, 0, c='green', edgecolors='none', s=100) 20 | plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', 21 | s=100) 22 | 23 | # Remove the axes. 24 | plt.axes().get_xaxis().set_visible(False) 25 | plt.axes().get_yaxis().set_visible(False) 26 | 27 | plt.show() 28 | 29 | keep_running = input("Make another walk? (y/n): ") 30 | if keep_running == 'n': 31 | break 32 | -------------------------------------------------------------------------------- /Chapter_15/scatter_squares.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | 3 | x_values = list(range(1, 1001)) 4 | y_values = [x**2 for x in x_values] 5 | 6 | plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolor='none', s=40) 7 | 8 | # Set chart title, and label axes. 9 | plt.title("Square Numbers", fontsize=24) 10 | plt.xlabel("Value", fontsize=14) 11 | plt.ylabel("Square of Value", fontsize=14) 12 | 13 | # Set size of tick labels. 14 | plt.tick_params(axis='both', which='major', labelsize=14) 15 | 16 | # Set the range for each axis. 17 | plt.axis([0, 1100, 0, 1100000]) 18 | 19 | plt.show() 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonCrashCourse-Exercises 2 | 3 | This repository contains my personal solutions for exercises from the book "Python Crash Course". 4 | 5 | ## 🚀Usage 6 | 7 | Clone this repository to your local machine and navigate to the specific chapter directory to view the exercises and solutions. 8 | 9 | ```bash 10 | git clone https://github.com/KawaliAsh/PythonCrashCourse-Exercises.git 11 | ``` 12 | 13 | ## 🤝 Contributing 14 | 15 | Welcome contributions of any kind! If you find bugs, have suggestions for improvements, or have other ideas and comments, share them with us by submitting an `Issue` or `Pull Request`. --------------------------------------------------------------------------------