Python编程:从入门到实践(课后习题10)

# 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()

    原文作者:周小馬
    原文地址: https://blog.csdn.net/z120379372/article/details/78027764
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞