本文代码是在jupyter中实现的,仅为了自我督促学习python之用。
10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写
入到文件 guest.txt中。
代码:
name = input("Please enter your name: ") # 提示用户输入姓名
filename = 'guest.txt'
with open(filename, 'w') as file_object1: # 将输入信息储存在创建好的文件"guest.txt"中
file_object1.write(name)
with open(filename)as file_object2: # 打开文件"guest.txt"并将文件中的内容打印出来
lines = file_object2.readlines()
print(lines)
运行结果:
Please enter your name: Li ming
['Li ming']
10-4 访客名单:编写一个 while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件 guest_book.txt 中。确保这个文件中的每条记录都独占一行。
代码:
filename = 'guest_book.txt'
active = True # 循环可以持续进行的标志
with open(filename, 'w') as file_object1:# 将输入信息储存在创建好的文件"guest_book.txt"中
while active:
name = input("\nPlease enter your name: ") # 提示用户输入姓名
file_object1.write(name.title()) # 将输入的姓名写入创建好的文件"guest_book.txt"中
file_object1.write('\n') # 防止不同的记录挤在一排
print("Dear users welcome your arrival!") # 问候语
repeat = input("Would you like to let another person respond ? (yes / no)") # 循环是否持续进行,输入no,直接退出循环
if repeat == 'no':
break
with open(filename)as file_object2: # 打开文件"guest_book.txt"并将文件中的内容打印出来
lines = file_object2.readlines()
print(lines)
运行结果:
Please enter your name: li ming
Dear users welcome your arrival!
Would you like to let another person respond ? (yes / no)yes
Please enter your name: zhan hua
Dear users welcome your arrival!
Would you like to let another person respond ? (yes / no)no
['Li Ming\n', 'Zhan Hua\n']
10-5 关于编程的调查:编写一个 while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。
代码:
filename = 'programming_reason.txt'
active = True # 循环可以持续进行的标志
with open(filename, 'w') as file_object:# 将输入信息储存在创建好的文件"programming_reason.txt"中
while active:
reason = input("\nWhy do you like programming ? : ") # 提示用户输入原因
file_object.write(reason) # 将输入的原因写入创建好的文件"programming_reason.txt"中
file_object.write('\n') # 防止不同的记录挤在一排
if reason == 'no':
break # 结束循环
with open(filename)as file_object1: # 打开文件"programming_reason.txt"并将文件中的内容打印出来
lines = file_object1.readlines()
print(lines)
运行结果:
Why do you like programming ? : It can exercise my thinking ability.
Why do you like programming ? : It allows me to get the pleasure of solving problems.
Why do you like programming ? : It can experience the beauty of computer language.
Why do you like programming ? : no
['It can exercise my thinking ability.\n', 'It allows me to get the pleasure of solving problems.\n', 'It can experience the beauty of computer language.\n', 'no\n']
备注:本节复习题涉及到while循环的知识,不清楚的地方,移步第七章进行复习。