簡體   English   中英

為什么我在運行程序時輸入的前兩個輸入會在文本文件中重復?

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

我正在嘗試制作 flash 卡生成器,但我無法從文本文件中收集輸入。 當程序詢問用戶問題和答案時,它會將信息放入一個文本文件中,以便稍后在用戶希望查看信息時使用。 但是,每當程序第一次運行時,前兩個輸入在文本文件中重復兩次。

這個錯誤的一個例子是這樣的:

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

這是我為完成任務而編寫的代碼:

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)

為什么我的輸入在寫入文件時會重復?

您正在跟蹤user_input中的所有用戶輸入,然后每次通過循環將其寫入您的文件。 所以,第一次,你寫 q1, a1。 下一次,你寫 q1, a1, q2, a2。 下一次,你寫 q1, a1, q2, a2, q3, a3。 如果你真的想在每個循環中更新文件,你應該只寫新的東西:

    q_a = question + ',' + answer
    f.write(q_a+'\n')
    user_inputs.append(q_a)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM