Skip to content
Advertisement

Why do the first two inputs I enter when I run my program repeat in the text file?

I’m trying to make a flash card generator, and I’m having trouble gathering the inputs from the text file. When the program asks the user for the questions and answers, it drops the information into a text file that will be used later, when the user wishes to review the information. However, whenever the program runs for the first time, the first two inputs are repeated twice in the text file.

An example of this bug is like so:

What is the capitol of New York, RochesterWhat is the Capitol of New York, Rochester .

Here is the code I’ve written to achieve my task:

user_inputs = []
f = open('flash_card.txt', 'a')
print('Hello! Welcome to Flash Card Study Helper:)')
create_add = input('Do you wish to create new cards? ')
while create_add == ('yes'):
    question = input('Please type out the question: ')
    answer = input('Please type out the answer: ')
    combined = ','.join(user_inputs)
    f.write(combined+'n')
    user_inputs.append(combined)
    create_add =input('Do you wish to create another card? ')
else:
   print(user_inputs)

Why do my inputs duplicate when written into the file?

Advertisement

Answer

You are tracking ALL of the user’s inputs in user_input, and then writing that to your file every time through the loop. So, first time, you write q1, a1. Next time, you write q1, a1, q2, a2. Next time, you write q1, a1, q2, a2, q3, a3. If you really want to update the file during every loop, you should only write the new stuff:

    q_a = question + ',' + answer
    f.write(q_a+'n')
    user_inputs.append(q_a)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement