├── chapter10 ├── guest.txt ├── love_number.json ├── username.json ├── cats.txt ├── dogs.txt ├── numbers.json ├── programming_reasons.txt ├── pi_digits.txt ├── guest_book.txt ├── number_reader.py ├── learning_python.txt ├── programming.txt ├── number_writer.py ├── greet_user.py ├── alice.py ├── write_message.py ├── file_reader.py ├── division.py ├── test10.1.py ├── word_count.py ├── pi_string.py ├── test10.2.py ├── remember_me.py ├── test10.3.py └── test10.4.py ├── chapter01 └── hello_world.py ├── chapter02 ├── comment.py ├── simple_message.py ├── apostrophe.py ├── simple_messages.py ├── birthday.py ├── name_cases.py └── name.py ├── chapter08 ├── function.py ├── pizza.py ├── greet_users.py ├── greeter.py ├── person.py ├── test8.1.py ├── user_profile.py ├── test8.7.py ├── printing_functions.py ├── pets.py ├── making_pizzas.py ├── test8.2.py ├── test8.4.py ├── test8.3.py ├── test8.5.py ├── formatted_name.py └── printing_models.py ├── chapter04 ├── even_numbers.py ├── numbers.py ├── test4.5.py ├── foods.py ├── squares.py ├── players.py ├── magicians.py ├── test4.2.py ├── dimensions.py ├── test4.3.py └── test4.4.py ├── chapter05 ├── magic_number.py ├── cars.py ├── banned_users.py ├── voting.py ├── amusement_park.py ├── test5.2.py ├── test5.4.py ├── toppings.py └── test5.3.py ├── chapter07 ├── pets.py ├── rollercoaster.py ├── even_or_odd.py ├── cities.py ├── greeter.py ├── counting.py ├── confirmed_users.py ├── mountain_poll.py ├── test7.1.py ├── parrot.py ├── test7.3.py └── test7.2.py ├── README.md ├── chapter06 ├── user.py ├── pizza.py ├── many_users.py ├── aliens.py ├── test6.2.py ├── test6.3.py ├── alien.py ├── favorite_languages.py └── test6.4.py ├── chapter09 ├── my_electric_car.py ├── test9.4.py ├── my_car.py ├── admin.py ├── my_cars.py ├── test9.5.py ├── dog.py ├── restaurant.py ├── only_user.py ├── electric_car.py ├── user.py ├── test9.1.py ├── test9.2.py ├── car.py └── test9.3.py └── chapter03 ├── bicycles.py ├── test3.1.py ├── cars.py ├── test3.3.py ├── motorcycles.py └── test3.2.py /chapter10/guest.txt: -------------------------------------------------------------------------------- 1 | nash -------------------------------------------------------------------------------- /chapter10/love_number.json: -------------------------------------------------------------------------------- 1 | "10" -------------------------------------------------------------------------------- /chapter10/username.json: -------------------------------------------------------------------------------- 1 | "nash" -------------------------------------------------------------------------------- /chapter10/cats.txt: -------------------------------------------------------------------------------- 1 | james 2 | mike 3 | john -------------------------------------------------------------------------------- /chapter10/dogs.txt: -------------------------------------------------------------------------------- 1 | kobe 2 | tom 3 | rose -------------------------------------------------------------------------------- /chapter10/numbers.json: -------------------------------------------------------------------------------- 1 | [2, 3, 5, 7, 11, 13] -------------------------------------------------------------------------------- /chapter01/hello_world.py: -------------------------------------------------------------------------------- 1 | print("Hello Python world!") 2 | -------------------------------------------------------------------------------- /chapter02/comment.py: -------------------------------------------------------------------------------- 1 | #向大家问好 2 | print("Hello Python people!") -------------------------------------------------------------------------------- /chapter10/programming_reasons.txt: -------------------------------------------------------------------------------- 1 | interesting 2 | money 3 | -------------------------------------------------------------------------------- /chapter02/simple_message.py: -------------------------------------------------------------------------------- 1 | message = "Hello" 2 | print(message) 3 | -------------------------------------------------------------------------------- /chapter08/function.py: -------------------------------------------------------------------------------- 1 | def func(): 2 | print("This is function!") 3 | -------------------------------------------------------------------------------- /chapter10/pi_digits.txt: -------------------------------------------------------------------------------- 1 | 3.1415926535 2 | 8979323846 3 | 2643383279 -------------------------------------------------------------------------------- /chapter10/guest_book.txt: -------------------------------------------------------------------------------- 1 | star 2 | wtr 3 | nash 4 | ok 5 | nash 6 | wtr 7 | -------------------------------------------------------------------------------- /chapter04/even_numbers.py: -------------------------------------------------------------------------------- 1 | even_numbers = list(range(2, 11, 2)) 2 | print(even_numbers) -------------------------------------------------------------------------------- /chapter02/apostrophe.py: -------------------------------------------------------------------------------- 1 | message = "One of Python's strengths is its diverse community" 2 | print(message) 3 | -------------------------------------------------------------------------------- /chapter02/simple_messages.py: -------------------------------------------------------------------------------- 1 | message = "Hello" 2 | print(message) 3 | 4 | message = "Bye" 5 | print(message) 6 | -------------------------------------------------------------------------------- /chapter05/magic_number.py: -------------------------------------------------------------------------------- 1 | answer = 17 2 | 3 | if answer != 42: 4 | print("That is not the correct answer. Please try again!") -------------------------------------------------------------------------------- /chapter10/number_reader.py: -------------------------------------------------------------------------------- 1 | import json 2 | filename = 'numbers.json' 3 | with open(filename) as f_obj: 4 | numbers = json.load(f_obj) 5 | 6 | print(numbers) -------------------------------------------------------------------------------- /chapter10/learning_python.txt: -------------------------------------------------------------------------------- 1 | In Python you can write beautiful code. 2 | In Python you can open file. 3 | In Python you can use dictionary. 4 | In Python you can use list. -------------------------------------------------------------------------------- /chapter04/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) -------------------------------------------------------------------------------- /chapter07/pets.py: -------------------------------------------------------------------------------- 1 | pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] 2 | print(pets) 3 | 4 | while 'cat' in pets: 5 | pets.remove('cat') 6 | 7 | print(pets) -------------------------------------------------------------------------------- /chapter10/programming.txt: -------------------------------------------------------------------------------- 1 | I love programming. 2 | I love creating new games. 3 | I also love finding meaning in large datasets. 4 | I love creating apps that can run in a browser. 5 | -------------------------------------------------------------------------------- /chapter05/cars.py: -------------------------------------------------------------------------------- 1 | cars = ['audi', 'bmw', 'subaru', 'toyota'] 2 | 3 | for car in cars: 4 | if car == 'bmw': 5 | print(car.upper()) 6 | else: 7 | print(car.title()) -------------------------------------------------------------------------------- /chapter10/number_writer.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | numbers = [2, 3, 5, 7, 11, 13] 4 | 5 | filename = 'numbers.json' 6 | with open(filename, 'w') as f_obj: 7 | json.dump(numbers, f_obj) 8 | -------------------------------------------------------------------------------- /chapter05/banned_users.py: -------------------------------------------------------------------------------- 1 | banned_users = ['andrew', 'carolina', 'david'] 2 | user = 'marie' 3 | if user not in banned_users: 4 | print(user.title() + ", you can post a response if you wish.") -------------------------------------------------------------------------------- /chapter10/greet_user.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | filename = 'username.json' 4 | 5 | with open(filename) as f_obj: 6 | username = json.load(f_obj) 7 | print("Welcome back, " + username + "!") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Crash-Course 2 | 《Python编程从入门到实践》相关代码 3 | 4 | 通过对于这本书的学习,完成以下几个目标: 5 | * 熟悉Python语言 6 | * 掌握git、github的使用 7 | * 掌握markdown的相关语法 8 | 9 | 将使用PyCharm来编写书上的相关代码 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /chapter06/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) -------------------------------------------------------------------------------- /chapter09/my_electric_car.py: -------------------------------------------------------------------------------- 1 | from car import ElectricCar 2 | 3 | my_tesla = ElectricCar('tesla', 'model s', 2016) 4 | 5 | print(my_tesla.get_descriptive_name()) 6 | my_tesla.battery.describe_battery() 7 | my_tesla.battery.get_range() -------------------------------------------------------------------------------- /chapter07/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 | -------------------------------------------------------------------------------- /chapter04/test4.5.py: -------------------------------------------------------------------------------- 1 | #4-13 自助餐 2 | foods = ('fish', 'chicken', 'steak', 'mutton', 'cabbage') 3 | for food in foods: 4 | print(food) 5 | 6 | foods = ('fish', 'chicken', 'beef', 'mutton', 'carrot') 7 | for food in foods: 8 | print(food) 9 | 10 | -------------------------------------------------------------------------------- /chapter08/pizza.py: -------------------------------------------------------------------------------- 1 | # 结合使用位置实参和任意数量实参 2 | def make_pizza(size, *toppings): 3 | """概述要制作的比萨""" 4 | print("\nMaking a " + str(size) + 5 | "-inch pizza with the following toppings:") 6 | for topping in toppings: 7 | print("- " + topping) 8 | -------------------------------------------------------------------------------- /chapter08/greet_users.py: -------------------------------------------------------------------------------- 1 | def greet_users(names): 2 | """向列表中的每位用户都发出简单的问候""" 3 | for name in names: 4 | msg = "Hello, " + name.title() + "!" 5 | print(msg) 6 | 7 | 8 | usernames = ['hannah', 'ty', 'margot'] 9 | greet_users(usernames) 10 | -------------------------------------------------------------------------------- /chapter07/even_or_odd.py: -------------------------------------------------------------------------------- 1 | number = input("Enter a number, and I'll tell you if it's even or odd: ") 2 | number = int(number) 3 | 4 | if number % 2 == 0: 5 | print("\nThe number " + str(number)+ " is even.") 6 | else: 7 | print("\nThe number " + str(number) + " is odd.") 8 | -------------------------------------------------------------------------------- /chapter08/greeter.py: -------------------------------------------------------------------------------- 1 | # 定义函数 2 | def greet_user(): 3 | """显示简单的问候语""" 4 | print("Hello!") 5 | 6 | 7 | greet_user() 8 | 9 | 10 | # 向函数传递信息 11 | def greet_user(username): 12 | """显示简单的问候语""" 13 | print("Hello, " + username.title() + "!") 14 | 15 | 16 | greet_user('jesse') 17 | 18 | -------------------------------------------------------------------------------- /chapter06/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("\t" + topping) 11 | 12 | -------------------------------------------------------------------------------- /chapter04/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("\nMy friend's favorite foods are:") 11 | print(friend_foods) 12 | -------------------------------------------------------------------------------- /chapter07/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 | 7 | if city == 'quit': 8 | break 9 | else: 10 | print("I'd love to go to " + city.title() + "!") 11 | -------------------------------------------------------------------------------- /chapter07/greeter.py: -------------------------------------------------------------------------------- 1 | name = input("Please enter your name: ") 2 | print("Hello, " + name + "!") 3 | 4 | #提示信息存储在变量中 5 | prompt = "If you tell us who you are, we can personalize the messages you see." 6 | prompt += "\nWhat is your first name? " 7 | 8 | name = input(prompt) 9 | print("\nHello, " + name + "!") 10 | -------------------------------------------------------------------------------- /chapter08/person.py: -------------------------------------------------------------------------------- 1 | def build_person(first_name, last_name, age=''): 2 | """返回一个字典,其中包含有关一个人的信息""" 3 | person = {'first': first_name, 'last': last_name} 4 | if age: 5 | person['age'] = age 6 | return person 7 | 8 | 9 | musician = build_person('jimi', 'hendrix', age=27) 10 | print(musician) 11 | -------------------------------------------------------------------------------- /chapter07/counting.py: -------------------------------------------------------------------------------- 1 | current_number = 1 2 | while current_number <= 5: 3 | print(current_number) 4 | current_number += 1 5 | 6 | # 在循环中使用continue 7 | current_number = 0 8 | while current_number < 10: 9 | current_number += 1 10 | if current_number % 2 == 0: 11 | continue 12 | 13 | print(current_number) 14 | -------------------------------------------------------------------------------- /chapter04/squares.py: -------------------------------------------------------------------------------- 1 | squares = [] 2 | for value in range(1, 11): 3 | square = value ** 2 4 | squares.append(square) 5 | print(squares) 6 | 7 | squares = [] 8 | for value in range(1, 11): 9 | squares.append(value ** 2) 10 | print(squares) 11 | 12 | #列表解析 13 | squares = [value ** 2 for value in range(1, 11)] 14 | print(squares) -------------------------------------------------------------------------------- /chapter04/players.py: -------------------------------------------------------------------------------- 1 | players = ['charles', 'martina', 'michael', 'florence', 'eli'] 2 | print(players[0:3]) 3 | print(players[1:4]) 4 | print(players[:4]) 5 | print(players[2:]) 6 | print(players[-3:]) 7 | 8 | #遍历切片 9 | print("Here are the first three players on my team:") 10 | for player in players[:3]: 11 | print(player.title()) 12 | 13 | -------------------------------------------------------------------------------- /chapter02/birthday.py: -------------------------------------------------------------------------------- 1 | #整型和字符串进行拼接时需要转化为字符串类型 2 | age = 23 3 | message = "Happy " + str(age) + "rd Birthday!" 4 | print(message) 5 | 6 | #加减乘除输出数字8 7 | print(3 + 5) 8 | print(10 - 2) 9 | print(2 * 4) 10 | print(64 / 8) 11 | 12 | #打印最喜欢的数字 13 | favorite_number = 13 14 | message = "my favorite number is " + str(favorite_number) 15 | print(message) 16 | -------------------------------------------------------------------------------- /chapter04/magicians.py: -------------------------------------------------------------------------------- 1 | magicians = ['alice', 'david', 'carolina'] 2 | for magician in magicians: 3 | print(magician) 4 | 5 | for magician in magicians: 6 | print(magician.title() + ", that was a great trick!") 7 | print("I can't wait to see your next trick," + magician.title() + ".\n") 8 | 9 | print("Thank you, everyone. That was a great magic show!") 10 | -------------------------------------------------------------------------------- /chapter08/test8.1.py: -------------------------------------------------------------------------------- 1 | # 8-1 消息 2 | def display_message(): 3 | """打印本章学习内容""" 4 | print("I will learn using of the function in this section") 5 | 6 | 7 | display_message() 8 | 9 | 10 | # 8-2 喜欢的图书 11 | def favorite_book(title): 12 | """打印喜欢的图书""" 13 | print("One of my favorite books is " + title + ".") 14 | 15 | 16 | favorite_book("three kingdoms") 17 | -------------------------------------------------------------------------------- /chapter04/test4.2.py: -------------------------------------------------------------------------------- 1 | #4-1 比萨 2 | pizzas = ['beef pizza', 'fruit pizza', 'seafood pizza'] 3 | for pizza in pizzas: 4 | print("I like " + pizza) 5 | print("I really love pizza!") 6 | 7 | #4-2 动物 8 | animals = ['cat', 'pig', 'dog'] 9 | for animal in animals: 10 | print("A " + animal + " would make a great pet") 11 | print("Any of these animals would make a great pet!") 12 | -------------------------------------------------------------------------------- /chapter03/bicycles.py: -------------------------------------------------------------------------------- 1 | #列表 2 | bicycles = ['trek', 'cannondale', 'redline', 'specialized'] 3 | print(bicycles) 4 | 5 | #访问列表元素 6 | print(bicycles[0]) 7 | print(bicycles[0].title()) 8 | print(bicycles[1]) 9 | print(bicycles[3]) 10 | 11 | #索引值为-1时返回列表最后一个元素 12 | print(bicycles[-1]) 13 | 14 | #使用列表中的值 15 | message = "My first bicycle was a " + bicycles[0].title() + "." 16 | print(message) -------------------------------------------------------------------------------- /chapter04/dimensions.py: -------------------------------------------------------------------------------- 1 | #定义元祖 2 | dimensions = (200, 50) 3 | print(dimensions[0]) 4 | print(dimensions[1]) 5 | 6 | #遍历元祖中的所有值 7 | for dimension in dimensions: 8 | print(dimension) 9 | 10 | #修改元祖变量 11 | print("Original dimensions:") 12 | for dimension in dimensions: 13 | print(dimension) 14 | 15 | dimensions = (400, 100) 16 | print("\nModified dimensions:") 17 | for dimension in dimensions: 18 | print(dimension) -------------------------------------------------------------------------------- /chapter10/alice.py: -------------------------------------------------------------------------------- 1 | filename = 'alice.txt' 2 | 3 | try: 4 | with open(filename) as f_obj: 5 | contents = f_obj.read() 6 | except FileNotFoundError: 7 | msg = "Sorry, the file " + filename + "does not exist." 8 | print(msg) 9 | else: 10 | # 计算文件大致包含多少个单词 11 | words = contents.split() 12 | num_words = len(words) 13 | print("The file " + filename + " has about " + str(num_words) + " words.") -------------------------------------------------------------------------------- /chapter07/confirmed_users.py: -------------------------------------------------------------------------------- 1 | unconfirmed_users = ['alice', 'brian', 'candace'] 2 | confirmed_users = [] 3 | 4 | while unconfirmed_users: 5 | current_user = unconfirmed_users.pop() 6 | 7 | print("Verifying user: " + current_user.title()) 8 | confirmed_users.append(current_user) 9 | 10 | print("\nThe following users have been confirmed:") 11 | for confirmed_user in confirmed_users: 12 | print(confirmed_user.title()) 13 | -------------------------------------------------------------------------------- /chapter10/write_message.py: -------------------------------------------------------------------------------- 1 | filename = 'programming.txt' 2 | 3 | # with open(filename, 'w') as file_object: 4 | # file_object.write("I love programming.\n") 5 | # file_object.write("I love creating new games.\n") 6 | # 附加到文件 7 | with open(filename, 'a') as file_object: 8 | file_object.write("I also love finding meaning in large datasets.\n") 9 | file_object.write("I love creating apps that can run in a browser.\n") 10 | 11 | -------------------------------------------------------------------------------- /chapter05/voting.py: -------------------------------------------------------------------------------- 1 | #简单的if语句 2 | age = 19 3 | if age >= 18: 4 | print("You are old enough to vote!") 5 | print("Have you registered to vote yet?") 6 | 7 | #if-else语句 8 | age = 17 9 | if age >= 18: 10 | print("You are old enough to vote!") 11 | print("Have you registered to vote yet?") 12 | else: 13 | print("Sorry, you are too young to vote.") 14 | print("Please register to vote as soon as you turn 18!") 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /chapter03/test3.1.py: -------------------------------------------------------------------------------- 1 | #3-1 姓名 2 | names = ["star", "nash", "john"] 3 | print(names[0].title()) 4 | print(names[1].title()) 5 | print(names[2].title()) 6 | 7 | #3-2 问候语 8 | message = "hello my friend!" 9 | print(names[0].title() + ", " + message) 10 | print(names[1].title() + ", " + message) 11 | print(names[2].title() + ", " + message) 12 | 13 | #3-3 自己的列表 14 | vehicles = ['bus', 'subway', 'bicycle', 'car'] 15 | print("I would like to own a " + vehicles[2]) -------------------------------------------------------------------------------- /chapter10/file_reader.py: -------------------------------------------------------------------------------- 1 | with open('pi_digits.txt') as file_object: 2 | contents = file_object.read() 3 | print(contents) 4 | 5 | # 逐行读取 6 | filename = 'pi_digits.txt' 7 | 8 | with open(filename) as file_object: 9 | for line in file_object: 10 | print(line.rstrip()) 11 | 12 | # 将文件各行存储在一个列表中 13 | 14 | with open(filename) as file_object: 15 | lines = file_object.readlines() 16 | 17 | for line in lines: 18 | print(line.strip()) 19 | -------------------------------------------------------------------------------- /chapter09/test9.4.py: -------------------------------------------------------------------------------- 1 | # 9-10 导入Restaurant类 2 | import restaurant 3 | restaurant_0 = restaurant.Restaurant("kfc", 'junk food') 4 | restaurant_0.describe_restaurant() 5 | 6 | # 9-11 导入Admin类 7 | import user 8 | admin = user.Admin('Tian ran', 'Wang', [ 'read'], 'handsome') 9 | admin.show_privileges() 10 | 11 | # 9-12 多个模块 12 | from only_user import User 13 | from admin import Admin, Privileges 14 | admin = Admin("steve", "nash", ["read"], "handsome") 15 | admin.show_privileges() -------------------------------------------------------------------------------- /chapter08/user_profile.py: -------------------------------------------------------------------------------- 1 | def build_profile(first, last, **user_info): 2 | """创建一个字典,其中包含我们知道的有关用户的一切""" 3 | profile = {} 4 | profile['first_name'] = first 5 | profile['last_name'] = last 6 | for key, value in user_info.items(): 7 | profile[key] = value 8 | return profile 9 | 10 | 11 | user_profile = build_profile('albert', 'einstein', 12 | location='princeton', 13 | field='physics') 14 | print(user_profile) -------------------------------------------------------------------------------- /chapter10/division.py: -------------------------------------------------------------------------------- 1 | print("Give me two numbers, and I;ll divide them.") 2 | print("Enter 'q' to quit.") 3 | 4 | while True: 5 | first_number = input("\nFirst number: ") 6 | if first_number == 'q': 7 | break 8 | second_number = input("Second number: ") 9 | if second_number == 'q': 10 | break 11 | try: 12 | answer = int(first_number) / int(second_number) 13 | except ZeroDivisionError: 14 | print("You can't divide by 0!") 15 | else: 16 | print(answer) 17 | -------------------------------------------------------------------------------- /chapter10/test10.1.py: -------------------------------------------------------------------------------- 1 | # 10-1 Python 学习笔记 2 | filename = 'learning_python.txt' 3 | with open(filename) as file_object: 4 | print(file_object.read()) 5 | 6 | with open(filename) as file_object: 7 | for line in file_object: 8 | print(line) 9 | 10 | with open(filename) as file_object: 11 | lines = file_object.readlines() 12 | 13 | for line in lines: 14 | print(line.rstrip()) 15 | 16 | # 10-2 C语言学习笔记 17 | with open(filename) as file_object: 18 | for line in file_object: 19 | print(line.replace('Python', 'C')) 20 | -------------------------------------------------------------------------------- /chapter07/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 someday? ") 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 | -------------------------------------------------------------------------------- /chapter08/test8.7.py: -------------------------------------------------------------------------------- 1 | import printing_functions 2 | 3 | # 8-15 打印模型 4 | unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] 5 | completed_models = [] 6 | printing_functions.print_models(unprinted_designs, completed_models) 7 | printing_functions.show_completed_models(completed_models) 8 | 9 | # 8-16 导入 10 | # import function 11 | # function.func() 12 | 13 | # from function import func 14 | # func() 15 | 16 | # from function import func as f 17 | # f() 18 | 19 | # import function as f 20 | # f.func() 21 | 22 | # from function import * 23 | # func() 24 | 25 | -------------------------------------------------------------------------------- /chapter07/test7.1.py: -------------------------------------------------------------------------------- 1 | # 7-1 汽车租赁 2 | car = input("What kind of car do you want to rent?") 3 | print("Let mee see if i can find you a " + car) 4 | 5 | # 7-2 餐馆订位 6 | number = input("How many people have dinner there?") 7 | number = int(number) 8 | if number > 8: 9 | print("There is no empty table") 10 | else: 11 | print("There is an empty table for you") 12 | 13 | # 7-3 10的整数倍 14 | number = input("Please input a number: ") 15 | number = int(number) 16 | if number % 10 == 0: 17 | print("It's a multiple of 10") 18 | else: 19 | print("It is not a multiple of 10") 20 | 21 | 22 | -------------------------------------------------------------------------------- /chapter07/parrot.py: -------------------------------------------------------------------------------- 1 | message = input("Tell me something, and I will repeat it back tou you: ") 2 | print(message) 3 | 4 | # 让用户选择何时退出 5 | prompt = "\nTell me something, and I will repeat it back tou you:" 6 | prompt += "\nEnter 'quit' to end the program" 7 | message = "" 8 | while message != 'quit': 9 | message = input(prompt) 10 | 11 | if message != 'quit': 12 | print(message) 13 | 14 | # 使用标志 15 | active = True 16 | while active: 17 | message = input(prompt) 18 | 19 | if message == 'quit': 20 | active = False 21 | else: 22 | print(message) 23 | 24 | -------------------------------------------------------------------------------- /chapter06/many_users.py: -------------------------------------------------------------------------------- 1 | users = { 2 | 'aeinstein': { 3 | 'first': 'albert', 4 | 'last': 'einstein', 5 | 'location': 'princeton', 6 | }, 7 | 8 | 'mcurie': { 9 | 'first': 'marie', 10 | 'last': 'curie', 11 | 'location': 'paris', 12 | }, 13 | } 14 | 15 | for username, user_info in users.items(): 16 | print("\nUsername: " + username) 17 | full_name = user_info['first'] + " " + user_info['last'] 18 | location = user_info['location'] 19 | 20 | print("\tFull name: " + full_name.title()) 21 | print("\tLocation: " + location.title()) -------------------------------------------------------------------------------- /chapter08/printing_functions.py: -------------------------------------------------------------------------------- 1 | def print_models(unprinted_designs, completed_models): 2 | """ 3 | 模拟打印每个设计,直到没有未打印的设计为止 4 | 打印每个设计后,都将其移到列表completed_models中 5 | """ 6 | while unprinted_designs: 7 | current_design = unprinted_designs.pop() 8 | 9 | print("Printing model: " + current_design) 10 | completed_models.append(current_design) 11 | 12 | 13 | def show_completed_models(completed_models): 14 | """显示打印好的所有模型""" 15 | print("\nThe following models have been printed:") 16 | for completed_model in completed_models: 17 | print(completed_model) 18 | -------------------------------------------------------------------------------- /chapter09/my_car.py: -------------------------------------------------------------------------------- 1 | from car import Car 2 | 3 | my_new_car = Car('audi', 'a4', 2016) 4 | print(my_new_car.get_descriptive_name()) 5 | my_new_car.read_odometer() 6 | 7 | # 直接修改属性的值 8 | my_new_car.odometer_reading = 23 9 | my_new_car.read_odometer() 10 | 11 | 12 | # 通过方法修改属性的值 13 | my_new_car.update_odometer(18) 14 | my_new_car.read_odometer() 15 | 16 | # 通过方法对属性的值进行递增 17 | my_used_car = Car('subaru', 'outback', 2013) 18 | print(my_used_car.get_descriptive_name()) 19 | 20 | my_used_car.update_odometer(23500) 21 | my_used_car.read_odometer() 22 | 23 | my_used_car.increment_odometer(100) 24 | my_used_car.read_odometer() 25 | 26 | -------------------------------------------------------------------------------- /chapter03/cars.py: -------------------------------------------------------------------------------- 1 | #使用方法sort()对列表进行永久性排序 2 | cars = ['bmw', 'audi', 'toyota', 'subaru'] 3 | cars.sort() 4 | print(cars) 5 | 6 | cars.sort(reverse=True) 7 | print(cars) 8 | 9 | #使用函数sorted()对列表进行临时排序 10 | cars = ['bmw', 'audi', 'toyota', 'subaru'] 11 | 12 | print("Here is the original list:") 13 | print(cars) 14 | 15 | print("\nHere is the sorted list:") 16 | print(sorted(cars)) 17 | 18 | print("\nHere is the original list again:") 19 | print(cars) 20 | 21 | #倒着打印列表 22 | cars = ['bmw', 'audi', 'toyota', 'subaru'] 23 | print(cars) 24 | 25 | cars.reverse() 26 | print(cars) 27 | 28 | #确定列表的长度 29 | cars = ['bmw', 'audi', 'toyota', 'subaru'] 30 | print(len(cars)) 31 | 32 | -------------------------------------------------------------------------------- /chapter09/admin.py: -------------------------------------------------------------------------------- 1 | from only_user import User 2 | 3 | 4 | class Admin(User): 5 | """管理员""" 6 | def __init__(self, first_name, last_name, privileges, *profile): 7 | """初始化""" 8 | super().__init__(first_name, last_name, profile) 9 | self.privileges = Privileges(privileges) 10 | 11 | def show_privileges(self): 12 | """显示管理员权限""" 13 | self.privileges.show_privileges() 14 | 15 | 16 | # 9-8 权限 17 | class Privileges: 18 | def __init__(self, privileges): 19 | self.privileges = privileges 20 | 21 | def show_privileges(self): 22 | """显示管理员权限""" 23 | for privilege in self.privileges: 24 | print(privilege) -------------------------------------------------------------------------------- /chapter10/word_count.py: -------------------------------------------------------------------------------- 1 | def count_words(filename): 2 | """计算一个文件大致包含多少个单词""" 3 | try: 4 | with open(filename) as f_obj: 5 | contents = f_obj.read() 6 | except FileNotFoundError: 7 | # msg = "Sorry, the file " + filename + " does not exist." 8 | # print(msg) 9 | pass 10 | else: 11 | # 计算文件大致包含多少个单词 12 | words = contents.split() 13 | num_words = len(words) 14 | print("The file " + filename + " has about " + str(num_words) + 15 | "words.") 16 | 17 | 18 | filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] 19 | for filename in filenames: 20 | count_words(filename) 21 | -------------------------------------------------------------------------------- /chapter10/pi_string.py: -------------------------------------------------------------------------------- 1 | filename = 'pi_digits.txt' 2 | with open(filename) as file_object: 3 | lines = file_object.readlines() 4 | 5 | pi_string = '' 6 | for line in lines: 7 | pi_string += line.strip() 8 | 9 | print(pi_string) 10 | print(len(pi_string)) 11 | 12 | # 一百万位的大型文件 13 | filename = 'pi_million_digits.txt' 14 | 15 | with open(filename) as file_object: 16 | lines = file_object.readlines() 17 | 18 | pi_string = '' 19 | for line in lines: 20 | pi_string += line.strip() 21 | 22 | birthday = input("Enter your birthday, in the form mmddyy: ") 23 | if birthday in pi_string: 24 | print("Your birthday appears in the first million digits of pi!") 25 | else: 26 | print("Your birthday does not appear in the first million digits of pi.") 27 | -------------------------------------------------------------------------------- /chapter08/pets.py: -------------------------------------------------------------------------------- 1 | def describe_pet(animal_type, pet_name): 2 | """显示宠物的信息""" 3 | print("\nI have a " + animal_type + ".") 4 | print("My " + animal_type + "'s name is " + pet_name.title() + ".") 5 | 6 | 7 | describe_pet('hamster', 'harry') 8 | describe_pet('dog', 'willie') 9 | # 关键字实参 10 | describe_pet(animal_type='hamster', pet_name='harry') 11 | describe_pet(pet_name='harry', animal_type='hamster') 12 | 13 | 14 | #默认值 15 | def describe_pet(pet_name, animal_type='dog'): 16 | """显示宠物的信息""" 17 | print("\nI have a " + animal_type + ".") 18 | print("My " + animal_type + "'s name is " + pet_name.title() + ".") 19 | 20 | 21 | describe_pet(pet_name='willie') 22 | describe_pet('willie') 23 | describe_pet(pet_name='harry', animal_type='hamster') 24 | -------------------------------------------------------------------------------- /chapter04/test4.3.py: -------------------------------------------------------------------------------- 1 | #4-3 数到20 2 | for number in range(1, 21): 3 | print(number) 4 | 5 | #4-4 一百万 6 | #numbers = list(range(1, 1000001)) 7 | #for number in numbers: 8 | # print(number) 9 | 10 | #4-5 计算 1~1000000的总和 11 | numbers = list(range(1, 1000001)) 12 | print(min(numbers)) 13 | print(max(numbers)) 14 | print(sum(numbers)) 15 | 16 | #4-6 奇数 17 | odds_number = list(range(1, 21, 2)) 18 | for number in odds_number: 19 | print(number) 20 | 21 | #4-7 3的倍数 22 | numbers = list(range(3, 31, 3)) 23 | for number in numbers: 24 | print(number) 25 | 26 | #4-8 立方 27 | numbers = [] 28 | for number in range(1, 11): 29 | numbers.append(number ** 3) 30 | print(numbers) 31 | 32 | #4-9 立方解析 33 | numbers = [value ** 3 for value in range(1, 11)] 34 | print(numbers) 35 | -------------------------------------------------------------------------------- /chapter02/name_cases.py: -------------------------------------------------------------------------------- 1 | name = "star" 2 | print("Hello " + name + ", would you like to learn some Python today?") 3 | print("Hello " + name.lower() + ", would you like to learn some Python today?") 4 | print("Hello " + name.upper() + ", would you like to learn some Python today?") 5 | print("Hello " + name.title() + ", would you like to learn some Python today?") 6 | 7 | print('Albert Einstein once said,"A person who never made a mistake never tried anything new."') 8 | famous_person = "Albert Einstein" 9 | message = famous_person + ' once said,"A person who never made a mistake never tried anything new."' 10 | print(message) 11 | 12 | people_name = "\t\nnash\n\t " 13 | print(people_name) 14 | print(people_name.lstrip()) 15 | print(people_name.rstrip()) 16 | print(people_name.strip()) -------------------------------------------------------------------------------- /chapter08/making_pizzas.py: -------------------------------------------------------------------------------- 1 | # 导入整个模块 2 | # import pizza 3 | 4 | # pizza.make_pizza(16, 'pepperoni') 5 | # pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') 6 | 7 | # 导入特定的函数 8 | # from pizza import make_pizza 9 | # make_pizza(16, 'pepperoni') 10 | # make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') 11 | 12 | # 使用as给函数指定别名 13 | # from pizza import make_pizza as mp 14 | # mp(16, 'pepperoni') 15 | # mp(12, 'mushrooms', 'green peppers', 'extra cheese') 16 | 17 | # 使用as给模块指定别名 18 | # import pizza as p 19 | 20 | # p.make_pizza(16, 'pepperoni') 21 | # p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') 22 | 23 | # 导入模块中的所有函数 24 | from pizza import * 25 | make_pizza(16, 'pepperoni') 26 | make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') 27 | -------------------------------------------------------------------------------- /chapter03/test3.3.py: -------------------------------------------------------------------------------- 1 | #3-8放眼世界 2 | places = ['hangzhou', 'yunnan', 'new york', 'phoenix', 'the golden states'] 3 | print(places) 4 | print(sorted(places)) 5 | print(places) 6 | print(sorted(places, reverse=True)) 7 | print(places) 8 | places.reverse() 9 | print(places) 10 | places.reverse() 11 | print(places) 12 | places.sort() 13 | print(places) 14 | places.sort(reverse=True) 15 | print(places) 16 | 17 | #3-9晚餐嘉宾 18 | people = ['john', 'mike', 'sarah', 'nash', 'kobe'] 19 | print(len(people)) 20 | 21 | #3-10尝试使用各个函数 22 | languages = ['python', 'java', 'c++'] 23 | print(languages) 24 | print(len(languages)) 25 | print(sorted(languages)) 26 | print(languages) 27 | print(sorted(languages, reverse=True)) 28 | languages.reverse() 29 | print(languages) 30 | languages.sort() 31 | print(languages) 32 | 33 | -------------------------------------------------------------------------------- /chapter02/name.py: -------------------------------------------------------------------------------- 1 | #字符串改变大小写 2 | name = "ada lovelace" 3 | print(name.title()) 4 | print(name.upper()) 5 | print(name.lower()) 6 | 7 | #字符串拼接 8 | first_name = "ada" 9 | last_name = "lovelace" 10 | full_name = first_name + " " + last_name 11 | message = "Hello, " + full_name.title() + "!" 12 | print(message) 13 | 14 | #制表符、换行符的使用 15 | print("Python") 16 | print("\tPython") 17 | print("Languages:\n\tPython\n\tC\n\tJavaScript") 18 | 19 | #删除空白 20 | favorite_language = 'python ' 21 | print(favorite_language) 22 | print(favorite_language.rstrip()) 23 | print(favorite_language) 24 | 25 | favorite_language = favorite_language.rstrip() 26 | print(favorite_language) 27 | 28 | favorite_language = ' python ' 29 | print(favorite_language.rstrip()) 30 | print(favorite_language.lstrip()) 31 | print(favorite_language.strip()) -------------------------------------------------------------------------------- /chapter10/test10.2.py: -------------------------------------------------------------------------------- 1 | # 10-3 访客 2 | filename = 'guest.txt' 3 | name = input("Please input your name:") 4 | with open(filename, 'w') as file_object: 5 | file_object.write(name) 6 | 7 | # 10-4 访客名单 8 | filename = 'guest_book.txt' 9 | while True: 10 | name = input("Please input your name(you can enter 'q' to quit):") 11 | if name == 'q': 12 | break 13 | print("Hello, " + name + " !") 14 | with open(filename, 'a') as file_object: 15 | file_object.write(name + '\n') 16 | 17 | # 10-5 关于编程的调查 18 | filename = 'programming_reasons.txt' 19 | while True: 20 | reason = input("Please input why you love programming(you can enter 'q' to quit):") 21 | if reason == 'q': 22 | break 23 | with open(filename, 'a') as file_object: 24 | file_object.write(reason + '\n') 25 | -------------------------------------------------------------------------------- /chapter09/my_cars.py: -------------------------------------------------------------------------------- 1 | # 从一个模块中导入多个类 2 | # from car import Car, ElectricCar 3 | 4 | # my_beetle = Car('volkswagen', 'beetle', 2016) 5 | # print(my_beetle.get_descriptive_name()) 6 | 7 | # my_tesla = ElectricCar('tesla', 'roadster', 2016) 8 | # print(my_tesla.get_descriptive_name()) 9 | 10 | # 导入整个模块 11 | # import car 12 | 13 | # my_beetle = car.Car('volkswagen', 'beetle', 2016) 14 | # print(my_beetle.get_descriptive_name()) 15 | 16 | # my_tesla = car.ElectricCar('tesla', 'roadster', 2016) 17 | # print(my_tesla.get_descriptive_name()) 18 | 19 | # 分别从每个模块导入类 20 | from car import Car 21 | from electric_car import ElectricCar 22 | my_beetle = Car('volkswagen', 'beetle', 2016) 23 | print(my_beetle.get_descriptive_name()) 24 | 25 | my_tesla = ElectricCar('tesla', 'roadster', 2016) 26 | print(my_tesla.get_descriptive_name()) -------------------------------------------------------------------------------- /chapter09/test9.5.py: -------------------------------------------------------------------------------- 1 | # 9-13 使用OrderedDict 2 | from collections import OrderedDict 3 | vocabulary = OrderedDict() 4 | 5 | vocabulary['stack'] = 'LIFO' 6 | vocabulary['queue'] = 'FIFO' 7 | vocabulary['http'] = '应用层协议' 8 | vocabulary['cpu'] = '中央处理器' 9 | vocabulary['pop'] = '弹出' 10 | 11 | for key, value in vocabulary.items(): 12 | print(key + ": " + value) 13 | 14 | # 9-14 骰子 15 | from random import randint 16 | 17 | 18 | class Die: 19 | def __init__(self, sides=6): 20 | self.sides = sides 21 | 22 | def roll_die(self): 23 | print(randint(1,self.sides)) 24 | 25 | 26 | die_0 = Die() 27 | for i in range(10): 28 | die_0.roll_die() 29 | 30 | die_1 = Die(10) 31 | for i in range(10): 32 | die_1.roll_die() 33 | 34 | die_2 = Die(20) 35 | for i in range(20): 36 | die_2.roll_die() 37 | -------------------------------------------------------------------------------- /chapter08/test8.2.py: -------------------------------------------------------------------------------- 1 | # 8-3 T恤 2 | def make_shirt(size, words): 3 | """打印T恤尺码和字样""" 4 | print("The size of T-shirt is " + size + ".") 5 | print("There are words on T-shirt: " + words) 6 | 7 | 8 | make_shirt('XL', 'Go Warriors!') 9 | 10 | 11 | # 8-4 大号T恤 12 | def make_shirt(size='L', words='I love Python'): 13 | """打印T恤尺码和字样""" 14 | print("The size of T-shirt is " + size + ".") 15 | print("There are words on T-shirt: " + words) 16 | 17 | 18 | make_shirt() 19 | make_shirt('M') 20 | make_shirt('XL', 'Go Warriors!') 21 | 22 | 23 | # 8-5 城市 24 | def describe_city(city, country='China'): 25 | """打印城市及所属国家""" 26 | print(city + " is in " + country + ".") 27 | 28 | 29 | describe_city('Hangzhou') 30 | describe_city('Wuhan') 31 | describe_city('New York','America') 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /chapter09/dog.py: -------------------------------------------------------------------------------- 1 | class Dog(): 2 | """一次模拟小狗的简单尝试""" 3 | 4 | def __init__(self, name, age): 5 | """初始化属性name和age""" 6 | self.name = name 7 | self.age = age 8 | 9 | def sit(self): 10 | """模拟小狗被命令时蹲下""" 11 | print(self.name.title() + " is now sitting.") 12 | 13 | def roll_over(self): 14 | """模拟小狗被命令时打滚""" 15 | print(self.name.title() + " rolled over!") 16 | 17 | 18 | my_dog = Dog('willie', 6) 19 | your_dog = Dog('lucy', 3) 20 | 21 | print("My dog's name is " + my_dog.name.title() + ".") 22 | print("My dog is " + str(my_dog.age) + " years old") 23 | my_dog.sit() 24 | my_dog.roll_over() 25 | 26 | print("\nYour dog's name is " + your_dog.name.title() + ".") 27 | print("Your dog is " + str(your_dog.age) + " years old") 28 | your_dog.sit() 29 | your_dog.roll_over() -------------------------------------------------------------------------------- /chapter09/restaurant.py: -------------------------------------------------------------------------------- 1 | class Restaurant: 2 | """模拟餐馆""" 3 | def __init__(self, restaurant_name, cuisine_type): 4 | """初始化餐馆名和菜肴类型""" 5 | self.restaurant_name = restaurant_name 6 | self.cuisine_type = cuisine_type 7 | self.number_served = 0 8 | 9 | def describe_restaurant(self): 10 | """打印餐馆信息""" 11 | print("restaurant name: " + self.restaurant_name) 12 | print("cuisine_type: " + self.cuisine_type) 13 | 14 | def open_restaurant(self): 15 | """表示餐厅正在营业""" 16 | print("restaurant is open!") 17 | 18 | def set_number_served(self, number_served): 19 | """设置就餐人数""" 20 | self.number_served = number_served 21 | 22 | def increment_number_served(self, increment): 23 | """增加就餐人数""" 24 | self.number_served += increment -------------------------------------------------------------------------------- /chapter05/amusement_park.py: -------------------------------------------------------------------------------- 1 | age = 12 2 | 3 | if age < 4: 4 | print("Your admission cost is $0.") 5 | elif age < 18: 6 | print("Your admission cost is $5.") 7 | else: 8 | print("Your admission cost is $10.") 9 | 10 | #更简洁的形式 11 | if age < 4: 12 | price = 0 13 | elif age < 18: 14 | price = 5 15 | else: 16 | price = 10 17 | 18 | print("Your admission cost is $" + str(price) + ".") 19 | 20 | #使用多个elif代码块 21 | if age < 4: 22 | price = 0 23 | elif age < 18: 24 | price = 5 25 | elif age < 65: 26 | price = 10 27 | else: 28 | price = 5 29 | print("Your admission cost is $" + str(price) + ".") 30 | 31 | #省略else代码块 32 | if age < 4: 33 | price = 0 34 | elif age < 18: 35 | price = 5 36 | elif age < 65: 37 | price = 10 38 | elif age >= 65: 39 | price = 5 40 | print("Your admission cost is $" + str(price) + ".") 41 | -------------------------------------------------------------------------------- /chapter06/aliens.py: -------------------------------------------------------------------------------- 1 | alien_0 = {'color': 'green', 'points': 5} 2 | alien_1 = {'color': 'yellow', 'points': 10} 3 | alien_2 = {'color': 'red', 'points': 15} 4 | 5 | aliens = [alien_0, alien_1, alien_2] 6 | 7 | for alien in aliens: 8 | print(alien) 9 | 10 | aliens = [] 11 | 12 | for alien_number in range(30): 13 | new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} 14 | aliens.append(new_alien) 15 | 16 | for alien in aliens[0:3]: 17 | if alien['color'] == 'green': 18 | alien['color'] = 'yellow' 19 | alien['speed'] = 'medium' 20 | alien['points'] = 10 21 | elif alien['color'] == 'yellow': 22 | alien['color'] = 'red' 23 | alien['speed'] = 'fast' 24 | alien['points'] = 15 25 | 26 | for alien in aliens[:5]: 27 | print(alien) 28 | print("...") 29 | 30 | print("Total number of aliens: " + str(len(aliens))) 31 | 32 | -------------------------------------------------------------------------------- /chapter10/remember_me.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | 4 | def get_stored_username(): 5 | """如果存储了用户名,就获取它""" 6 | filename = 'username.json' 7 | try: 8 | with open(filename) as f_obj: 9 | username = json.load(f_obj) 10 | except FileNotFoundError: 11 | return None 12 | else: 13 | return username 14 | 15 | 16 | def get_new_username(): 17 | """提示用户输入用户名""" 18 | username = input("What is your name?") 19 | filename = 'username.json' 20 | with open(filename, 'w') as f_obj: 21 | json.dump(username, f_obj) 22 | return username 23 | 24 | 25 | def greet_user(): 26 | """问候用户, 并指出其名字""" 27 | username = get_stored_username() 28 | if username: 29 | print("Welcome back, " + username + "!") 30 | else: 31 | username = get_new_username() 32 | print("We'll remember you when you come back, " + username + "!") 33 | 34 | 35 | greet_user() 36 | -------------------------------------------------------------------------------- /chapter08/test8.4.py: -------------------------------------------------------------------------------- 1 | # 8-9 魔术师 2 | def show_magicians(magicians): 3 | """打印魔术师的名字""" 4 | for magician in magicians: 5 | print(magician) 6 | 7 | 8 | magicians = ['wtr', 'star', 'nash'] 9 | show_magicians(magicians) 10 | 11 | 12 | # 8-10 了不起的魔术师 13 | def make_great(magicians): 14 | """在每个魔术师名字前加上'the Great'""" 15 | count = 0 16 | while count < len(magicians): 17 | magicians[count] = "the Great " + magicians[count] 18 | count += 1 19 | 20 | 21 | make_great(magicians) 22 | show_magicians(magicians) 23 | 24 | 25 | # 8-11 不变的魔术师 26 | def make_great(magicians): 27 | """在每个魔术师名字前加上'the Great'返回一个新的列表""" 28 | count = 0 29 | while count < len(magicians): 30 | magicians[count] = "the Great " + magicians[count] 31 | count += 1 32 | 33 | return magicians 34 | 35 | 36 | magicians = ['wtr', 'star', 'nash'] 37 | new_magicians = make_great(magicians[:]) 38 | show_magicians(magicians) 39 | show_magicians(new_magicians) 40 | 41 | -------------------------------------------------------------------------------- /chapter06/test6.2.py: -------------------------------------------------------------------------------- 1 | #6-1 人 2 | person = {'first_name': 'steve', 'last_name': 'nash', 'age': 43, 'city': 'the golden states'} 3 | print(person) 4 | print(person['first_name']) 5 | print(person['last_name']) 6 | print(person['age']) 7 | print(person['city']) 8 | 9 | #6-2 喜欢的数字 10 | number = { 11 | 'star': 4, 12 | 'nash': 13, 13 | 'mike': 1, 14 | 'kobe': 24, 15 | 'james': 23, 16 | } 17 | 18 | print("star loves " + str(number['star'])) 19 | print("nash loves " + str(number['nash'])) 20 | print("mike loves " + str(number['mike'])) 21 | print("kobe loves " + str(number['kobe'])) 22 | print("james loves " + str(number['star'])) 23 | 24 | #6-3 词汇表 25 | vocabulary = { 26 | 'stack': 'LIFO', 27 | 'queue': 'FIFO', 28 | 'http': '应用层协议', 29 | 'cpu': '中央处理器', 30 | 'pop': '弹出', 31 | } 32 | 33 | print("stack:" + vocabulary['stack']) 34 | print("queue:" + vocabulary['queue']) 35 | print("http:" + vocabulary['http']) 36 | print("cpu:" + vocabulary['cpu']) 37 | print("pop:" + vocabulary['pop']) -------------------------------------------------------------------------------- /chapter05/test5.2.py: -------------------------------------------------------------------------------- 1 | #5-1 条件测试 2 | person = 'nash' 3 | print("Is person == 'nash'? I predict True.") 4 | print(person == 'nash') 5 | 6 | print("\nIs person == 'curry'? I predict False") 7 | print(person == 'curry') 8 | 9 | print("\nIs person != 'curry'? I predict True") 10 | print(person != 'curry') 11 | 12 | print("\nIs person == 'Nash'? I predict False") 13 | print(person == 'Nash') 14 | 15 | print("\nIs person.title() == 'Nash'? I predict True") 16 | print(person.title() == 'Nash') 17 | 18 | #5-2 更多的条件测试 19 | str1 = 'abc' 20 | print(str1 == 'abc') 21 | print(str1 == 'cba') 22 | 23 | str2 = 'AbC' 24 | print(str2 == 'abc') 25 | print(str2.lower() == 'abc') 26 | 27 | num1 = 8 28 | num2 = 12 29 | print(num1 == num2) 30 | print(num1 != num2) 31 | print(num1 > num2) 32 | print(num1 < num2) 33 | print(num1 >= num2) 34 | print(num1 <= num2) 35 | print(str1 == 'abc' and num1 < num2) 36 | print(str1 == 'cba' or num1 <= num2) 37 | 38 | persons = ['mike', 'john'] 39 | print('sarah' in persons) 40 | print('sarah' not in persons) -------------------------------------------------------------------------------- /chapter08/test8.3.py: -------------------------------------------------------------------------------- 1 | # 8-6 城市名 2 | def city_country(city, country): 3 | """返回城市和属于的国家""" 4 | return city + ", " + country 5 | 6 | 7 | print(city_country('Hangzhou', 'China')) 8 | print(city_country('Phoenix', 'America')) 9 | print(city_country('Wuhan', 'China')) 10 | 11 | 12 | # 8-7 专辑 13 | def make_album(singer, name, count=''): 14 | """创建描述音乐专辑的字典""" 15 | if count: 16 | album = {'singer': singer, 'name': name, 'count': count} 17 | else: 18 | album = {'singer': singer, 'name': name} 19 | return album 20 | 21 | 22 | album_0 = make_album("孙燕姿", "逆光") 23 | album_1 = make_album("孙燕姿", "是时候") 24 | album_2 = make_album("张杰", "我想", 10) 25 | print(album_0) 26 | print(album_1) 27 | print(album_2) 28 | 29 | 30 | # 8-8 用户的专辑 31 | while True: 32 | print("请输入一个专辑的歌手和名称,你可以随时输入'q'来退出") 33 | 34 | singer = input("请输入歌手:") 35 | if singer == 'q': 36 | break 37 | 38 | name = input("请输入名称:") 39 | if name == 'q': 40 | break 41 | 42 | album = make_album(singer, name) 43 | print(album) 44 | 45 | 46 | -------------------------------------------------------------------------------- /chapter04/test4.4.py: -------------------------------------------------------------------------------- 1 | #4-10 切片 2 | my_foods = ['pizza', 'falafel', 'carrot cake', 'ice cream', 'chicken'] 3 | print("The first three items in the list are:") 4 | print(my_foods[:3]) 5 | print("Three items from the middle of the list are:") 6 | print(my_foods[1:4]) 7 | print("The last three items in the list are:") 8 | print(my_foods[-3:]) 9 | 10 | #4-11 你的比萨和我的比萨 11 | pizzas = ['beef pizza', 'fruit pizza', 'seafood pizza'] 12 | friend_pizzas = pizzas[:] 13 | pizzas.append('chicken pizza') 14 | friend_pizzas.append('mutton pizza') 15 | print("My favorite pizzas are:") 16 | for pizza in pizzas: 17 | print(pizza) 18 | 19 | print("My friend's favorite pizzas are:") 20 | for pizza in friend_pizzas: 21 | print(pizza) 22 | 23 | #4-12 使用多个循环 24 | my_foods = ['pizza', 'falafel', 'carrot cake'] 25 | friend_foods = my_foods[:] 26 | 27 | my_foods.append('cannoli') 28 | friend_foods.append('ice cream') 29 | 30 | print("My favorite foods are:") 31 | for food in my_foods: 32 | print(food) 33 | 34 | print("\nMy friend's favorite foods are:") 35 | for food in friend_foods: 36 | print(food) -------------------------------------------------------------------------------- /chapter06/test6.3.py: -------------------------------------------------------------------------------- 1 | #6-4 词汇表2 2 | vocabulary = { 3 | 'stack': 'LIFO', 4 | 'queue': 'FIFO', 5 | 'http': '应用层协议', 6 | 'cpu': '中央处理器', 7 | 'pop': '弹出', 8 | 'for': 'for循环', 9 | 'if': '条件语句', 10 | 'list': '列表', 11 | 'dict': '字典', 12 | 'tuple': '元祖', 13 | } 14 | 15 | for key, value in vocabulary.items(): 16 | print(key + ": " + value) 17 | 18 | #6-5 河流 19 | rivers = { 20 | 'nile': 'egypt', 21 | 'huang river': 'china', 22 | 'hen river': 'indian', 23 | } 24 | for key, value in rivers.items(): 25 | print("The " + key + " runs through " + value + ".") 26 | 27 | for key in rivers.keys(): 28 | print(key) 29 | 30 | for value in rivers.values(): 31 | print(value) 32 | 33 | #6-6 调查 34 | favorite_languages = { 35 | 'jen': 'python', 36 | 'sarah': 'c', 37 | 'edward': 'ruby', 38 | 'phil': 'python', 39 | } 40 | 41 | people = ['jen', 'nash', 'curry', 'edward'] 42 | for person in people: 43 | if person in favorite_languages.keys(): 44 | print("Thank you for taking the poll, " + person) 45 | else: 46 | print("Please take the poll, " + person) 47 | -------------------------------------------------------------------------------- /chapter07/test7.3.py: -------------------------------------------------------------------------------- 1 | # 7-8 熟食店 2 | sandwich_orders = ['beef sandwich', 'seafood sandwich', 'fruit sandwich'] 3 | finished_sandwiches = [] 4 | while sandwich_orders: 5 | sandwich = sandwich_orders.pop() 6 | print("I made your " + sandwich) 7 | finished_sandwiches.append(sandwich) 8 | 9 | print("All of sandwiches have been finished:") 10 | for sandwich in finished_sandwiches: 11 | print(sandwich) 12 | 13 | # 7-9 五香烟熏牛肉卖完了 14 | sandwich_orders = ['beef', 'pastrami', 'seafood', 'pastrami', 'fruit', 'pastrami', 'pastrami'] 15 | print("pastrami have been sold out!") 16 | while 'pastrami' in sandwich_orders: 17 | sandwich_orders.remove('pastrami') 18 | 19 | print(sandwich_orders) 20 | 21 | # 7-10 梦想的度假胜地 22 | places = {} 23 | while True: 24 | username = input("Please input your username") 25 | place = input("If you could visit one place in the world, where would you go?") 26 | places[username] = place 27 | repeat = input("Do you want to input another username? (yes/no)") 28 | if repeat == 'no': 29 | break 30 | 31 | for username, place in places.items(): 32 | print(username + ":" + place) 33 | 34 | -------------------------------------------------------------------------------- /chapter09/only_user.py: -------------------------------------------------------------------------------- 1 | class User: 2 | def __init__(self, first_name, last_name, *profile): 3 | """初始化用户信息""" 4 | self.first_name = first_name 5 | self.last_name = last_name 6 | self.profile = profile 7 | self.login_attempts = 0 8 | 9 | def describe_user(self): 10 | """打印用户信息摘要""" 11 | print(self.first_name) 12 | print(self.last_name) 13 | print(self.profile) 14 | 15 | def greet_user(self): 16 | """问候用户""" 17 | print("Hello, " + self.first_name + " " + self.last_name + "!") 18 | 19 | def increment_login_attempts(self): 20 | """登陆次数加一""" 21 | self.login_attempts += 1 22 | 23 | def reset_login_attempts(self): 24 | """登陆次数置0""" 25 | self.login_attempts = 0 26 | 27 | 28 | class Admin(User): 29 | """管理员""" 30 | def __init__(self, first_name, last_name, privileges, *profile): 31 | """初始化""" 32 | super().__init__(first_name, last_name, profile) 33 | self.privileges = Privileges(privileges) 34 | 35 | def show_privileges(self): 36 | """显示管理员权限""" 37 | self.privileges.show_privileges() 38 | -------------------------------------------------------------------------------- /chapter08/test8.5.py: -------------------------------------------------------------------------------- 1 | # 8-12 三明治 2 | def sandwich(*toppings): 3 | """打印加在三明治中的配料""" 4 | print(toppings) 5 | 6 | 7 | sandwich('mushrooms', 'cheese', 'beef') 8 | sandwich('fruit') 9 | sandwich('fish', 'apple') 10 | 11 | # 8-13 用户简介 12 | def build_profile(first, last, **user_info): 13 | """创建一个字典,其中包含我们知道的有关用户的一切""" 14 | profile = {} 15 | profile['first_name'] = first 16 | profile['last_name'] = last 17 | for key, value in user_info.items(): 18 | profile[key] = value 19 | return profile 20 | 21 | 22 | profile = build_profile('Tian ran', 'Wang', age='21', hometown='Hangzhou', university='ZJU') 23 | for key,value in profile.items(): 24 | print(key + ":" + value ) 25 | 26 | 27 | # 8-14 汽车 28 | def make_car(manufacturer,model,**information): 29 | """将汽车信息存储在字典中""" 30 | car_info = {} 31 | car_info['manufacturer'] = manufacturer 32 | car_info['model'] = model 33 | for key,value in information.items(): 34 | car_info[key] = value 35 | 36 | return car_info 37 | 38 | 39 | car = make_car('subaru', 'outback', color='blue', two_package=True) 40 | for key,value in car.items(): 41 | print(key + ":" + str(value)) 42 | -------------------------------------------------------------------------------- /chapter08/formatted_name.py: -------------------------------------------------------------------------------- 1 | def get_formatted_name(first_name, last_name): 2 | """返回整洁的姓名""" 3 | full_name = first_name + ' ' + last_name 4 | return full_name.title() 5 | 6 | 7 | musician = get_formatted_name('jimi', 'hendrix') 8 | print(musician) 9 | 10 | 11 | # 让实参变成可选的 12 | def get_formatted_name(first_name, last_name, middle_name = ''): 13 | """返回整洁的姓名""" 14 | if middle_name: 15 | full_name = first_name + ' ' + middle_name + ' ' + last_name 16 | else: 17 | full_name = first_name + ' ' + last_name 18 | return full_name.title() 19 | 20 | 21 | musician = get_formatted_name('jimi', 'hendrix') 22 | print(musician) 23 | 24 | musician = get_formatted_name('john', 'hooker', 'lee') 25 | print(musician) 26 | 27 | # 结合使用函数和while循环 28 | while True: 29 | print("\nPlease tell me your name:") 30 | print("(enter 'q' at any time to quit)") 31 | 32 | f_name = input("First name: ") 33 | if f_name == 'q': 34 | break 35 | 36 | l_name = input("Last name: ") 37 | if l_name == 'q': 38 | break 39 | 40 | formatted_name = get_formatted_name(f_name, l_name) 41 | print("\nHello, " + formatted_name + "!") 42 | 43 | -------------------------------------------------------------------------------- /chapter06/alien.py: -------------------------------------------------------------------------------- 1 | alien_0 = {'color': 'green', 'points': 5} 2 | 3 | print(alien_0['color']) 4 | print(alien_0['points']) 5 | 6 | #访问字典中的值 7 | new_points = alien_0['points'] 8 | print("You just earned " + str(new_points) + " points!") 9 | 10 | #添加键-值对 11 | alien_0['x_position'] = 0 12 | alien_0['y_position'] = 25 13 | print(alien_0) 14 | 15 | #先创建一个空字典 16 | alien_0 = {} 17 | alien_0['color'] = 'green' 18 | alien_0['points'] = 5 19 | print(alien_0) 20 | 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': 'medium'} 28 | print("Original x-position: " + str(alien_0['x_position'])) 29 | 30 | #向右移动外星人 31 | #据外星人当前速度决定将其移动多远 32 | if alien_0['speed'] == 'slow': 33 | x_increment = 1 34 | elif alien_0['speed'] == 'medium': 35 | x_increment = 2 36 | else: 37 | # 这个外星人的速度一定很快 38 | x_increment = 3 39 | 40 | #新位置等于老位置加上增量 41 | alien_0['x_position'] = alien_0['x_position'] + x_increment 42 | print("New x-position: " + str(alien_0['x_position'])) 43 | 44 | #删除键-值对 45 | alien_0 = {'color': 'green', 'points': 5} 46 | print(alien_0) 47 | 48 | del alien_0['points'] 49 | print(alien_0) -------------------------------------------------------------------------------- /chapter09/electric_car.py: -------------------------------------------------------------------------------- 1 | """一组可用于表示电动汽车的类""" 2 | from car import Car 3 | 4 | 5 | class Battery: 6 | """一次模拟电动汽车电瓶的简单尝试""" 7 | 8 | def __init__(self, battery_size=70): 9 | """初始化电瓶的属性""" 10 | self.battery_size = battery_size 11 | 12 | def describe_battery(self): 13 | """打印一条描述电瓶容量的消息""" 14 | print("This car has a " + str(self.battery_size) + "-kwh battery") 15 | 16 | def get_range(self): 17 | """打印一条消息,指出电瓶的续航里程""" 18 | if self.battery_size == 70: 19 | range = 240 20 | elif self.battery_size == 85: 21 | range = 270 22 | 23 | message = "This car can go approximately " + str(range) 24 | message += " miles on a full charge." 25 | print(message) 26 | 27 | 28 | class ElectricCar(Car): 29 | def __init__(self, make, model, year): 30 | """ 31 | 电动汽车的独特之处 32 | 初始化父类的属性,再初始化电动汽车特有的属性 33 | """ 34 | super().__init__(make, model, year) 35 | self.battery = Battery() 36 | 37 | def describe_battery(self): 38 | """打印一条描述电瓶容量的信息""" 39 | print("This car has a " + str(self.battery_size) + "-kwh battery.") 40 | 41 | def fill_gas_tank(self): 42 | """电动汽车没有油箱""" 43 | print("This car doesn't need a gas tank!") 44 | 45 | 46 | -------------------------------------------------------------------------------- /chapter10/test10.3.py: -------------------------------------------------------------------------------- 1 | # 10-6 加法运算 2 | try: 3 | number1 = input("Please input a number:") 4 | number2 = input("Please input another number:") 5 | sum1 = int(number1) + int(number2) 6 | print(sum1) 7 | except ValueError: 8 | print("Please input number.") 9 | 10 | # 10-7 加法计算器 11 | while True: 12 | try: 13 | number1 = input("Please input a number:") 14 | number2 = input("Please input another number:") 15 | sum1 = int(number1) + int(number2) 16 | print(sum1) 17 | except ValueError: 18 | print("Please input number.") 19 | else: 20 | break 21 | 22 | # 10-8 猫和狗 23 | filename_1 = 'cats.txt' 24 | filename_2 = 'dogs.txt' 25 | try: 26 | with open(filename_1) as file_object: 27 | print(file_object.read()) 28 | with open(filename_2) as file_object: 29 | print(file_object.read()) 30 | except FileNotFoundError: 31 | print("File not exist!") 32 | 33 | # 10-9 沉默的猫和狗 34 | filename_1 = 'cats.txt' 35 | filename_2 = 'dogs.txt' 36 | try: 37 | with open(filename_1) as file_object: 38 | print(file_object.read()) 39 | with open(filename_2) as file_object: 40 | print(file_object.read()) 41 | except FileNotFoundError: 42 | pass 43 | 44 | # 10-10 常见单词 45 | filename = 'little_women.txt' 46 | with open(filename) as file_object: 47 | contents = file_object.read() 48 | 49 | print(contents.lower().count('the')) 50 | -------------------------------------------------------------------------------- /chapter09/user.py: -------------------------------------------------------------------------------- 1 | class User: 2 | def __init__(self, first_name, last_name, *profile): 3 | """初始化用户信息""" 4 | self.first_name = first_name 5 | self.last_name = last_name 6 | self.profile = profile 7 | self.login_attempts = 0 8 | 9 | def describe_user(self): 10 | """打印用户信息摘要""" 11 | print(self.first_name) 12 | print(self.last_name) 13 | print(self.profile) 14 | 15 | def greet_user(self): 16 | """问候用户""" 17 | print("Hello, " + self.first_name + " " + self.last_name + "!") 18 | 19 | def increment_login_attempts(self): 20 | """登陆次数加一""" 21 | self.login_attempts += 1 22 | 23 | def reset_login_attempts(self): 24 | """登陆次数置0""" 25 | self.login_attempts = 0 26 | 27 | 28 | class Admin(User): 29 | """管理员""" 30 | def __init__(self, first_name, last_name, privileges, *profile): 31 | """初始化""" 32 | super().__init__(first_name, last_name, profile) 33 | self.privileges = Privileges(privileges) 34 | 35 | def show_privileges(self): 36 | """显示管理员权限""" 37 | self.privileges.show_privileges() 38 | 39 | 40 | class Privileges: 41 | def __init__(self, privileges): 42 | self.privileges = privileges 43 | 44 | def show_privileges(self): 45 | """显示管理员权限""" 46 | for privilege in self.privileges: 47 | print(privilege) -------------------------------------------------------------------------------- /chapter05/test5.4.py: -------------------------------------------------------------------------------- 1 | #5-8 以特殊方式跟管理员打招呼 2 | users = ['admin', 'star', 'nash', 'kobe', 'james'] 3 | for user in users: 4 | if user == 'admin': 5 | print("Hello admin, would you like to see a status report?") 6 | else: 7 | print("Hello " + user + ", thank you for logging in again") 8 | 9 | #5-9 处理没有用户的情形 10 | users = [] 11 | if users: 12 | for user in users: 13 | if user == 'admin': 14 | print("Hello admin, would you like to see a status report?") 15 | else: 16 | print("Hello " + user + ", thank you for logging in again") 17 | else: 18 | print("We need to find some users!") 19 | 20 | #5-10 检查用户名 21 | current_users = ['admin', 'star', 'Nash', 'kobe', 'james'] 22 | new_users = ['admin', 'curry', 'NASH', 'kidd', 'jordan'] 23 | lower_current_users = [user.lower() for user in current_users] 24 | for new_user in new_users: 25 | if new_user.lower() in lower_current_users: 26 | print("The user name have been used! You need to input another user name!") 27 | else: 28 | print("The user name have not been used!") 29 | 30 | #5-11序数 31 | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] 32 | for number in numbers: 33 | if number == 1: 34 | print(str(number) + "st") 35 | elif number == 2: 36 | print(str(number) + "nd") 37 | elif number == 3: 38 | print(str(number) + "rd") 39 | else: 40 | print(str(number) + "th") 41 | -------------------------------------------------------------------------------- /chapter07/test7.2.py: -------------------------------------------------------------------------------- 1 | # 7-4 比萨配料 2 | prompt = "Please enter a topping:" 3 | prompt += "\nEnter 'quit' to end the loop." 4 | active = True 5 | while active: 6 | topping = input(prompt) 7 | if topping == 'quit': 8 | active = False 9 | else: 10 | print("We will add " + topping + " to your pizza!") 11 | 12 | # 7-5 电影票 13 | prompt = "Please enter your age." 14 | prompt += "\nEnter 'quit to end the loop." 15 | active = True 16 | while active: 17 | age = input(prompt) 18 | if age == 'quit': 19 | active = False 20 | else: 21 | age = int(age) 22 | if age < 3: 23 | print("Free") 24 | elif age <= 12: 25 | print("$10") 26 | else: 27 | print("$15") 28 | 29 | # 7-6 三个出口 30 | # 修改 7-5 31 | # 用户输入'quit'时用break结束循环 32 | while True: 33 | age = input(prompt) 34 | if age == 'quit': 35 | break 36 | else: 37 | age = int(age) 38 | if age < 3: 39 | print("Free") 40 | elif age <= 12: 41 | print("$10") 42 | else: 43 | print("$15") 44 | 45 | # while循环中使用条件测试结束循环 46 | age = "" 47 | while age != 'quit': 48 | age = input(prompt) 49 | if age != 'quit': 50 | age = int(age) 51 | if age < 3: 52 | print("Free") 53 | elif age <= 12: 54 | print("$10") 55 | else: 56 | print("$15") 57 | 58 | # 7-7 无限循环 59 | while True: 60 | print(1) 61 | 62 | -------------------------------------------------------------------------------- /chapter08/printing_models.py: -------------------------------------------------------------------------------- 1 | # 不使用函数 2 | unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] 3 | completed_models = [] 4 | 5 | while unprinted_designs: 6 | current_design = unprinted_designs.pop() 7 | 8 | print("Printing model: " + current_design) 9 | completed_models.append(current_design) 10 | 11 | print("\nThe following models have been printed:") 12 | for completed_model in completed_models: 13 | print(completed_model) 14 | 15 | 16 | # 使用函数 17 | def print_models(unprinted_designs, completed_models): 18 | """ 19 | 模拟打印每个设计,直到没有未打印的设计为止 20 | 打印每个设计后,都将其移到列表completed_models中 21 | """ 22 | while unprinted_designs: 23 | current_design = unprinted_designs.pop() 24 | 25 | print("Printing model: " + current_design) 26 | completed_models.append(current_design) 27 | 28 | 29 | def show_completed_models(completed_models): 30 | """显示打印好的所有模型""" 31 | print("\nThe following models have been printed:") 32 | for completed_model in completed_models: 33 | print(completed_model) 34 | 35 | 36 | unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] 37 | completed_models = [] 38 | print_models(unprinted_designs,completed_models) 39 | show_completed_models(completed_models) 40 | 41 | #传递副本的方法,可以禁止函数修改原来的列表 42 | unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] 43 | completed_models = [] 44 | print_models(unprinted_designs[:], completed_models) 45 | show_completed_models(completed_models) 46 | print(unprinted_designs) -------------------------------------------------------------------------------- /chapter03/motorcycles.py: -------------------------------------------------------------------------------- 1 | motorcycles = ['honda', 'yamaha', 'suzuki'] 2 | print(motorcycles) 3 | 4 | #修改列表元素 5 | motorcycles[0] = 'ducati' 6 | print(motorcycles) 7 | 8 | #在列表末尾添加元素 9 | motorcycles = ['honda', 'yamaha', 'suzuki'] 10 | motorcycles.append('ducati') 11 | print(motorcycles) 12 | 13 | motorcycles = [] 14 | motorcycles.append('honda') 15 | motorcycles.append('yamaha') 16 | motorcycles.append('suzuki') 17 | print(motorcycles) 18 | 19 | #在列表中插入元素 20 | motorcycles.insert(0, 'ducati') 21 | print(motorcycles) 22 | 23 | #从列表中删除元素 24 | #使用del语句删除元素 25 | motorcycles = ['honda', 'yamaha', 'suzuki'] 26 | print(motorcycles) 27 | del motorcycles[0] 28 | print(motorcycles) 29 | 30 | motorcycles = ['honda', 'yamaha', 'suzuki'] 31 | print(motorcycles) 32 | del motorcycles[1] 33 | print(motorcycles) 34 | 35 | #使用方法pop()删除元素 36 | motorcycles = ['honda', 'yamaha', 'suzuki'] 37 | print(motorcycles) 38 | 39 | popped_motorcycle = motorcycles.pop() 40 | print(motorcycles) 41 | print(popped_motorcycle) 42 | 43 | motorcycles = ['honda', 'yamaha', 'suzuki'] 44 | last_owned = motorcycles.pop() 45 | print("The last motorcycle I owned was a " + last_owned.title() + ".") 46 | 47 | #弹出列表中任何位置处的元素 48 | motorcycles = ['honda', 'yamaha', 'suzuki'] 49 | first_owned = motorcycles.pop(0) 50 | print('The first motorcycle I owned was a ' + first_owned.title() + '.') 51 | 52 | #根据值删除元素 53 | motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 54 | print(motorcycles) 55 | motorcycles.remove('ducati') 56 | print(motorcycles) 57 | 58 | motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 59 | print(motorcycles) 60 | too_expensice = 'ducati' 61 | motorcycles.remove(too_expensice) 62 | print(motorcycles) 63 | print("\nA " + too_expensice.title() + " is too expensive for me.") 64 | -------------------------------------------------------------------------------- /chapter03/test3.2.py: -------------------------------------------------------------------------------- 1 | #3-4嘉宾名单 2 | people = ['john', 'mike', 'sarah', 'nash', 'kobe'] 3 | print(people[0].title() + "," + people[1].title() + "," + people[2].title() + "," + people[3].title() + "," + 4 | people[4].title() + ", welcome to have dinner with me!") 5 | 6 | #3-5修改嘉宾名单 7 | print("It's a pity that " + people[1] + " can't enter my dinner.") 8 | people[1] = 'james' 9 | print(people[0].title() + "," + people[1].title() + "," + people[2].title() + "," + people[3].title() + "," + 10 | people[4].title() + ", welcome to have dinner with me!") 11 | 12 | #3-6添加嘉宾 13 | print("I have found a bigger table") 14 | people.insert(0, "curry") 15 | people.insert(3, "durant") 16 | people.insert(7, "kidd") 17 | print(people[0].title() + "," + people[1].title() + "," + people[2].title() + "," + people[3].title() + "," + 18 | people[4].title() + "," + people[5].title() + "," + people[6].title() + "," + 19 | people[7].title() + ", welcome to have dinner with me!") 20 | 21 | #3-7缩减名单 22 | print("Sorry, only two persons can have dinner with me") 23 | person = people.pop() 24 | print("Sorry " + person + ", I can't invite you to enter my dinner") 25 | person = people.pop() 26 | print("Sorry " + person + ", I can't invite you to enter my dinner") 27 | person = people.pop() 28 | print("Sorry " + person + ", I can't invite you to enter my dinner") 29 | person = people.pop() 30 | print("Sorry " + person + ", I can't invite you to enter my dinner") 31 | person = people.pop() 32 | print("Sorry " + person + ", I can't invite you to enter my dinner") 33 | person = people.pop() 34 | print("Sorry " + person + ", I can't invite you to enter my dinner") 35 | print(people[0] + ", you still can have dinner with me!") 36 | print(people[1] + ", you still can have dinner with me!") 37 | del people[1] 38 | del people[0] 39 | print(people) 40 | -------------------------------------------------------------------------------- /chapter09/test9.1.py: -------------------------------------------------------------------------------- 1 | # 9-1 餐馆 2 | class Restaurant: 3 | """模拟餐馆""" 4 | def __init__(self, restaurant_name, cuisine_type): 5 | """初始化餐馆名和菜肴类型""" 6 | self.restaurant_name = restaurant_name 7 | self.cuisine_type = cuisine_type 8 | 9 | def describe_restaurant(self): 10 | """打印餐馆信息""" 11 | print("restaurant name: " + self.restaurant_name) 12 | print("cuisine_type: " + self.cuisine_type) 13 | 14 | def open_restaurant(self): 15 | """表示餐厅正在营业""" 16 | print("restaurant is open!") 17 | 18 | 19 | restaurant = Restaurant("KFC", "junk food") 20 | print(restaurant.restaurant_name) 21 | print(restaurant.cuisine_type) 22 | restaurant.describe_restaurant() 23 | restaurant.open_restaurant() 24 | 25 | # 9-2 三家餐馆 26 | restaurant_0 = Restaurant("M", "junk food") 27 | restaurant_1 = Restaurant("hamburger king", "hamburger") 28 | restaurant_2 = Restaurant("黄焖鸡米饭", "中餐") 29 | restaurant_0.describe_restaurant() 30 | restaurant_1.describe_restaurant() 31 | restaurant_2.describe_restaurant() 32 | 33 | 34 | # 9-3 用户 35 | class User: 36 | """描述用户信息的类""" 37 | def __init__(self, first_name, last_name, *profile): 38 | """初始化用户信息""" 39 | self.first_name = first_name 40 | self.last_name = last_name 41 | self.profile = profile 42 | 43 | def describe_user(self): 44 | """打印用户信息摘要""" 45 | print(self.first_name) 46 | print(self.last_name) 47 | print(self.profile) 48 | 49 | def greet_user(self): 50 | """问候用户""" 51 | print("Hello, " + self.first_name + " " + self.last_name + "!") 52 | 53 | 54 | user_1 = User('wang', 'tianran', 'a', 'b', 'c') 55 | user_2 = User('steve', 'nash', 'handsome') 56 | user_1.describe_user() 57 | user_1.greet_user() 58 | user_2.greet_user() 59 | user_2.describe_user() 60 | -------------------------------------------------------------------------------- /chapter06/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'].title() + 10 | ".") 11 | 12 | #遍历所有键值对 13 | for name, language in favorite_languages.items(): 14 | print(name.title() + "'s favorite language is " + 15 | language.title() + '.') 16 | 17 | #遍历字典中的所有键 18 | for name in favorite_languages.keys(): 19 | print(name.title()) 20 | 21 | for name in favorite_languages: 22 | print(name.title()) 23 | 24 | friends = ['phil', 'sarah'] 25 | for name in favorite_languages.keys(): 26 | print(name.title()) 27 | 28 | if name in friends: 29 | print(" Hi " + name.title() + 30 | ", I see your favorite language is " + 31 | favorite_languages[name].title() + "!") 32 | 33 | if 'erin' not in favorite_languages.keys(): 34 | print("Erin, please take our poll!") 35 | 36 | #按顺序遍历字典中的所有值 37 | for name in sorted(favorite_languages.keys()): 38 | print(name.title() + ", thank you for talking the poll.") 39 | 40 | #遍历字典中的所有值 41 | print("The following languages have been mentioned:") 42 | for language in favorite_languages.values(): 43 | print(language.title()) 44 | 45 | #剔除重复项 46 | for language in set(favorite_languages.values()): 47 | print(language.title()) 48 | 49 | #在字典中存储列表 50 | favorite_languages = { 51 | 'jen': ['python', 'ruby'], 52 | 'sarah': ['c'], 53 | 'edward': ['ruby', 'go'], 54 | 'phil': ['python', 'haskell'], 55 | } 56 | 57 | for name, languages in favorite_languages.items(): 58 | if len(languages) == 1: 59 | print("\n" + name.title() + "'s favorite language is:") 60 | else: 61 | print("\n" + name.title() + "'s favorite languages are:") 62 | for language in languages: 63 | print("\t" + language.title()) 64 | 65 | -------------------------------------------------------------------------------- /chapter10/test10.4.py: -------------------------------------------------------------------------------- 1 | # 10-11 喜欢的数字 2 | import json 3 | number = input("Please input your love number") 4 | filename = 'love_number.json' 5 | with open(filename, 'w') as f_obj: 6 | json.dump(number, f_obj) 7 | 8 | with open(filename) as f_obj: 9 | love_number = json.load(f_obj) 10 | 11 | print("I know your favorite number! It's " + love_number) 12 | 13 | # 10-12 记住喜欢的数字 14 | try: 15 | with open(filename) as f_obj: 16 | number = json.load(f_obj) 17 | except FileNotFoundError: 18 | number = input("Please input your love number") 19 | filename = 'love_number.json' 20 | with open(filename, 'w') as f_obj: 21 | json.dump(number, f_obj) 22 | else: 23 | print("I know your favorite number! It's " + number) 24 | 25 | 26 | # 10-13 验证用户 27 | def get_stored_username(): 28 | """如果存储了用户名,就获取它""" 29 | filename = 'username.json' 30 | try: 31 | with open(filename) as f_obj: 32 | username = json.load(f_obj) 33 | except FileNotFoundError: 34 | return None 35 | else: 36 | return username 37 | 38 | 39 | def get_new_username(): 40 | """提示用户输入用户名""" 41 | username = input("What is your name?") 42 | filename = 'username.json' 43 | with open(filename, 'w') as f_obj: 44 | json.dump(username, f_obj) 45 | return username 46 | 47 | 48 | def greet_user(): 49 | """问候用户, 并指出其名字""" 50 | username = get_stored_username() 51 | if username: 52 | print("Is your name " + username + "?") 53 | is_name = input("Please input yes or no?") 54 | if is_name == 'yes': 55 | print("Welcome back, " + username + "!") 56 | else: 57 | username = get_new_username() 58 | print("We'll remember you when you come back, " + username + "!") 59 | else: 60 | username = get_new_username() 61 | print("We'll remember you when you come back, " + username + "!") 62 | 63 | 64 | greet_user() 65 | -------------------------------------------------------------------------------- /chapter06/test6.4.py: -------------------------------------------------------------------------------- 1 | #6-7 人 2 | person_0 = {'first_name': 'steve', 'last_name': 'nash', 'age': 43, 'city': 'the golden states'} 3 | person_1 = {'first_name': 'stephen', 'last_name': 'curry', 'age': 29, 'city': 'the golden states'} 4 | person_2 = {'first_name': 'kobe', 'last_name': 'bryant', 'age': 39, 'city': 'los Angeles'} 5 | 6 | people = [person_0, person_1, person_2] 7 | for person in people: 8 | print(person) 9 | 10 | #6-8 宠物 11 | pet_0 = {'kind': 'pig', 'master': 'wtr'} 12 | pet_1 = {'kind': 'dog', 'master': 'star'} 13 | pets = [pet_0, pet_1] 14 | for pet in pets: 15 | print(pet) 16 | 17 | #6-9 喜欢的地方 18 | favorite_places ={ 19 | 'star': ['nei meng', 'hang zhou', 'wu han'], 20 | 'wtr': ['phoenix', 'hang zhou'], 21 | 'nash': ['canada', 'america'], 22 | } 23 | for name, places in favorite_places.items(): 24 | print(name + " loves to go to:") 25 | for place in places: 26 | print(place) 27 | 28 | #6-10 喜欢的数字 29 | number = { 30 | 'star': [4, 18], 31 | 'nash': [13, 10, 3], 32 | 'mike': [1], 33 | 'kobe': [24, 8], 34 | 'james': [23, 6], 35 | } 36 | 37 | for person, numbers in number.items(): 38 | print(person + " loves:") 39 | for number in numbers: 40 | print(number) 41 | 42 | #6-11 城市 43 | cities = { 44 | 'Hangzhou': { 45 | 'country': 'china', 46 | 'popularity': '8,000,000', 47 | 'fact': 'beautiful', 48 | }, 49 | 'Phoenix': { 50 | 'country': 'america', 51 | 'popularity': '1,000,000', 52 | 'fact': 'suns', 53 | }, 54 | 'Neimeng': { 55 | 'country': 'china', 56 | 'popularity': '2,000,000', 57 | 'fact': 'grassland', 58 | }, 59 | 60 | } 61 | 62 | for city, information in cities.items(): 63 | print(city + "has these information:") 64 | print("country: " + information['country']) 65 | print("popularity: " + information['popularity']) 66 | print("fact: " + information['fact']) 67 | 68 | 69 | -------------------------------------------------------------------------------- /chapter05/toppings.py: -------------------------------------------------------------------------------- 1 | requested_topping = 'mushrooms' 2 | 3 | if requested_topping != 'anchovies': 4 | print("Hold the anchovies!") 5 | 6 | #测试多个条件 7 | requested_toppings = ['mushrooms', 'extra cheese'] 8 | 9 | if 'mushrooms' in requested_toppings: 10 | print("Adding mushrooms.") 11 | if 'pepperoni' in requested_toppings: 12 | print("Adding pepperoni.") 13 | if 'extra cheese' in requested_toppings: 14 | print("Adding extra cheese.") 15 | 16 | print("\nFinished making your pizza!") 17 | 18 | #只执行一个代码块 19 | if 'mushrooms' in requested_toppings: 20 | print("Adding mushrooms.") 21 | elif 'pepperoni' in requested_toppings: 22 | print("Adding pepperoni.") 23 | elif 'extra cheese' in requested_toppings: 24 | print("Adding extra cheese.") 25 | 26 | print("\nFinished making your pizza!") 27 | 28 | #检查特殊元素 29 | requested_toppings = ['mushrooms', 'green peppers', 'extra cheese'] 30 | 31 | for requested_topping in requested_toppings: 32 | if requested_topping == 'green peppers': 33 | print("Sorry, we are out of green peppers right now.") 34 | else: 35 | print("Adding " + requested_topping + ".") 36 | 37 | print("\nFinished making your pizza!") 38 | 39 | #确定列表不是空的 40 | requested_toppings = [] 41 | 42 | if requested_toppings: 43 | for requested_topping in requested_toppings: 44 | print("Adding " + requested_topping + ".") 45 | print("\nFinished making your pizza!") 46 | else: 47 | print("Are you sure you want a plain pizza?") 48 | 49 | #使用多个列表 50 | available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] 51 | requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] 52 | 53 | for requested_topping in requested_toppings: 54 | if requested_topping in available_toppings: 55 | print("Adding " + requested_topping + ".") 56 | else: 57 | print("Sorry, we don't have " + requested_topping + ".") 58 | print("\nFinished making your pizza!") 59 | -------------------------------------------------------------------------------- /chapter05/test5.3.py: -------------------------------------------------------------------------------- 1 | #5-3 外星人颜色#1 2 | alien_color = 'green' 3 | if alien_color == 'green': 4 | print('You got 5 points!') 5 | 6 | alien_color = 'yellow' 7 | if alien_color == 'green': 8 | print('You got 5 points!') 9 | 10 | #5-4外星人颜色#2 11 | alien_color = 'green' 12 | if alien_color == 'green': 13 | print("You got 5 points!") 14 | else: 15 | print("You got 10 points!") 16 | 17 | alien_color = 'yellow' 18 | if alien_color == 'green': 19 | print("You got 5 points!") 20 | else: 21 | print("You got 10 points!") 22 | 23 | #5-5 外星人颜色#3 24 | alien_color = 'green' 25 | if alien_color == 'green': 26 | print("You got 5 points!") 27 | elif alien_color == 'yellow': 28 | print("You got 10 points!") 29 | else : 30 | print("You got 15 points!") 31 | 32 | alien_color = 'yellow' 33 | if alien_color == 'green': 34 | print("You got 5 points!") 35 | elif alien_color == 'yellow': 36 | print("You got 10 points!") 37 | else: 38 | print("You got 15 points!") 39 | 40 | alien_color = 'red' 41 | if alien_color == 'green': 42 | print("You got 5 points!") 43 | elif alien_color == 'yellow': 44 | print("You got 10 points!") 45 | else: 46 | print("You got 15 points!") 47 | 48 | #5-6 人生的不同阶段 49 | age = 21 50 | if age < 2: 51 | print("He is a baby") 52 | elif age < 4: 53 | print("He is studying walking now") 54 | elif age < 13: 55 | print("He is a child") 56 | elif age < 20: 57 | print("He is a teenage") 58 | elif age < 65: 59 | print("He is an adult") 60 | else: 61 | print("He is an old man") 62 | 63 | #5-7 喜欢的水果 64 | favorite_fruits = ['banana', 'strawberry', 'watermelon'] 65 | if 'banana' in favorite_fruits: 66 | print("You really like bananas!") 67 | if 'strawberry' in favorite_fruits: 68 | print("You really like strawberry!") 69 | if 'apple' in favorite_fruits: 70 | print("You really like apple!") 71 | if 'watermelon' in favorite_fruits: 72 | print("You really like watermelon!") 73 | if 'pineapple' in favorite_fruits: 74 | print("You really like pineapple!") 75 | 76 | -------------------------------------------------------------------------------- /chapter09/test9.2.py: -------------------------------------------------------------------------------- 1 | # 9-4 就餐人数 2 | class Restaurant: 3 | """模拟餐馆""" 4 | def __init__(self, restaurant_name, cuisine_type): 5 | """初始化餐馆名和菜肴类型""" 6 | self.restaurant_name = restaurant_name 7 | self.cuisine_type = cuisine_type 8 | self.number_served = 0 9 | 10 | def describe_restaurant(self): 11 | """打印餐馆信息""" 12 | print("restaurant name: " + self.restaurant_name) 13 | print("cuisine_type: " + self.cuisine_type) 14 | 15 | def open_restaurant(self): 16 | """表示餐厅正在营业""" 17 | print("restaurant is open!") 18 | 19 | def set_number_served(self, number_served): 20 | """设置就餐人数""" 21 | self.number_served = number_served 22 | 23 | def increment_number_served(self, increment): 24 | """增加就餐人数""" 25 | self.number_served += increment 26 | 27 | 28 | restaurant = Restaurant("kfc", "junk food") 29 | print(restaurant.number_served) 30 | restaurant.number_served = 10 31 | print(restaurant.number_served) 32 | 33 | restaurant.set_number_served(100) 34 | print(restaurant.number_served) 35 | 36 | restaurant.increment_number_served(10) 37 | print(restaurant.number_served) 38 | 39 | # 9-5 尝试登陆次数 40 | """描述用户信息的类""" 41 | class User: 42 | def __init__(self, first_name, last_name, *profile): 43 | """初始化用户信息""" 44 | self.first_name = first_name 45 | self.last_name = last_name 46 | self.profile = profile 47 | self.login_attempts = 0 48 | 49 | def describe_user(self): 50 | """打印用户信息摘要""" 51 | print(self.first_name) 52 | print(self.last_name) 53 | print(self.profile) 54 | 55 | def greet_user(self): 56 | """问候用户""" 57 | print("Hello, " + self.first_name + " " + self.last_name + "!") 58 | 59 | def increment_login_attempts(self): 60 | """登陆次数加一""" 61 | self.login_attempts += 1 62 | 63 | def reset_login_attempts(self): 64 | """登陆次数置0""" 65 | self.login_attempts = 0 66 | 67 | 68 | user = User('steve', 'nash', 'handsome') 69 | print(user.login_attempts) 70 | user.increment_login_attempts() 71 | user.increment_login_attempts() 72 | print(user.login_attempts) 73 | user.reset_login_attempts() 74 | print(user.login_attempts) -------------------------------------------------------------------------------- /chapter09/car.py: -------------------------------------------------------------------------------- 1 | """一组用于表示燃油汽车和电动汽车的类""" 2 | 3 | 4 | class Car(): 5 | """一次模拟汽车的简单尝试""" 6 | 7 | def __init__(self, make, model, year): 8 | """初始化描述汽车的属性""" 9 | self.make = make 10 | self.model = model 11 | self.year = year 12 | self.odometer_reading = 0 13 | 14 | def get_descriptive_name(self): 15 | """返回整洁的描述性信息""" 16 | long_name = str(self.year) + ' ' + self.make + ' ' + self.model 17 | return long_name.title() 18 | 19 | def read_odometer(self): 20 | """打印一条指出汽车里程的消息""" 21 | print("This car has " + str(self.odometer_reading) + " miles on it.") 22 | 23 | def update_odometer(self, mileage): 24 | """ 25 | 将里程表读数设置为指定的值 26 | 禁止将里程表读数往回调 27 | """ 28 | if mileage >= self.odometer_reading: 29 | self.odometer_reading = mileage 30 | else: 31 | print("You can't roll back an odometer!") 32 | 33 | def increment_odometer(self, miles): 34 | """将里程表读数增加指定的量""" 35 | self.odometer_reading += miles 36 | 37 | 38 | class Battery: 39 | """一次模拟电动汽车电瓶的简单尝试""" 40 | 41 | def __init__(self, battery_size=70): 42 | """初始化电瓶的属性""" 43 | self.battery_size = battery_size 44 | 45 | def describe_battery(self): 46 | """打印一条描述电瓶容量的消息""" 47 | print("This car has a " + str(self.battery_size) + "-kwh battery") 48 | 49 | def get_range(self): 50 | """打印一条消息,指出电瓶的续航里程""" 51 | if self.battery_size == 70: 52 | range = 240 53 | elif self.battery_size == 85: 54 | range = 270 55 | 56 | message = "This car can go approximately " + str(range) 57 | message += " miles on a full charge." 58 | print(message) 59 | 60 | 61 | class ElectricCar(Car): 62 | def __init__(self, make, model, year): 63 | """ 64 | 电动汽车的独特之处 65 | 初始化父类的属性,再初始化电动汽车特有的属性 66 | """ 67 | super().__init__(make, model, year) 68 | self.battery = Battery() 69 | 70 | def describe_battery(self): 71 | """打印一条描述电瓶容量的信息""" 72 | print("This car has a " + str(self.battery_size) + "-kwh battery.") 73 | 74 | def fill_gas_tank(self): 75 | """电动汽车没有油箱""" 76 | print("This car doesn't need a gas tank!") 77 | -------------------------------------------------------------------------------- /chapter09/test9.3.py: -------------------------------------------------------------------------------- 1 | # 9-6 冰淇淋小店 2 | class Restaurant: 3 | """模拟餐馆""" 4 | def __init__(self, restaurant_name, cuisine_type): 5 | """初始化餐馆名和菜肴类型""" 6 | self.restaurant_name = restaurant_name 7 | self.cuisine_type = cuisine_type 8 | self.number_served = 0 9 | 10 | def describe_restaurant(self): 11 | """打印餐馆信息""" 12 | print("restaurant name: " + self.restaurant_name) 13 | print("cuisine_type: " + self.cuisine_type) 14 | 15 | def open_restaurant(self): 16 | """表示餐厅正在营业""" 17 | print("restaurant is open!") 18 | 19 | def set_number_served(self, number_served): 20 | """设置就餐人数""" 21 | self.number_served = number_served 22 | 23 | def increment_number_served(self, increment): 24 | """增加就餐人数""" 25 | self.number_served += increment 26 | 27 | 28 | class IceCreamStand(Restaurant): 29 | """冰淇淋小店""" 30 | def __init__(self, restaurant_name, cuisine_type, flavors): 31 | """初始化""" 32 | super().__init__(restaurant_name, cuisine_type) 33 | self.flavors = flavors 34 | 35 | def show_flavors(self): 36 | """展示冰淇淋口味""" 37 | for flavor in self.flavors: 38 | print(flavor) 39 | 40 | 41 | flavors = ['apple', 'banana', 'mango'] 42 | iceCreamStand = IceCreamStand("KFC", "junk food", flavors) 43 | iceCreamStand.show_flavors() 44 | 45 | 46 | # 9-7 管理员 47 | class User: 48 | def __init__(self, first_name, last_name, *profile): 49 | """初始化用户信息""" 50 | self.first_name = first_name 51 | self.last_name = last_name 52 | self.profile = profile 53 | self.login_attempts = 0 54 | 55 | def describe_user(self): 56 | """打印用户信息摘要""" 57 | print(self.first_name) 58 | print(self.last_name) 59 | print(self.profile) 60 | 61 | def greet_user(self): 62 | """问候用户""" 63 | print("Hello, " + self.first_name + " " + self.last_name + "!") 64 | 65 | def increment_login_attempts(self): 66 | """登陆次数加一""" 67 | self.login_attempts += 1 68 | 69 | def reset_login_attempts(self): 70 | """登陆次数置0""" 71 | self.login_attempts = 0 72 | 73 | 74 | class Admin(User): 75 | """管理员""" 76 | def __init__(self, first_name, last_name, privileges, *profile): 77 | """初始化""" 78 | super().__init__(first_name, last_name, profile) 79 | self.privileges = Privileges(privileges) 80 | 81 | def show_privileges(self): 82 | """显示管理员权限""" 83 | self.privileges.show_privileges() 84 | 85 | 86 | # 9-8 权限 87 | class Privileges: 88 | def __init__(self, privileges): 89 | self.privileges = privileges 90 | 91 | def show_privileges(self): 92 | """显示管理员权限""" 93 | for privilege in self.privileges: 94 | print(privilege) 95 | 96 | 97 | admin = Admin("Tian ran", "Wang", ['add', 'remove'], 'handsome', 'tall') 98 | admin.show_privileges() 99 | 100 | 101 | # 9-9 电瓶升级 102 | class Car(): 103 | """一次模拟汽车的简单尝试""" 104 | def __init__(self, make, model, year): 105 | """初始化描述汽车的属性""" 106 | self.make = make 107 | self.model = model 108 | self.year = year 109 | self.odometer_reading = 0 110 | 111 | def get_descriptive_name(self): 112 | """返回整洁的描述性信息""" 113 | long_name = str(self.year) + ' ' + self.make + ' ' + self.model 114 | return long_name.title() 115 | 116 | def read_odometer(self): 117 | """打印一条指出汽车里程的消息""" 118 | print("This car has " + str(self.odometer_reading) + " miles on it.") 119 | 120 | def update_odometer(self, mileage): 121 | """ 122 | 将里程表读数设置为指定的值 123 | 禁止将里程表读数往回调 124 | """ 125 | if mileage >= self.odometer_reading: 126 | self.odometer_reading = mileage 127 | else: 128 | print("You can't roll back an odometer!") 129 | 130 | def increment_odometer(self, miles): 131 | """将里程表读数增加指定的量""" 132 | self.odometer_reading += miles 133 | 134 | def fill_gas_tank(self): 135 | """汽车有油箱""" 136 | print("This car need a gas tank!") 137 | 138 | class Battery: 139 | """一次模拟电动汽车电瓶的简单尝试""" 140 | 141 | def __init__(self, battery_size=70): 142 | """初始化电瓶的属性""" 143 | self.battery_size = battery_size 144 | 145 | def describe_battery(self): 146 | """打印一条描述电瓶容量的消息""" 147 | print("This car has a " + str(self.battery_size) + "-kwh battery") 148 | 149 | def get_range(self): 150 | """打印一条消息,指出电瓶的续航里程""" 151 | if self.battery_size == 70: 152 | range = 240 153 | elif self.battery_size == 85: 154 | range = 270 155 | 156 | message = "This car can go approximately " + str(range) 157 | message += " miles on a full charge." 158 | print(message) 159 | 160 | def upgrade_battery(self): 161 | """检查电瓶容量""" 162 | if self.battery_size != 85: 163 | self.battery_size = 85 164 | 165 | 166 | class ElectricCar(Car): 167 | def __init__(self, make, model, year): 168 | """ 169 | 电动汽车的独特之处 170 | 初始化父类的属性,再初始化电动汽车特有的属性 171 | """ 172 | super().__init__(make, model, year) 173 | self.battery = Battery() 174 | 175 | def describe_battery(self): 176 | """打印一条描述电瓶容量的信息""" 177 | print("This car has a " + str(self.battery_size) + "-kwh battery.") 178 | 179 | def fill_gas_tank(self): 180 | """电动汽车没有油箱""" 181 | print("This car doesn't need a gas tank!") 182 | 183 | 184 | car = ElectricCar('BMW', 's', 2016) 185 | car.battery.get_range() 186 | car.battery.upgrade_battery() 187 | car.battery.get_range() --------------------------------------------------------------------------------