-1

I am working on a Python 3 program that gets string data from the program user and then writes that data to a text file. An another program that reads the data from a file and then displays that data.

The requirements are that both programs will use loops. Program #1 should use the signal QUIT to stop running. Program #2 should run until all of the data is extracted from the file.

I thought I had an understanding of reading/writing to text files in python but I'm completely stumped on this and how to run a loop that will keep going until the signal QUIT. I tried a for loop but that didn't work out so I'm assuming I would use a while loop but not sure how to make that work.

The outlook is expected to the look like the below:

Program #1 Enter a file name: test.txt Enter a string: Once upon a time Enter a string: In the west Enter a string: QUIT

Program #2 Enter a file name: test.txt Once upon a time In the west

I'm really stuck on this so if anyone could help out that would be amazing.

Sorry here is the code I have:

tf = open("test.txt", "w")
a = input("Enter a string: ")
while a != "QUIT":
    print(input("Enter a string: ")
    if a == "QUIT":
          break
    
Ejones222
  • 29
  • 7

1 Answers1

1

To stop taking input, we required the latest line to be equal to "QUIT". In your code,a is not modified after definition, since all subsequent inputs are not stored at all. Instead, we must update a for each input:

tf = open("test.txt", "w")
a = input("Enter a string: ")
while a != "QUIT":
    # Current a is not "QUIT"
    # Write a to tf...
    a = input("Enter a string: ")

Also, there's redundancy in breaking out of the loop when it already has the same condition for running. It can be avoided by changing the order of input and processing inside the loop (as above).

ankurbohra04
  • 432
  • 5
  • 12