我试图创建一个问答程序,在这个程序中,程序从一个文件中询问一个问题,然后比较答案,但是当我写正确的答案时,它仍然告诉我它是错误的。
import random
def Questionnaire():
a=1
i=1
while i <= 10 :
with open("mcq.txt", "r") as r:
list = r.readlines()
questions = random.choice(list)
questans = questions.split(";;")
question, answer = questans[0], questans[1]
print(f"Q{a} - {question}")
a,i=a+1,i+1
ans(answer)
def ans(answer):
mychoice =str(input("What is your answer ?"))
if mychoice != answer :
print(f"Wrong answer, the right one is : {answer} \n")
else :
print("Bravo, it is the right one ! \n")
Questionnaire()在我的第二个函数中,if else语句总是返回False,即使我更改为make != BTW文本页类似于Who was the first president of the USA? A-Trump B-Clinton C-Lincoln D-George Washington;;D,并且它继续这样。
该文件如下所示
Who is the head of the new government in France in 1936? A-Thorez B-Blum C-Daladier D-Pétain ;; B
What is the slogan of the Popular Front? A- “With France, for the French” B- “liberty, equality, fraternity” C- “work, family, homeland” D- “bread, peace, freedom” ;; D
Which party does not make up the Popular Front? A-The Radical Party B-The SFIO C-The National Bloc D-The Communist Party ;; C
What event of 1934 contributed to the creation of the Popular Front? A-The Congress of Tours B-The riots of the leagues C-The Crash of Wall-Street D-The resignation of Clémenceau ;; B
What event is at the origin of the crisis of the 1930s? A-The Russian Revolution B-The Rise of Fascism C-The First World War D-The Wall Street Crash ;; D
Which of these countries is an island? A-France B-Netherlands C-Australia D-Korea ;; C
What is the color of Henri's white horse 4 A-Green B-Red C-Gray D-White ;; D
One byte corresponds to A-1bit B-4 bits C-8 bits D-32 bits ;; C
With 1 byte you can encode A-255 values B-8 values C-16 values D-256 values ;; D
What is Microsoft Windows? A-A type of computer B-An operating system C-A database management system ;; B
The binary system uses the basis A-2 B-10 C-8 D-16 E-None of the above is true. ;; A
In Greco-Roman mythology, the gods gathered on A-Mount Sinai B-Vesuvius C-Mount Olympus ;; C
In Greek mythology, Pegasus is A-A winged horse B-A man with an eagle's head C-A giant ;; A
In what year was François Mitterrand elected President of the French Republic? A-1974 B-1976 C-1981 D-1986 ;; C谢谢
发布于 2021-12-29 09:35:08
修复
这是因为,当使用readlines()时,它会给出一个以\n char结尾的字符串列表,因此答案字符串变成了与A不同的A\n。还有,有时在回信前有一个空格。使用str.strip()将两者都删除
question, answer = questans[0], questans[1].strip()改进
在每次迭代时打开和读取整个文件:在beginning
random.choice上读取一次可以在两个不同的迭代中给出相同的行:使用random.shuffle随机化一次,然后接受order
a和i做相同的操作,保持一个
enumerate和一个问题列表中的一部分只做X问题def Questionnaire(nb_question=10):
with open("test.txt", "r", encoding="utf-8") as r:
values = r.read().splitlines() # don't keep ending \n
random.shuffle(values) # randomize once
for i, questions in enumerate(values[:nb_question], start=1):
question, answer = questions.split(";;")
print(f"Q{i} - {question.strip()}")
ans(answer.strip())https://stackoverflow.com/questions/70517488
复制相似问题