Souce code for the book:
# places = ['lushan', 'zhangjiajie','aerbeisishan', 'sea', 'jiuzhaigou'] # for place in places: # print(f'{place.title()} is so beautfull!') # print(f"I can't wait to see you, {place.title()}.\n") # print(f"It's great to do that") fruits = ['apple','peach','orange'] for fruit in fruits: print(fruit) print(f'My faverate fruit is {fruit.title()}') print(f'I like fruit') animals = ['lion', 'tiger','deer'] for animal in animals: print(animal) print(f'{animal.title()} is a dangerous animal.') print(f'All the animals are dangerous.')
# bicycles=[' trek ',' cannondale ','redline'] # message= f"My first bicycle was a {bicycles[0].title().strip()}." # print(message) # names = ['stephen', 'eton', 'frank', 'jeremy'] # message = f"hello,{names[0].title()}." # message1 = f"hello,{names[1].title()}." # message2 = f"hello,{names[2].title()}." # message3 = f"hello,{names[3].title()}." # print(message) # print(message1) # print(message2) # print(message3) # vehicles= ['BMW','Benz','Audi'] # message = f"I would like to have a {vehicles[0]}." # print(message) # print(vehicles) # vehicles.append('porsche') # #print(vehicles) # vehicles2 = [] # vehicles2.append('Porsche') # vehicles2.append('Maserati') # vehicles2.insert(1, 'Mclaren') # vehicles2.insert(1, 'Aston Matin') # vehicles2.append(vehicles) # del vehicles2[-1] # poped_vehicles = vehicles2.pop(2) # print(vehicles2) # print(poped_vehicles) # print(f"The last vehicles is {poped_vehicles.title()}") # removed_item = 'Aston Matin' # vehicles2.remove(removed_item) # print(f'\n {removed_item.title()} is removed.') # print(vehicles2) # names = ['pig','sheep','cow'] # poped_name = 'sheep' # names.remove(poped_name) # print(f'{poped_name.title()} cannot come.') # names.insert(1, 'duck') # print(f'\nI have found a big table!') # names.insert(0,'rabbit') # names.insert(0,'Cat') # names.append('Dog') # message = f'Please come my house to have a meeting, {names[0].title()}.' # message1 = f'Please come my house to have a meeting, {names[1].title()}.' # message2 = f'Please come my house to have a meeting, {names[2].title()}.' # print(message) # print(message1) # print(message2) # message3 = f'\nPlease come to my house to have a meeting, {names[3].title()}' # message4 = f'\nPlease come to my house to have a meeting, {names[4].title()}' # message5 = f'\nPlease come to my house to have a meeting, {names[5].title()}' # print(message3) # print(message4) # print(message5) # poped_name = names.pop() # print(f'Sorry, cannot invite you, {poped_name.title()}') # poped_name = names.pop() # print(f'Sorry, cannot invite you, {poped_name.title()}') # poped_name = names.pop() # print(f'Sorry, cannot invite you, {poped_name.title()}') # poped_name = names.pop() # print(f'Sorry, cannot invite you, {poped_name.title()}') # print(f'You are welcome to house still, {names[0].title()}, {names[1].title()}.') # del names[0] # print(names) # del names[0] # print(names) vehicles2= ['BMW','Benz','Audi'] vehicles2.append('Maserati') vehicles2.insert(1, 'Mclaren') vehicles2.insert(1, 'Aston Matin') print(vehicles2) print(sorted(vehicles2, reverse=True)) print(vehicles2) # vehicles2.sort(reverse=True) vehicles2.reverse() print(vehicles2) vehicles2.reverse() print(vehicles2) length = len(vehicles2) print(length) places = ['lushan', 'zhangjiajie','aerbeisishan', 'sea', 'jiuzhaigou'] print(places) print(sorted(places)) print(sorted(places, reverse=True)) print(places) places.reverse() print(places) places.reverse() print(places) places.sort() print(places) places.sort(reverse = True) print(places) print(len(places)) print(len(vehicles2)) print(places[-1].title()) names=[] # print(names[-1]) print(len(names))
# bicycles=[' trek ',' cannondale ','redline'] # message= f"My first bicycle was a {bicycles[0].title().strip()}." # print(message) # names = ['stephen', 'eton', 'frank', 'jeremy'] # message = f"hello,{names[0].title()}." # message1 = f"hello,{names[1].title()}." # message2 = f"hello,{names[2].title()}." # message3 = f"hello,{names[3].title()}." # print(message) # print(message1) # print(message2) # print(message3) # vehicles= ['BMW','Benz','Audi'] # message = f"I would like to have a {vehicles[0]}." # print(message) # print(vehicles) # vehicles.append('porsche') # #print(vehicles) # vehicles2 = [] # vehicles2.append('Porsche') # vehicles2.append('Maserati') # vehicles2.insert(1, 'Mclaren') # vehicles2.insert(1, 'Aston Matin') # vehicles2.append(vehicles) # del vehicles2[-1] # poped_vehicles = vehicles2.pop(2) # print(vehicles2) # print(poped_vehicles) # print(f"The last vehicles is {poped_vehicles.title()}") # removed_item = 'Aston Matin' # vehicles2.remove(removed_item) # print(f'\n {removed_item.title()} is removed.') # print(vehicles2) names = ['pig','sheep','cow'] poped_name = 'sheep' names.remove(poped_name) print(f'{poped_name.title()} cannot come.') names.insert(1, 'duck') print(f'\nI have found a big table!') names.insert(0,'rabbit') names.insert(0,'Cat') names.append('Dog') message = f'Please come my house to have a meeting, {names[0].title()}.' message1 = f'Please come my house to have a meeting, {names[1].title()}.' message2 = f'Please come my house to have a meeting, {names[2].title()}.' print(message) print(message1) print(message2) message3 = f'\nPlease come to my house to have a meeting, {names[3].title()}' message4 = f'\nPlease come to my house to have a meeting, {names[4].title()}' message5 = f'\nPlease come to my house to have a meeting, {names[5].title()}' print(message3) print(message4) print(message5) poped_name = names.pop() print(f'Sorry, cannot invite you, {poped_name.title()}') poped_name = names.pop() print(f'Sorry, cannot invite you, {poped_name.title()}') poped_name = names.pop() print(f'Sorry, cannot invite you, {poped_name.title()}') poped_name = names.pop() print(f'Sorry, cannot invite you, {poped_name.title()}') print(f'You are welcome to house still, {names[0].title()}, {names[1].title()}.') del names[0] print(names) del names[0] print(names)
# for value in range(6): # print(value) # numbers= list(range(2,11,2)) # print(numbers) # squares = [] # for value in range(1,11): # squares.append(value**2) # print(squares) # print(sum(squares)) # nums = [value**2 for value in range(1, 11)] # print(nums) # numbers = list(range(1,21, 2)) # for number in numbers: # print(number) # print(min(numbers)) # print(max(numbers)) # numbers = list(range(3, 31, 3)) # for number in numbers: # print(number) # numb3 = [] # for value in range(1, 11): # numb3.append(value**3) # for value in numb3: # print(value) # print(sum(numb3)) numb4 = [value**3 for value in range(1, 11)] print(numb4) print(numb4[-3:]) for number in numb4[-5:]: print(number)
my_foods= ['pizza','falafel','carrot cake'] friend_foods = my_foods[:] their_food=my_foods their_food.append('cannoli') my_foods.append('apple pie') friend_foods.append('orange pie') print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) print(their_food) print("My favorite pizzas are:") for food in my_foods: print(food) print("My friend's favorite pizzas are:") for food in friend_foods: print(food)
#!/usr/bin/env python3 import sys import random from PySide6 import QtCore, QtWidgets, QtGui class MyWidget(QtWidgets.QWidget): def __init__(self): super().__init__() self.hello = ["Hallo Welt", "Hei maailma", "Hola Mundo", "Привет мир"] self.button = QtWidgets.QPushButton("Click me!") self.text = QtWidgets.QLabel("Hello World", alignment=QtCore.Qt.AlignCenter) self.layout = QtWidgets.QVBoxLayout(self) self.layout.addWidget(self.text) self.layout.addWidget(self.button) self.button.clicked.connect(self.magic) @QtCore.Slot() def magic(self): self.text.setText(random.choice(self.hello)) if __name__ == "__main__": app = QtWidgets.QApplication([]) widget = MyWidget() widget.resize(800, 600) widget.show() sys.exit(app.exec_())
demensions = (200, 50) print("Original dimensions:") print(demensions[0]) print(demensions[1]) demensions = (300,600) print("\nModified dimensions:") for demension in demensions: print(demension) foods = ('Dumpling',"Rice","Noodles","Bread",'Egg') print("\nFoods is:") for food in foods: print(food) foods = ('Dumpling',"Cake","Noodles","Bread",'Pizza') print("\nChanged foods is:") for food in foods: print(food)
# m = n = 3 # test = [[0 for i in range(3)] for j in range(3)] # test[2][2]=12 # print("test =", test) # test = [x*x for x in range(1,11)] # print("test =", test) # alien_0 = {'color': 'green', 'points': 5} # # print(alien_0['color']) # # print(alien_0['points']) # print(alien_0) # alien_0['x_position'] = 0 # alien_0['y_position'] = 25 # print(alien_0) # del alien_0['x_position'] # print(alien_0) # favorite_languages = { # 'jen': 'python', # 'sarah': 'c', # 'edward': 'ruby', # 'phil': 'python', # } # favorite_fruit = { # 'ethan': 'apple', # 'jack': 'pear', # } # print(favorite_fruit) # print(favorite_languages) # language = favorite_languages['sarah'].title() # print(f"sarah's favorite language is {language}") # print(f"{favorite_fruit['ethan']}") # print(f"{favorite_fruit['jack']}") # print(f"{favorite_fruit.get('shelly','No this value assigned.')}") # value = favorite_fruit.get('shelly') # print(value) # info = {'first_name': 'liu', 'last name': 'jack', 'age': '41', 'city': 'suzhou'} # print(info['first_name']) # print(info['last name']) # print(info['age']) # print(info['city']) # info = { # 'first_name': 'liu', # 'last name': 'jack', # 'age': '41', # 'city': 'suzhou' # } # for key, value in info.items(): # print(f"\nKey:{key}") # print(f"Value:{value}") favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } # for name, language in favorite_languages.items(): # print(f"{name.title()}'s favorite language is {language.title()}.") # for name in favorite_languages: # print(name.title()) # for name in favorite_languages.keys(): # print(name.title()) # for name in sorted(favorite_languages.keys()): # print(f"{name.title()}, thank you for taking the poll.") # if 'eric' not in favorite_languages.keys(): # print("Eric, please take our poll.") # friends = ['phil', 'sarah'] # for name in favorite_languages.keys(): # print(f"Hi {name.title()}.") # if name in friends: # language = favorite_languages[name].title() # print(f"\t{name.title()}, I see you love {language}!") # print('The following languages have been mentioned:') # for language in set(favorite_languages.values()): # print(language.title()) # languages = {"python", "ruby", "python",'c'} # print(languages) # alien_0 = {'color': 'green', 'points':5} # alien_1 = {'color': 'yellow', 'points':10} # alien_2 = {'color': 'red', 'points':15} # aliens = [alien_0, alien_1, alien_2] # for alien in aliens: # print(alien) aliens = [] for alien_number in range(30): new_alien = {'color': 'green', 'points':5, 'speed':'slow'} aliens.append(new_alien) for alien in aliens[:5]: print(alien) print("...") print(f"Total number of aliens: {len(aliens)}") for alien in aliens[:3]: if(alien['color'] == 'green'): alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 for alien in aliens[:5]: print(alien) print("...") for alien in aliens[:3]: if(alien['color'] == 'green'): alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 elif alien['color'] == 'yellow': alien['color'] = 'red' alien['speed'] = 'fast' alien['points'] = 15 for alien in aliens[:5]: print(alien) print("...")
# car ='subaru' # print("Is car == 'subaru'? I predict Ture.") # print(car == 'subaru') # print("\nIs car =='audi'? I predict False.") # print(car == 'audi') # number = 5 # print("Is number == 6? I think it's False.") # print(number==6) # print("Is number == 5? I think it's True.") # print(number==5) # age=18 # print("Is age>=20? I think it's False.") # print(age>=20) # print("Is age<=20? I think it's Ture") # print(age<=20) # age=18 # print("Is age!= 18? I think it's False.") # print(age != 18) # print("Is age!= 20? I think it's Ture") # print(age!=20) # fruits =['apple', 'orange', 'pear', 'peach'] # print("Is orange in the list fruits? I think it's Ture.") # print('orange' in fruits) # print("Is banana in the list fruits? I predict it's False.") # print('banana' in fruits) # print("Is Apple in the list? I think it's False.") # print("Apple" in fruits) # print("Is Apple in the list? I think it's Ture.") # print("Apple".lower() in fruits) # fruit = "Pear " # print("Pear" != fruit) # print('banana' in fruits and 'apple' in fruits) # print('banana' in fruits or 'apple' in fruits) # print('orange' in fruits and 'apple' in fruits) # print('banana' in fruits or 'berry' in fruits) # print('banana' not in fruits or 'grape' not in fruits) # print('banana' not in fruits and 'grape' not in fruits) # print('apple' not in fruits or 'berry' not in fruits) # print('apple' not in fruits and 'berry' not in fruits) # age =16 # if age>=18: # print("You can go do the execution of test.") # print("Have you registered yet?") # else: # print("You cannot do the test.") # print("Please register to vote as soon as you turn 18!") # requeste_toppings = ['mushrooms','extra chess'] # if 'mushrooms' in requeste_toppings: # print('Adding mushrooms.') # if 'pepperoni' in requeste_toppings: # print('Adding pepperoni.') # if 'extra chess' in requeste_toppings: # print('Adding extra chess.') # print("\nFinished making your pizza!") # alien_color = 'green' # alien_color = 'blue' # if alien_color == 'green': # print('You got 5 points.') # elif alien_color == 'Yellow': # print('You got 10 points.') # elif alien_color == 'red': # print('You got 15 points.') # else: # print('You got 20 points.') # age = 21 # if age < 2: # print('This one is a baby.') # elif age < 4 and age >= 2: # print('This one is a infant.') # elif age < 13 and age >= 4: # print('This one is a child.') # elif age < 20 and age >= 13: # print('This one is a young man.') # elif age < 65 and age >= 20: # print('This one is a adult.') # elif age >= 65: # print('This one is a old man.') # fruits = ['apple', 'pear', 'peach'] # fruit1 = 'apple' # fruit2 = 'pear' # fruit3 = 'peach' # fruit4 = 'orange' # fruit5 = 'grape' # if fruit1 in fruits: # print('You really like apple.') # if fruit2 in fruits: # print('You really like pear.') # if fruit3 in fruits: # print('You really like peach.') # if fruit4 in fruits: # print('You really like orange.') # if fruit5 in fruits: # print('You really like grape.') # user_list = ['Jason', 'admin', 'Jack', 'Peter', 'Sunny'] # # user_list = [] # if user_list: # for user in user_list: # if user == 'admin': # print('Hello admin, would you like to see a status report?') # else: # print('Hello Jaden, thank you for logging in again.') # else: # print('We need to find some users!') current_users = ['Jason', 'admin', 'JACK', 'Peter', 'Sunny'] new_users = ['Kevin', 'Shelly', 'Ray', 'Jack', 'peter'] current_users_lowercase = [user.lower() for user in current_users] # for user in current_users: # current_users_lowercase.append(user.lower()) if current_users_lowercase: for user in new_users: if isinstance(user, str): if user.lower() in current_users_lowercase: print(f'The user name {user} is in use, try another name.') else: print(f'The use name {user} is not in use.') # numbers = list(range(1,10)) # # print(numbers) # for number in numbers: # if number == 1: # print("1st") # elif number == 2: # print('2nd') # elif number == 3: # print('3rd') # else: # print(f'{number}th')
# Save the info of Pizza # pizza = { # 'crust':'thick', # 'toppings':['mushrooms', 'extra cheese'], # } # # print the pizza info # print(f"You ordered a {pizza['crust']}-crust pizza" # r"with the following toppings:\n") # for topping in pizza['toppings']: # print("\t"+topping) # faborite_languages ={ # 'jen': ['python', 'ruby'], # 'sarah': ['c'], # 'edward': ['ruby', 'go'], # 'phil': ['python', 'haskell'], # } # for name, languages in faborite_languages.items(): # if len(languages) < 2: # print(f"\n{name.title()}'s favorite language is:") # else: # print(f"\n{name.title()}'s favorite languages are:") # for language in languages: # print(f"\t{language.title()}") # users = { # 'aeinstein': { # 'first': 'albert', # 'last': 'einstein', # 'location': 'princeton', # }, # 'mcurie': { # 'first': 'marie', # 'last': 'curie', # 'location': 'paris', # }, # } # for username, user_info in users.items(): # print(f"\nUserName: {username}") # full_name = f"{user_info['first']} {user_info['last']}" # location = user_info['location'] # print(f"\tFull name: {full_name.title()}") # print(f"\tLocation: {location.title()}") # jack_info = { # 'first_name': 'zhang', # 'last_name': 'jack', # 'age': '41', # 'city': 'suzhou', # } # mike_info = { # 'first_name': 'ma', # 'last_name': 'mike', # 'age': '32', # 'city': 'shanghai', # } # peter_info = { # 'first_name': 'lu', # 'last_name': 'peter', # 'age': '50', # 'city': 'hangzhou', # } # peoples = [jack_info, mike_info, peter_info] # for people in peoples: # print(f"\nFull name: {people['first_name'].title()} {people['last_name']}") # print(f"His age is {people['age']}") # print(f"He is in {people['city'].title()}") favorite_places = { 'jack': ['huangshan',], 'peter': ['taishan', 'huashan', 'maoshan'], 'mike': ['wuyishan', 'taihangshan'], } for name, places in favorite_places.items(): if len(places) < 2: print(f'\n{name} like place is:') else: print(f'\n{name} like places are:') for place in places: print(f"{place}") cities = { 'suzhou': { 'country': 'china', 'peoples_number': 15000, 'info': 'water city', }, 'chongqing': { 'country': 'china', 'peoples_number': 23000, 'info': 'mountain city', }, 'haerbin': { 'country': 'china', 'peoples_number': 12000, 'info': 'ice city', }, } for city, city_info in cities.items(): print(f"\nCity name is : {city.title()}") print(f"\tThe city is located in {city_info['country'].title()}") print(f"\tThe city people number is {city_info['peoples_number']}") print(f"\tThe fact is {city_info['info'].title()}")
# message = input("Tell me something, and I will repeat it back to you: ") # print(message) # prompt = "If you tell us who you are, we can personalize the messages you see." # prompt += "\nWhat's your first name? " # name = input(prompt) # print(f"\nHello, {name}!") age = input("How old are you? ") print(f"{age}")
height = input("How tall are you, in inches? ") height = int(height) if height <= 48: print("\nYou're tall enough to ride!") else: print("\nYou'll be able to ride when You're a little order.") number = input("Enter a number, and I'll tell you if it's even or odd: ") number = int(number) if number % 2 == 0: print(f"\nThe number {number} is even.") else: print(f"\nThe number {number} is odd.")
# current_number = 1 # while current_number <=5: # print(current_number) # current_number += 1 # unconfirmed_users = ['alice', 'brian', 'candace'] # confimed_users = [] # while unconfirmed_users: # current_user = unconfirmed_users.pop() # print(f"Verifying user: {current_user.title()}") # confimed_users.append(current_user) # print("\nThe following users have been confirmed:") # for confimed_user in confimed_users: # print(confimed_user.title()) # pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] # print(pets) # while 'cat' in pets: # pets.remove('cat') # print(pets) # def greet_user(username): # """显示简单的问候语""" # print(f"Hello, {username.title()}!") # greet_user('jesse') # greet_user('sarah') # def display_message(): # """print your learning""" # print(f"Learning is the function.") # display_message() # def favorite_book(title): # print(f"One of my favorite books is {title.title()}.") # favorite_book("alice in wonderland") #pets.py # def describe_pet(pet_name, animal_type = 'dog'): # """显示宠物信息""" # print(f"\nI have a {animal_type}.") # print(f"My {animal_type}'s name is {pet_name.title()}.") # describe_pet('hamster','harry') # describe_pet('dog', 'willie') # describe_pet(pet_name='willie') # describe_pet('willie') # describe_pet(animal_type ='hamster', pet_name = 'harry') def make_shirt(size = "big", strs = "I love python"): print(f"Your shirt is {size} and the string on it is {strs}.") make_shirt(12, "One know the world must know the energy vibration and frequency.") make_shirt() make_shirt("middle") make_shirt(strs="I love C#") def describe_city(city_name, country = "china"): print(f"{city_name} is in {country}.") describe_city("Suzhu") describe_city("Roma","Greek") describe_city("Beijing")
# def get_formatted_name(first_name, last_name, middle_name=''): # """返回整洁的姓名""" # if middle_name: # full_name = f"{first_name} {middle_name} {last_name}" # else: # full_name = f"{first_name} {last_name}" # return full_name.title() # musician = get_formatted_name('jimi', 'hendrix') # print(musician) # musician = get_formatted_name('jimi', 'hendrix', 'lee') # musician = get_formatted_name('john', 'hooker', 'lee') # print(musician) # def build_person(first_name, last_name, age = None): # """返回一个字典,其中包含有关一个人的信息。""" # person = {'first': first_name, 'last': last_name} # if age: # person['age'] = age # return person # musician = build_person('jimi', 'hendrix', age = 27) # print(musician) # def get_formatted_name(first_name, last_name): # """返回整洁的姓名""" # full_name = f"{first_name} {last_name}" # return full_name.title() # while True: # print("\nPlease tell me your name:") # print("(enter 'q' at any time to quit)") # f_name = input("First name:") # if f_name == 'q': # break # l_name = input("Last name:") # if l_name == 'q': # break # formatted_name = get_formatted_name(f_name, l_name) # print(f"\nHello, {formatted_name}!") # def greet_users(names): # """向列表中的每位用户发出简单的问候""" # for name in names: # msg = f"Hello, {name.title()}!" # print(msg) # usernames = ['hannah', 'ty', 'margot'] # greet_users(usernames) # def print_models(unprinted_designs, completed_models): # """ # 模拟打印每个设计,知道没有未打印的设计为止。 # 打印每个设计后,都将其移到列表completed_models中。 # """ # while unprinted_designs: # current_design = unprinted_designs.pop() # print(f"Printing model: {current_design}") # completed_models.append(current_design) # def show_completed_models(completed_models): # """显示打印好的所有模型。""" # print("\nThe following models have been printed:") # for completed_model in completed_models: # print(completed_model) # unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron'] # completed_models = [] # print_models(unprinted_designs[:], completed_models) # show_completed_models(completed_models) # print(unprinted_designs) # def make_pizza(size, *toppings): # """概述要制作的匹萨""" # print(f"\nMaking a {size}-inch pizza with the following toppings:") # for topping in toppings: # print(f"- {topping}") # make_pizza(16, 'pepperoni') # make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # def build_profile(first, last, **user_info): # """创建一个字典,其中包含我们知道的有关用户的一切。""" # user_info['first_name'] = first # user_info['last_name'] = last # return user_info # user_profile = build_profile('albert', 'einstein', # location='princeton', # field='physics') # print(user_profile) # def make_sandwich(*foods): # print(f"Your sandwich is made by:") # for food in foods: # print(f"- {food}") # make_sandwich('bread', 'cheese') # make_sandwich('salmon', 'bacon', 'egg') # make_sandwich('sausage', 'tomato', 'egg', 'cake') # def build_profile(first, last, **user_info): # """创建一个字典,其中包含我们知道的有关用户的一切。""" # user_info['first_name'] = first # user_info['last_name'] = last # return user_info # user_profile = build_profile('xu', 'luke', # hometown='beijing', # title='manage', # hair='long') # print(user_profile) def make_car(manufacturer, typeN, **car_info): car_info['made_by'] = manufacturer car_info['type'] = typeN return car_info car = make_car('subaru', 'outback', color='blue', tow_package=True) print(car)
# import pizza # pizza.make_pizza(16, 'peppenroni') # pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # from pizza import make_pizza as mp # # make_pizza(16, 'peppenroni') # # make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') # mp(16, 'peppenroni') # mp(12, 'mushrooms', 'green peppers', 'extra cheese') # import pizza as p # p.make_pizza(16, 'peppenroni') # p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese') from pizza import * make_pizza(16, 'peppenroni') make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# class Dog: # """一次模拟小狗的简单尝试。""" # def __init__(self, name, age): # """初始化属性name和age.""" # self.name = name # self.age = age # def sit(self): # """模拟小狗收到命令时蹲下。""" # print(f"{self.name} is now sitting.") # def roll_over(self): # """模拟小狗收到命令时打滚。""" # print(f"{self.name} rolled over!") # my_dog = Dog('willie', 6) # print(f"My dog's name is {my_dog.name}.") # print(f"My dog is {my_dog.age} years old.") # my_dog.sit() # my_dog.roll_over() # your_dog = Dog('Lucy', 3) # print(f"\nYour dog's name is {your_dog.name}.") # print(f"Your dog is {your_dog.age} years old.") # your_dog.sit() # your_dog.roll_over() # class Restaurant: # """餐馆类""" # def __init__(self, name, tp): # self.restaurant_name = name # self.restaurant_type = tp # self.number_served = 0 # def describe_restaurant(self): # print(f"The restaurant name is {self.restaurant_name}.") # print(f"The restaurant type is {self.restaurant_type}.") # def open_restaurant(self): # print(f"The restaurant is opened.") # def set_number_served(self, number): # if number >= self.number_served: # self.number_served = number # else: # print("You cannot roll back the number!") # def increment_served(self, inc_number): # if inc_number >= 0: # self.number_served += inc_number # else: # print("You cannot roll back the number!") # # corner_restaurant = Restaurant('Bruce R', 'Italy') # # print(f"{corner_restaurant.restaurant_name}") # # print(f"{corner_restaurant.restaurant_type}") # # corner_restaurant.describe_restaurant() # # corner_restaurant.open_restaurant() # # beer_restaurant = Restaurant('BeerR', 'Germany') # # beer_restaurant.describe_restaurant() # # bake_restaurant = Restaurant('BakeR', 'Korea') # # bake_restaurant.describe_restaurant() # # sich_restaurant = Restaurant('MalaR', 'China') # # sich_restaurant.describe_restaurant() # su_restaurant = Restaurant('su_bang_cai', 'China') # print(f"There are {su_restaurant.number_served} peoples came here.") # su_restaurant.number_served = 21_505 # print(f"There are {su_restaurant.number_served} peoples came here.") # su_restaurant.set_number_served(28_500) # print(f"There are {su_restaurant.number_served} peoples came here.") # su_restaurant.increment_served(500) # print(f"There are {su_restaurant.number_served} peoples came here.") class User: """用户名""" def __init__(self, first, last, descrb): self.first_name = first self.last_name = last self.describe = descrb self.login_attempts = 0 def describ_user(self): print(f"The {self.last_name} description is {self.describe}.") def greet_user(self): print(f"Hello {self.first_name} {self.last_name}!") def increment_login_attempts(self): self.login_attempts += 1 def reset_login_attempts(self): self.login_attempts = 0 # # user1 = User('Li', 'Mike', 'a honest man') # # user1.describ_user() # # user1.greet_user() # # user2 = User('Xiao', 'Dawei', 'a hansome man') # # user2.describ_user() # # user2.greet_user() # web_user = User('Zhang', 'San', 'a web user') # web_user.increment_login_attempts() # web_user.increment_login_attempts() # web_user.increment_login_attempts() # web_user.increment_login_attempts() # print(web_user.login_attempts) # web_user.reset_login_attempts() # print(web_user.login_attempts) class Car: """模拟汽车""" def __init__(self, make, model, year): """初始化""" self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """返回整洁的描述信息""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """打印里程表""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self, mileage): """设置里程表""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): """将里程表读数增加指定的量""" if miles >= 0: self.odometer_reading += miles else: print("You can't roll back an odometer!") def fill_gas_tank(self): print("Filling gas...") # my_new_car = Car('audi', 'a4', 2019) # print(my_new_car.get_descriptive_name()) # my_new_car.odometer_reading = 23 # my_new_car.read_odometer() # my_new_car.update_odometer(29) # my_new_car.read_odometer() # my_new_car.update_odometer(21) # my_new_car.read_odometer() # my_used_car = Car('subaru', 'outback', 2015) # print(my_used_car.get_descriptive_name()) # my_used_car.update_odometer(21_500) # my_used_car.read_odometer() # my_used_car.increment_odometer(100) # my_used_car.read_odometer() class Battery: """模拟电动车电瓶""" def __init__(self, battery_size=60): """初始化电瓶属性。""" self.battery_size = battery_size def describe_battery(self): """打印电瓶容量消息""" print(f"This car has a {self.battery_size}-kWh battery.") def get_range(self): """打印续航里程""" if self.battery_size == 60: range = 270 elif self.battery_size == 75: range = 338 elif self.battery_size ==100: range = 450 print(f"This car can go about {range} miles on a full charge.") def upgrade_battery(self): """升级电池""" if self.battery_size != 100: self.battery_size =100 class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self, make, model, year): """ 初始化父类的属性。 再初始化电动汽车特有的属性。 """ super().__init__(make, model, year) # self.battery_size = 60 self.battery = Battery() # def describe_battery(self): # """打印描述电瓶容量""" # print(f"This car has a {self.battery_size}-kWh battery.") def fill_gas_tank(self): """电动车没有油箱""" print("This car doesn't need a gas tank!") # my_tesla = ElectricCar('tesla', 'model y', 2021) # print(my_tesla.get_descriptive_name()) # print(my_tesla.odometer_reading) # # my_tesla.describe_battery() # my_tesla.fill_gas_tank() # my_tesla.battery.describe_battery() # my_tesla.battery.get_range() # class IceCreamStand(Restaurant): # """Ice cream class""" # def __init__(self, name, tp, flavors): # """inite the class""" # super().__init__(name, tp) # self.flavors = flavors # def show_flavors(self): # """Show flavers""" # print("There are the following flavers ice cream:") # for flavor in self.flavors: # print(f"- {flavor}") # corner_icecream_stand = IceCreamStand('my_faverate_r', 'ice_cream', ['choclate', 'milk', 'fruit', 'strawberry']) # corner_icecream_stand.show_flavors() # class Admin(User): # """The administrator class""" # def __init__(self, first, last, descrb): # """inite the class""" # super().__init__(first, last, descrb) # self.privileges = ["can add post", "can delete post", "can ban user"] # def show_privileges(self): # print(f"{self.first_name} {self.last_name} has the follow access: ") # for p in self.privileges: # print(f"- {p}") # my_admin = Admin('Lu', 'luke', 'an administrator') # my_admin.show_privileges() upgrede_e_car = ElectricCar('tesla', 'model x', 2021) upgrede_e_car.battery.get_range() upgrede_e_car.battery.upgrade_battery() upgrede_e_car.battery.get_range()
# from class_car import Car, ElectricCar # my_new_car = Car('audi', 'a4', 2019) # print(my_new_car.get_descriptive_name()) # my_new_car.odometer_reading = 23 # my_new_car.read_odometer() # my_tesla = ElectricCar('tesla', 'model s', 2019) # print(my_tesla.get_descriptive_name()) # my_tesla.battery.describe_battery() # my_tesla.battery.get_range() # my_beetle = Car('volkswagen', 'beetle', 2019) # print(my_beetle.get_descriptive_name()) # my_tesla = ElectricCar('tesla', 'roadster', 2019) # print(my_tesla.get_descriptive_name()) # import class_car # my_beetle = class_car.Car('volkswagen', 'beetle', 2019) # print(my_beetle.get_descriptive_name()) # my_tesla = class_car.ElectricCar('tesla', 'roadster', 2019) # print(my_tesla.get_descriptive_name()) # from class_car import ElectricCar as EC # my_tesla = EC('tesla', 'model 3', 2020) # print(my_tesla.get_descriptive_name()) from random import randint, choice # players = ['charles', 'martina', 'michael', 'florence', 'eli'] # first_up = choice(players) # print(randint(1, 6)) # print(first_up) # class Die: # """Die class for roll it""" # def __init__(self, sides = 6): # self.sides = sides # def roll_die(self): # """Print the random number""" # print(randint(1, self.sides)) # die1 = Die() # for num in range(1,11): # die1.roll_die() # die2 = Die(10) # die3 = Die(20) # print("\n") # for num in range(1, 11): # die2.roll_die() # print("\n") # for num in range(1, 11): # die3.roll_die() nums = [1,3,5,9,8,2,6,4,7,0,'r','u','a','l','e'] my_ticket = [] print("The win number of the lottery are: ") for num in range(1,5): win_num = choice(nums) print(f"- {win_num}") my_ticket.append(win_num) loop_num = 0 for win_num in my_ticket: flag = True while flag: random_num = choice(nums) loop_num += 1 if random_num == win_num: flag = False print(f"Loop number is {loop_num}.")
# file_path = '源代码文件/chapter_10/pi_million_digits.txt' # # file_path = '/Projects/PythonAPP/pi_digits.txt' # # file_path = r'D:\Projects\PythonAPP\pi_digits.txt' # with open(file_path) as file_object: # lines = file_object.readlines() # # for line in file_object: # # print(line.rstrip()) # # contents = file_object.read() # # print(contents.rstrip()) # # for line in lines: # # print(line.rstrip()) # pi_string = '' # for line in lines: # pi_string += line.strip() # print(f"{pi_string[:52]}...") # print(len(pi_string)) # birthday = "830302" # if birthday in pi_string: # print("Your birthday appears in the first million ditigs of pi!") # else: # print("Your birthday does not appear in the first million ditigs of pi.") # with open("learning_python.txt") as file_object: # # contents = file_object.read() # # lines = file_object.readlines() # # for line in lines: # # print(line.rstrip()) # for line in file_object: # print(line.rstrip().lower().replace('python', 'C')) # # i = 1 # # while i <= 3: # # i += 1 # # print(contents) # filename = 'programming.txt' # with open(filename, 'a') as file_object: # # file_object.write("I love programming." + str(5689) +"\n") # # file_object.write("I love creating new games.\n") # # file_object.write("I love python.") # file_object.write("I also love finding meaning in large datasets.\n") # file_object.write("I love creating apps that can run in a browser.\n") # try: # print(5/0) # except ZeroDivisionError: # print("You can't divide by zero!") # else: # print("good!") # filename = 'alice.txt' # try: # with open(filename, encoding='utf-8') as f: # contents = f.read() # except FileNotFoundError: # print(f"Sorry, the file {filename} does not exist.") # else: # #计算该文件大致包含多少个单词。 # words = contents.split() # num_words = len(words) # print(f"The file {filename} has about {num_words} words.") # title = "Alice in, Wonderland." # print(title.split()) # def count_words(filename): # """计算一个文件包含多少单词。""" # try: # with open(filename, encoding='utf-8') as f: # contents = f.read() # except FileNotFoundError: # pass # # print(f"Sorry, the file {filename} does not exist.") # else: # words = contents.split() # num_words = len(words) # print(f"The file {filename} has about {num_words} words.") # filename = 'alice.txt' # count_words(filename) # filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] # for filename in filenames: # count_words(filename) # try: # int_value = int('1239f') # except ValueError: # print("The value is not correct.") # else: # print(int_value) # filenames = ['cats.txt', 'dogs.txt'] # for filename in filenames: # try: # with open(filename) as file_object: # lines = file_object.readlines() # except: # pass # # print(f"There is no file {filename}.") # else: # for line in lines: # print(line.rstrip()) # line = "Row, row, row your boat" # print(line.count('row')) # print(line.lower().count('row')) # filename = "alice.txt" # with open(filename, encoding = 'utf-8') as file_object: # # contents = file_object.read() # # print(contents.count('the')) # lines = file_object.readlines() # count_num = 0 # for line in lines: # count_num += line.count('the') # print(count_num) import json numbers = [2,3,5,7,11,13,15] filename = 'numbers.json' with open(filename, 'w') as f: json.dump(numbers, f) with open(filename) as f: numbers = json.load(f) print(numbers)
# import unittest # def get_formatted_name(first, last, middle=''): # """生成简洁的姓名。""" # if middle: # full_name = f"{first} {middle} {last}" # else: # full_name = f"{first} {last}" # return full_name.title() # class NameTestCase(unittest.TestCase): # """测试name_function.py.""" # def test_first_last_name(self): # """能够正确处理像Janis Joplin这样的姓名吗?""" # formatted_name = get_formatted_name('janis', 'joplin') # self.assertEqual(formatted_name, 'Janis Joplin') # def test_first_last_middle_name(self): # """能够正确地处理像Wolfgang Amadeus Mozart 这样的姓名吗?""" # formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus') # self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart') # if __name__ == '__main__': # unittest.main() # def city_function(city_name, country_name, population=0): # # return f"{city_name.title()}, {country_name.title()}" # if population != 0: # return_str = f"{city_name.title()}, {country_name.title()} - population {population}" # else: # return_str = f"{city_name.title()}, {country_name.title()}" # return return_str # class CityTestCases(unittest.TestCase): # """测试函数city_functions.py""" # def test_city_country(self): # """测试city function字符串""" # test_string = city_function('beijing', 'china') # self.assertEqual(test_string, 'Beijing, China') # def test_city_country_population(self): # """测试city country population 字符串""" # test_str = city_function('beijing', 'china', 5000000) # self.assertEqual(test_str, 'Beijing, China - population 5000000') # if __name__ == "__main__": # unittest.main() # while True: # first_name = input("Please input your first name:") # if first_name == 'q': # break # second_name = input("Please input your second name:") # if second_name == 'q': # break # print(f"Your full name is: {first_name} {second_name}") class AnonymousSurvey: """收集匿名调查问卷的答案。""" def __init__(self, question): """存储一个问题,并未存储答案做准备。""" self.question = question self.responses = [] def show_question(self): """显示调查问卷。""" print(self.question) def store_response(self, new_response): """存储单份调查问卷。""" self.responses.append(new_response) def show_results(self): """显示收集到的所有答卷。""" print("survey result:") for response in self.responses: print(f"- {response}") # #定义一个问题, 并创建一个调查。 # question = "What language did you first learn to speak?" # my_survey = AnonymousSurvey(question) # #显示问题并存储答案。 # my_survey.show_question() # print("Enter 'q' at any time to quit.\n") # while True: # response = input("Language: ") # if response =='q': # break # my_survey.store_response(response) # #显示调查结果。 # print("\nThank you to everyone who paticipated in the survey!") # my_survey.show_results() # import unittest # class TestAnonymousSurvey(unittest.TestCase): # """针对AnonymousSurvey类的测试。""" # def setUp(self): # """ # 创建一个调查对象和一组答案,供使用的测试方法使用。 # """ # question = "What language did you first learn to speak?" # self.my_survey = AnonymousSurvey(question) # self.responses = ['Englih', 'Spanish', "Mandarin"] # def test_store_single_response(self): # """测试单个答案会被妥善的存储。""" # # question = "What language did you first learn to speak?" # # my_survey = AnonymousSurvey(question) # # my_survey.store_response('English') # self.my_survey.store_response(self.responses[0]) # self.assertIn(self.responses[0], self.my_survey.responses) # def test_store_three_responses(self): # """测试单个答案会被妥善的存储。""" # # question = "What language did you first learn to speak?" # # my_survey = AnonymousSurvey(question) # # responses = ['Egnlish', 'Spanish', "Mandarin"] # for response in self.responses: # self.my_survey.store_response(response) # for response in self.responses: # self.assertIn(response, self.my_survey.responses) # if __name__ == '__main__': # unittest.main() class Employee: """存储雇员信息""" def __init__(self, first_name, last_name, salary) -> None: """初始化雇员类""" self.first_name = first_name self.last_name = last_name self.salary = salary def give_raise(self, increasement=5000): """加薪函数""" self.salary += increasement import unittest class TestEmployee(unittest.TestCase): """测试雇员类""" def setUp(self) -> None: """创建雇员类,供测试函数使用。""" self.my_employee = Employee('Jin','Jason', 6000) def test_give_default_raise(self): """测试增加默认的薪资。""" self.my_employee.give_raise() self.assertEqual(self.my_employee.salary, 11000) def test_give_custom_raise(self): """测试增加自定义薪资。""" self.my_employee.give_raise(8000) self.assertEqual(self.my_employee.salary, 14000) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import matplotlib import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['STZhongsong'] # Matplotlib中设置字体-黑体,解决Matplotlib中文乱码问题 plt.rcParams['axes.unicode_minus'] = False # 解决Matplotlib坐标轴负号'-'显示为方块的问题 input_values = [1,2,3,4,5] squares = [1, 4,9, 16, 25] plt.style.use('seaborn') fig, ax = plt.subplots() ax.plot(input_values, squares, linewidth=3) ax.set_title("平方数", fontsize=24) ax.set_xlabel("值", fontsize=14) ax.set_ylabel("值的平方", fontsize=14) ax.tick_params(axis='both', labelsize=14) plt.show() print(matplotlib.matplotlib_fname()) print(matplotlib.get_cachedir())