# 10-4 file_name = 'guest_book.txt' with open(file_name, 'a') as file: while(True): name = input("Please enter your name:") if(name == 'quit'): break file.write(name+ '\n') # 10-5 file_name = 'reasons.txt' with open(file_name, 'a') as file: while True: reason = input("Why do you like programming?") if(reason =='quit'):break file.write(reason+ '\n') # 10-7 while True: try: num_a = int(input("Please enter the first number:")) num_b = int(input("Please enter the second number:")) except ValueError: print("Sorry, please enter a number!") else: print(num_a + num_b)
# 10-11 import json file_name = 'test.txt' with open(file_name,'w') as file: num = input("Please enter your favorite number:") str = "I know your favorite number! It's "+ num + '.' json.dump(str, file) with open(file_name) as file: str_in_json = json.load(file) print(str_in_json)
# 10-13 import json def get_stored_username(): try: file_name = 'username.json' with open(file_name) as file: name = json.load(file) except FileNotFoundError: return None else: return name def get_new_username(): username = input("What is your name?") filename = 'username.json' with open(filename, 'w') as file: json.dump(username, file) return username def greet_user(): username = get_stored_username() if username: ans = input("Is " + username + " your name? Y/N") if ans == 'Y' or ans == '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()