确定。所以这就是我到目前为止...... #Russian Translation Program
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 ':(')
此程序有效,但是当添加多个条目时,它始终显示不正确。有帮助吗?此外,它在一个问题后停止运行,永远不会到达下一个问题....
答案 0 :(得分:1)
这里有几个问题。
/n
\n
而不是f.write("{0}:{1},/n"...
当您第一次在循环中执行list(f)
时,它会调用f.readlines()
,将读数“指针”移动到文件的末尾。因此,对list(f)
的所有后续调用都将返回一个空列表。小心这个隐藏的状态。
list(f)
在其返回的行中包含换行符号,并且在任何答案结尾处都有逗号。因此answer
会得到类似"word,\n"
的内容。在将answer
与result
进行比较之前,您必须删除这两个字符。
在第一个问题之后停止运行,因为你在提问部分没有循环。
此外,Python3中没有raw_input
,只有input
。
考虑到所有这些,固定程序(变化很小)可能如下所示:
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 ':( ')
答案 1 :(得分:0)
适用于我的代码。感谢所有帮助人员
导入操作系统 随机导入
#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 ':( ')