好的。这就是我到目前为止所拥有的……#俄语翻译程序
import os
import random
#Asks users if they want to add more vocabulary
word_adder=raw_input("Add more words? If yes, press 1: ")
with open("Russian_study.txt","a") as f:
while word_adder=="1":
word=raw_input("Enter word: ")
translation=raw_input("Word translation: ")
f.write("{0}:{1},/n".format(word,translation))
word_adder=raw_input("Add another word? If yes, press 1: ")
#Checks to see if file exists, if not one is created
with open("Russian_study.txt","a") as f:
pass
os.system('clear')
print("Begin Quiz")
#Begin testing user
with open("Russian_study.txt","r") as f:
from random import choice
question, answer = choice(list(f)).split(':')
result = raw_input('{0} is '.format(question))
print('Correct' if result==answer else ':(')这个程序可以工作,但是,当添加多个条目时,它总是显示不正确。有什么帮助吗?此外,它在一个问题后停止运行,永远不会进入下一个问题……
发布于 2013-05-08 14:32:51
这里有几个问题。
/n而不是\n在循环中第一次执行list(f),它调用f.readlines(),将读取的“指针”移动到文件的末尾。因此,对list(f)的所有后续调用都将返回一个空列表。注意这个隐藏的state.list(f)在它返回的行中包含换行符,并且在任何答案的末尾都有一个逗号。所以answer会得到类似于"word,\n"的东西。在比较answer和result.考虑到所有这些,固定的程序(只需最少的更改)可能如下所示:
import os
import random
#Asks users if they want to add more vocabulary
word_adder=input("Add more words? If yes, press 1: ")
with open("Russian_study.txt","a") as f:
while word_adder=="1":
word=input("Enter word: ")
translation=input("Word translation: ")
f.write("{0}:{1},\n".format(word,translation))
word_adder=input("Add another word? If yes, press 1: ")
#Checks to see if file exists, if not one is created
with open("Russian_study.txt","a") as f:
pass
os.system('clear')
print("Begin Quiz")
#Begin testing user
with open("Russian_study.txt","r") as f:
l = list(f)
from random import choice
while True:
question, answer = choice(l).split(':')
answer = answer[:-2]
result = input('{0} is '.format(question))
print('Correct' if result==answer else ':( ')发布于 2013-05-08 14:48:14
为我工作的代码。感谢你们所有的帮助
导入操作系统随机导入
#Asks users if they want to add more vocabulary
word_adder=raw_input("Add more words? If yes, press 1: ")
with open("Russian_study.txt","a") as f:
while word_adder=="1":
word=raw_input("Enter word: ")
translation=raw_input("Word translation: ")
f.write("{0}:{1},\n".format(word,translation))
word_adder=raw_input("Add another word? If yes, press 1: ")
#Checks to see if file exists, if not one is created
with open("Russian_study.txt","a") as f:
pass
os.system('clear')
print("Begin Quiz")
#Begin testing user
with open("Russian_study.txt","r") as f:
l = list(f)
from random import choice
while True:
question, answer = choice(l).split(':')
answer = answer[:-2]
result = raw_input('{0} is '.format(question))
print('Correct' if result==answer else ':( ')https://stackoverflow.com/questions/16433643
复制相似问题