10-3 访客 :编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
代码:
filename = 'guest.txt'
guest_name = input("Please input your name: ")
with open(filename, 'w') as file_object:
file_object.write(guest_name)
结果:(生成文本)
Tom
10-4 访客名单 :编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。
代码:
filename = 'guest.txt'
guest_name = input("Please input your name: (input 'q' to quit)")
while guest_name!='q':
with open(filename, 'a') as file_object:
file_object.write(guest_name + '\n')
guest_name = input("Please input your name: (input 'q' to quit)")
结果:(输入Tom, Tim)
Tom
Tim
10-6 加法运算 :提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
代码:
a = input("Please input the first number: ")
b = input("Please input the second number: ")
try:
a=int(a)
b=int(b)
except ValueError:
print("Sorry, the type of txt can't be calculated.")
else:
c= a+b
print(c)
结果:
(输入是3,4)
7
(输入是3,da)
Sorry, the type of txt can't be calculated.
10-7 加法计算器 :将你为完成练习10-6而编写的代码放在一个while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。
代码:c=0
i=0
while i<2:
a = input("Please input the second number: ")
try:
a=int(a)
except ValueError:
print("Sorry, the type of txt can't be calculated.")
else:
i+=1
c+=a
print(c)
结果:
Please input the second number: 3
Please input the second number: da
Sorry, the type of txt can't be calculated.
Please input the second number: 1ad2
Sorry, the type of txt can't be calculated.
Please input the second number: 31
34
10-8 猫和狗 :创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行。
代码:def OpenFile(filename):
try:
with open (filename) as file_object:
line = file_object.readlines()
except FileNotFoundError:
print("Sorry, the file "+filename+" can't be found.")
else:
for line_ in line:
print(line_.rstrip())
filename = "cat.txt"
OpenFile(filename)
filename = "dog.txt"
OpenFile(filename)
结果:
(文件不在)
cat1
cat2
cat3
Sorry, the file dog.txt can't be found.
(文件在文件夹中)
cat1
cat2
cat3
dog1
dog2
dog3
10-12 记住喜欢的数字 :将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。
代码:
import json
def get_stored_number():
filename="user.json"
try:
with open(filename) as f_obj:
number = json.load(f_obj)
except FileNotFoundError:
return None
else:
return number
def greet_user():
number = get_stored_number()
number = number
if number:
print("The number you like is: " + str(number))
else:
number = input("Please input the number you like: ")
filename = "user.json"
with open(filename,"w") as f_obj:
json.dump(number,f_obj)
print("We'll remember the number you like when you come back!")
greet_user()
结果:
(文件不存在时)
Please input the number you like: 8
We'll remember the number you like when you come back!
(存储数字后)
The number you like is: 8