首页 > 解决方案 > python中的一个简单测验

问题描述

我正在编写一个 python 代码来用英语和新鲜的方式训练用户,这取决于选项,它会询问英语或法语问题并接受答案,然后它会根据列表检查输入的答案并增加分数,但是在第一个问题,我的代码停止运行

我尝试包含一个 for 循环并使 while 循环成为函数的一部分,但什么也没有

#Python program to drill a student in french
import sys
option = 0
score=0
english_questions=['What is Thank you in French___?', 'What is you are welcome in French___?', 'What is no in French___?', 'What is Pardon in French___?', 'What is yes in French?___?']
french_questions =['What does Merci mean in English___? ', 'What does derien mean in English___?','What does No mean in English___?', 'What does pardon mean in English___?', 'What does oui mean in English___?' ]
french_answers =['merci', 'derien', 'no', 'pardon', 'oui']
english_answers=['thankyou', 'welcome', 'no', 'pardon', 'yes']
number_of_questions = 5
question_number = 0
print('Welcome to English-French Vocabulary Drill')
print('*********************************************')
print('To be drilled in English Press 1')
print('To be drilled in French Press 2')
print('*********************************************')

#a try except block to handle invalid option type
if option not in (1, 2):
     try:
         option=input('Please Enter option:')
     except:
         print('Invalid option, Please enter 1 or 2')

if option == 1:
   questions = english_questions
   answers = french_answers
elif option == 2:
    questions = french_questions
    answers = english_answers
#Function to check answer
def check_answer(user_answer, questions, answers):
    if user_answer in answers:
        print('')
        print('Correct')
        global score
        score +=1 
        global question_number
        question_number +=1
    else:
        print('')
        print('Incorrect, try again')
        global guesses 
        guesses +=1

global number_of_questions
while question_number < number_of_questions: 
    x = questions[question_number]
    user_answer = answers[question_number]
    print('')
    user_answer = input (x + ':')
    print (check_answer(user_answer, x, answers))
    print('')
    print('score : ' +str(score) )

我希望它会打印出每个问题并一个接一个地要求答案,但我得到的是“正确的无分数:0 W:”

标签: pythonpython-3.x

解决方案


在脚本顶部声明并初始化这些变量:

number_of_questions = 0
guesses = 0

然后将选项与字符串进行比较,这是用户输入:

if option == '1':
    questions = english_questions
    answers = french_answers
elif option == '2':
    questions = french_questions
    answers = english_answers

通过这些修复,它无需提升即可运行。


推荐阅读