问题描述
我是一个初学者,尝试做一个简短的学习练习,我反复提示用户输入他们的名字,并将这些名字保存到 guest_book.txt,每个名字在一个新行中。到目前为止,while 循环总是给我带来麻烦,无法让它们正常工作。
"""Prompt users for their names & store their responses"""
print("Enter 'q' to quit at any time.")
name = ''
while True:
if name.lower() != 'q':
"""Get and store name in guestbook text file"""
name = input("Can you tell me your name?\n")
with open('guest_book.txt','w') as guest:
guest.write(name.title().strip(),"\n")
"""Print greeting message with user's name"""
print(f"Well hello there,{name.title()}")
continue
else:
break
当我省略 with open()
块时它运行完美。
解决方法
以更pythonic的方式:
with open('guest_book.txt','w') as guest:
while True:
# Prompt users for their names & store their responses
name = input("Can you tell me your name?\n")
if name.lower() == 'q':
break
# Get and store name in guestbook text file
guest.write(f"{name.title().strip()}\n")
# Print greeting message with user's name
print(f"Well hello there,{name.title()}")
Can you tell me your name?
Louis
Well hello there,Louis
Can you tell me your name?
Paul
Well hello there,Paul
Can you tell me your name?
Alex
Well hello there,Alex
Can you tell me your name?
q
>>> %cat guest_book.txt
Louis
Paul
Alex
,
首先尝试读取 Python 显示的错误。
TypeError: write() takes exactly one argument (2 given)
接下来你在 if 状态后回答一个名字。我对您的代码进行了一些更改,并打开了代码的开头(感谢 Corralien 的审查):
print("Enter 'q' to quit at any time.")
with open('guest_book.txt','w') as file:
while True:
name = input("Can you tell me your name?").title().strip()
if name.lower() == 'q':
break
if name:
file.write('{}\n'.format(name))
print('Well hello there,{}'.format(name))