简体   繁体   English

我如何在gradeAnswers函数中比较数组userResponse和CorrectAnswers。 这是唯一无法正常运行的pary

[英]How can i compare the arrays userResponse and correctAnswers in the gradeAnswers function. It is the only pary not functioning properly

def main():

    correctAnswers = ['B','D','A','A','C',
                      'A','B','A','C','D',
                      'B','C','D','A','D',
                      'C','C','B','D','A']

    userResponse = userAnswers()
    correct = gradeAnswers(correctAnswers, userResponse)
    passFail(correct)


#function to obtain the users input for answers and put in an array
def userAnswers():

    answers = 1

    userResponse = ['','','','','','','','','','',
                    '','','','','','','','','','',]

    for answers in range (20):
            print('What is the answer to number ',\
                answers + 1, '? ',sep='',end='') 
            userResponse[answers] = str(input())


    print(userResponse)
    return userResponse   




#function to calculates the amount of correct answers and displays such
def gradeAnswers(correctAnswers, userResponse):
    correct = 1
    incorrect = 0
    index = 1
    for correct in range (20):

            if userResponse[correct] == correctAnswers[index]:
                index += 1
                correct += 1**




    print('You answered',correct, 'out of 20 questions correctly')

    return correct***


#function to determine and display wether the user passed or failed
def passFail(correct):

    if correct >= 15:
        print('You passed.  Good Job')
    else:
        print('You failed.  Do Better')



main()

One possible way, would be to use pairwise comparison by means of zip method: 一种可能的方式是通过zip方法使用成对比较:

def gradeAnswers(correctAnswers, userResponse):
    correct = 1

    for userAnwser, correctAnwser in zip(userResponse, correctAnswers):
        if userAnwser == correctAnwser:
            correct += 1


    print('You answered',correct, 'out of 20 questions correctly')

    return correct

There are other ways also, like using list comprehension, but I did not want to change your code too much. 还有其他方法,例如使用列表理解,但我不想过多更改您的代码。 Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM