Search code examples
pythonfilewhile-loopbreakcontinue

How do I run while loop that appends a text file?


I'm a beginner trying to do a short learning exercise where I repeatedly prompt users for their name and save those names to guest_book.txt, each name in a new line. So far, while loops are always giving me trouble to get them working properly.

In this case, the program ends when I enter the first name, here's the code:

"""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

It runs perfectly when I omit the with open() block.


Solution

  • In a more pythonic way:

    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