# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/20 from _for_ex import pt_title pt_title('EX 5 - 8 & 9') # EX 5-8 users = ['jack', 'stven', 'mary', 'admin', 'oliver'] # users = [] # for ex 5-9 if users: for user in users: if user == 'admin': print("Hello " + user.title() + ", would you like to see a status report?") else: print("Hello " + user.title() + ", thank you for logging in again.") else: print("We need to find some users!") # EX 5 - 9 pt_title('EX 5 - 10') current_users = ['jack', 'stven', 'mary', 'admin', 'oliver', 'lee', 'wesley'] new_users = ['mary', 'oliver', 'wesley', 'frank', 'wesley', 'lemon'] for new_user in new_users: if new_user.lower() in current_users: print("The username " + new_user.title() + " already exists and cannot be created.") else: print("The new username " + new_user.title() + " are created!")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/22 from _for_ex import pt_title pt_title('favorite_languages.py'.upper()) # def get_languages(name): # print(name.title() + "'s favorite language is " + # favorite_languages[name].title() + ".") # favorite_languages = { # 'jen': 'python', # 'sarah': 'c', # 'edward': 'ruby', # 'phil': 'python', # } # for n in favorite_languages: # get_languages(n) # pt_title("new favorite languages".title()) # friends = ['phil', 'sarah'] # for name in favorite_languages.keys(): # print(name.title()) # if name in friends: # print(" Hi " + name.title() + ", I see your favorite language is " + # favorite_languages[name] + "!") # if 'erin' not in favorite_languages.keys(): # print("Erin, please take our poll!\n")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/23 from _for_ex import pt_title pt_title('confirmed_users.py'.upper()) # 首先,创建一个待验证用户列表 # 和一个用于存储已验证用户的空列表 unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] # 验证每个用户,直到没有未验证用户为止 # 将每个经过验证的列表都移到已验证用户列表中 while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: "******"\nThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/24 from _for_ex import pt_title pt_title('greeter.py'.upper()) def get_formatted_name(first_name, last_name): """返回整洁的姓名""" full_name = 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("\nHello, " + formatted_name + "!")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/19 from _for_ex import pt_title pt_title('banned_user.py') banned_users = ['andrew', 'carolina', 'david'] user = '******' if user not in banned_users: print(user.title() + ", you can post a response if you wish.")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/24 from _for_ex import pt_title pt_title('EX 7 - 8') sandwich_orders = ['培根三明治', '鸡蛋三明治', '火腿三明治'] finished_sandwiches = [] while sandwich_orders: sandwich_order = sandwich_orders.pop() finished_sandwiches.append(sandwich_order) print("我正在制作你的" + sandwich_order + "。") print("\n--- Finished Sandwiches ---") for finished_sandwiche in finished_sandwiches: print(finished_sandwiche + "已经制作完成。")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/26 from _for_ex import pt_title from name_function import get_formatted_name pt_title('names.py'.upper()) print("Enter 'q' at any time to quit.") while True: first = input("\nPlease give me a first name: ") if first == 'q': break last = input("\nPlease give me a last name: ") if last == 'q': break formatted_name = get_formatted_name(first, last) print("\tNeatly formatted name: " + formatted_name + ".")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/23 from _for_ex import pt_title pt_title('parrot.py'.upper()) # message = input("Tell me something, and I will repeat it back to you: ") # print(message) # name = input("Please enter your name: ") # print("Hello, " + name.title() + "!") # prompt = "If you tell us who you are, we can personalize the message you see." # prompt += "\nWhat is your first name? " # name = input(prompt) # print("Hello, " + name.title() + "!") prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " message = "" active = True while active: message = input(prompt) if message.lower() != 'quit': print(message.title()) else: active = False
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/23 from _for_ex import pt_title pt_title('pets.py'.upper()) pets = ['goldfish', 'dog', 'cat', 'dog', 'cat', 'rabbit', 'cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(sorted(set(pets)))
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/26 from _for_ex import pt_title pt_title('survey.py'.upper()) class AnonymousSurvey(): """收集匿名调查问卷的答案""" def __init__(self, question): """存储一个问题,并为存储答案做准备""" self.question = question self.responses = [] def show_question(self): """显示调查问卷""" print(self.question) def store_response(self, new_responses): """存储单份调查卷""" self.responses.append(new_responses) def show_results(self): """显示收集到的所有答卷""" print("Survey results:") for response in self.responses: print('- ' + response)
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/24 from _for_ex import pt_title pt_title('user_profile.py'.upper()) def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print(user_profile)
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/22 from _for_ex import pt_title pt_title('aliens.py'.upper()) # 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[0:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['points'] = 10 alien['speed'] = 'medium' elif alien['color'] == 'yellow': alien['color'] = 'red' alien['points'] = 15 alien['speed'] = 'fast' for alien in aliens[:10]:
# -*- coding: utf-8 -*- # cretae by o.c. 20-18/7/24 from _for_ex import pt_title pt_title('mountain_poll.py'.upper()) responses = {} # 设置一个标志,指出调查是否继续 polling_active = True while polling_active: # 提示输入被调查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") # 将答卷存储在字典中 responses[name] = response # 看看是否还有人要参与调查 repeat = input("Would you like to let another person respond? (yes/ no) ") repeats = ['n', 'no'] if repeat.lower() in repeats: polling_active = False # 调查结束,显示结果 print("\n--- Poll Results ---") for name, response in responses.items(): print(name.title() + " would like to climb " + response.title() + ".")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/26 import unittest from _for_ex import pt_title from survey import AnonymousSurvey pt_title('test_survey.py'.upper()) class TestAnonymousSurvey(unittest.TestCase): """针对AnonymousSurvey类的测试""" def setUp(self): """创建一个调查对象和一组答案,供使用的测试方法使用""" question = "What language did you first learn to speak?" self.my_survey = AnonymousSurvey(question) self.responses = ['English', 'Spanish', 'Mandarin'] def test_store_single_response(self): """测试单个答案会被妥善地存储""" self.my_survey.store_response(self.responses[0]) self.assertIn(self.responses[0], self.my_survey.responses) def test_store_three_response(self): """测试三个答案会被妥善地存储""" for response in self.responses: self.my_survey.store_response(response) for response in self.responses: self.assertIn(response, self.my_survey.responses) unittest.main()
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title from pizza import make_pizza as mp pt_title('making_pizzas.py'.upper()) mp(16, 'pepperoni') mp(12, 'mushrooms', 'green peppers', 'extra cheese')
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/23 from _for_ex import pt_title pt_title('counting.py'.upper()) # current_number = 1 # while current_number <= 5: # print(current_number) # current_number += 1 current_number = 0 while current_number < 100: current_number += 1 if current_number % 10 == 0: print() if current_number % 2 == 0: continue print(current_number, end='\t') print()
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/20 from _for_ex import pt_title pt_title('alien.py') # alien_0 = {'color': 'green', 'points': 5} # print(alien_0['color']) # print(alien_0['points']) # new_points = alien_0['points'] # print("You just earned " + str(new_points) + " points!") # alien_0['x_position'] = 0 # alien_0['y_position'] = 25 # print(alien_0) # pt_title('new line') # alien_0 = {} # alien_0['color'] = 'green' # alien_0['points'] = 5 # print("The alien is " + alien_0['color'] + ".") # alien_0['color'] = 'yellow' # print("The alien is now " + alien_0['color'] + ".") # print(alien_0) alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'} print("Original x-position: " + str(alien_0['x_position']))
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/22 from _for_ex import pt_title pt_title('many_users.py'.upper()) users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', } } for username, user_info in users.items(): print("\nUsername: "******" " + user_info['last'] location = user_info['location'] print("\tFull name: " + full_name.title()) print("\tLocation: " + location.title())
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/24 from _for_ex import pt_title pt_title('EX 8 - 1') def display_message(): print("I study function.") display_message() # EX 8-2 pt_title('EX 8 - 2') def favorite_book(title): print("One of my favorite books is " + title) favorite_book("Alice in Wonderland")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/24 from _for_ex import pt_title pt_title('greet_users.py'.upper()) def greet_users(names): for name in names: msg = "Hello, " + name.title() + "!" print(msg) username = ['hannah', 'ty', 'margot'] greet_users(username)
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/24 from _for_ex import pt_title pt_title('EX 7 - 10') places = {} polling_active = True while polling_active: name = input("What is your name? ") where = input( "If you could visit one place in the world, where would you go? ") places[name] = where respond = input("Would you like to let another person respond? (yes/ no) ") if respond.lower() in ['n', 'no']: polling_active = False print("\n--- Poll Results ---") for name, where in places.items(): print(name.title() + "'s dream vacation destination is " + where.title() + ".")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title pt_title('EX 10 - 1') # EX 10-1 filename = 'E:/learnPython/Python编程_从入门到实践/learning_python.txt' with open(filename) as file_object: print(file_object.readlines()) print() file_object.seek(0) for line in file_object.readlines(): print(line, end='') print() file_object.seek(0) lines = file_object.readlines() for line in lines: print(line, end='')
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title pt_title('word_count.py'.upper()) def count_words(filename): try: with open(path + filename, encoding='utf-8') as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.") path = './/_txts//' filenames = [ 'alice_in_wonderland.txt', 'maupassant.txt', 'hints_on_child-training.txt', 'limitations.txt', 'hideline.txt' ] for filename in filenames: count_words(filename)
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/26 from _for_ex import pt_title import json pt_title('EX 10 - 13') def get_stored_username(): """如果存储了用户,就获取他""" filename = './/_jsons//username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username def get_new_username(): """提示用户输入用户名""" filename = './/_jsons//username.json' username = input("What is your name? ") with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username def greet_user(): """问候用户,并指出其名字"""
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/20 from _for_ex import pt_title pt_title('toppings.py') available_toppings = [ 'mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese' ] requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print("Adding " + requested_topping + ".") else: print("Sorry, we don't have " + requested_topping + ".") print("\nFinished making your pizza!")
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title # EX 8-12 # 三明治 sandwich 食材 ingredients 描述 describe pt_title('EX 8 - 12') def made_sandwich(*ingredients): print("\n--- Now making your sandwich ---") for ingredinet in ingredients: print("- " + ingredinet) made_sandwich('ham 火腿', 'eggs 鸡蛋', 'sausage 香肠') made_sandwich('eggs 鸡蛋', 'cheese 芝士') made_sandwich('bacon 培根', 'eggs 鸡蛋', 'cheese 芝士', 'ham 火腿') # EX 8-13 pt_title('EX 8 - 13') def build_profile(first, last, **user_info): profile = {} profile['first_name'] = first profile['last_name'] = last for key, value in user_info.items(): profile[key] = value return profile
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/26 from _for_ex import pt_title from survey import AnonymousSurvey pt_title('language_survey.py'.upper()) question = "What language did you first learn to speak?" my_survey = AnonymousSurvey(question) my_survey.show_question() print("Entry '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 participated in the survey!") my_survey.show_results()
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title pt_title('EX 10 - 3') # EX 10-3 filename = './/_txts//guest.txt' user_name = input("Please enter your name: ") with open(filename, 'a') as file_object: file_object.write(user_name + "\n")
from _for_ex import pt_title my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') # print("My favorite foods are:") # print(my_foods) # print("\nMy friend's favorite foods are:") # print(friend_foods) # 4-10 pt_title('EX 4 - 10') print("The full items in the list are:") print(my_foods) print("\nThe first three items in the list are:") print(my_foods[:3]) print("\nThe items from the middle of the list are:") print(my_foods[1:4]) print("\nThe last three items in the list are:") print(my_foods[-3:]) # 4-11 pt_title('EX 4 - 11') pizzas = ['seafood pizza 海鲜披萨', 'cheese pizza 芝士披萨'] friend_pizzas = pizzas[:]
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title pt_title('EX 10 - 4') filename = ".//_txts//guest_book.txt" with open(filename, 'a') as file_object: while True: print("\n--- Please enter your name ---") print("(enter 'q' to quit) ") guest_name = input("> ") if guest_name.lower() == 'q': break else: print("\nHello " + guest_name.title() + ".") file_object.write(guest_name.title() + "\n")