Python程式設計:從入門到實踐(課後習題10)
阿新 • • 發佈:2019-01-08
# 10-6 加法運算 first_number = input("First number: ") second_number = input("Second number: ") try: add = int(first_number) + int(second_number) except ValueError: print("You must enter digits!!!") else: print(add) # 10-7 加法計算器 print("Please enter two digits, I will add the two numbers.") print("Enter 'q' to quit.") while True: first_number = input("First number: ") if first_number == 'q': break second_number = input("Second number: ") try: add = int(first_number) + int(second_number) except ValueError: print("You must enter digits!!!\n") else: print(add) # 10-8 貓和狗 filename_cat = 'd:/cats.txt' filename_dog = 'd:/dogs.txt' with open(filename_cat) as cat: cats = cat.read() print(cats) with open(filename_dog) as dog: dogs = dog.read() print(dogs) cats.close() dogs.close() try: with open(filename_cat) as cat: cats = cat.read() except FileNotFoundError: print(filename_cat + " has no exsit.") else: print(cats) # 10-9 沉默的貓和狗 try: with open(filename_cat) as cat: cats = cat.read() except FileNotFoundError: pass else: print(cats) #10-10 常見單詞 filename = 'd:/gutenberg.txt' try: with open(filename) as gutenberg: gu_read = gutenberg.read() splitx = gu_read.split() except FileNotFoundError: print(filename_cat + " has no exsit.") else: counts = splitx.count('the') print(counts) # 10-11 喜歡的數字 import json filename = 'numbers.json' numbers = input("Enter a number you like: ") with open(filename, 'w') as f_obj: json.dump(numbers, f_obj) with open(filename) as f_obj: numbers = json.load(f_obj) print("I know your favorite number! It's " + str(numbers) + ".") # 10-12 記住喜歡的數字 import json filename = 'numbers.json' try: with open(filename) as f_obj: numbers = json.load(f_obj) except FileNotFoundError: numbers = input("Enter a number you like: ") with open(filename, 'w') as f_obj: json.dump(numbers, f_obj) print("I remember this number you like.") else: print("I know your favorite number! It's " + str(numbers) + ".") #10-13驗證使用者 import json def get_stored_username(): filename = '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(): username = input("What is your name? ") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return username def greet_user(): username = get_stored_username() if username: print("Is your name this: " + username + "?") yn = input("Enter 'y' is yes, 'n' is no. ") if yn == 'y': print("Welcome back " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!") else: username = get_new_username() print("We'll remember you when you come back, " + username + "!") greet_user()