首页 > 解决方案 > 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.")

标签: pythoninput

解决方案


如果您坚持“退出”是用户键入的最后一件事,只需摆脱 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!")

推荐阅读