python - How to get an input after a with open?
问题描述
Sorry if the title doesn't make much sense or anything else I say, I've only started using Python recently and I am still trying to get used to it. If anyone could help me that'd be great! I want to have it so once the person enters all their details the print with print("Hi "+name+", You've been added to the guest book.") comes up, and then the stop=input("\nPlease enter 'quit'." ) comes after it. I know that the if stop=='quit': break comes before the with open but I'm not sure what the code is so I can have the please enter 'quit' is the very last thing.
filename = 'final_booking.txt'
print("Enter 'quit' when you are finished.")
while True:
name=input("\nWhat is your full name?" )
address=input("\nWhat is your address?" )
email=input("\nWhat is your email address?" )
adult=input("\nHow many Adult tickets have been booked?" )
child=input("\nHow many Child tickets have been booked?" )
total=input("\nWhat is the total cost of your booking?" )
stop=input("\nPlease enter 'quit'." )
if stop=='quit':
break
else:
with open(filename,'a') as f:
f.write(name+address+email+adult+child+total+"\n")
print("Hi "+name+", You've been added to the guest book.")
解决方案
如果您坚持“退出”是用户键入的最后一件事,只需摆脱 else 语句并将它们合并即可。
filename = 'ans.txt'
print("Enter 'quit' when you are finished.")
while True:
name=input("\nWhat is your full name?" )
address=input("\nWhat is your address?" )
email=input("\nWhat is your email address?" )
adult=input("\nHow many Adult tickets have been booked?" )
child=input("\nHow many Child tickets have been booked?" )
total=input("\nWhat is the total cost of your booking?" )
stop=input("\nPlease enter 'quit'." )
if stop=='quit':
with open(filename,'a') as f:
f.write(name+address+email+adult+child+total+"\n")
print("Hi "+name+", You've been added to the guest book.")
break
虽然程序会在之后退出,但我建议您改为制作一个菜单,如下所示:
filename = 'ans.txt'
print("Enter 'quit' when you are finished.")
while True:
choice = input("""type 'one' to register
type 'quit' to exit the program: """)
if choice == "one":
name=input("\nWhat is your full name?" )
address=input("\nWhat is your address?" )
email=input("\nWhat is your email address?" )
adult=input("\nHow many Adult tickets have been booked?" )
child=input("\nHow many Child tickets have been booked?" )
total=input("\nWhat is the total cost of your booking?" )
with open(filename,'a') as f:
f.write(name+address+email+adult+child+total+"\n")
print("Hi "+name+", You've been added to the guest book.")
elif choice == "quit":
break
else:
print("Invalid Input!")
推荐阅读
- javascript - 生成自定义输出链接
- javascript - VueJS 双向数据绑定绑定
- python - 从另一个文件替换一个文件中的文本
- javascript - 作为参数的函数
- dialogflow-es - 谷歌上的操作:conv.device 只返回坐标
- php - 根据 Woocommerce 3 中的总金额自动完成处理订单
- android - 如何查找目录中的文件数?
- reactjs - 在像 Instagram 这样的延迟加载 React 网站上,我应该使用哪个事件处理程序进行 DOM 操作?
- spring-mvc - 从 Bean 的名称和属性的名称转换为 JSP 中的属性
- python - Python 中的 HLS Live Stream API 从磁盘提供文件