代码具有值错误

时间:2015-07-24 08:36:12

标签: python python-3.x

我需要帮助我的代码一直给我这个错误。 错误是:

ValueError: too many values to unpack (expected 2)

给我错误的一行是这一行:

question , answer = generateQuestions (maxNum)

我无法弄清楚如何修复它。以下是我的代码:

 import random

    def generateQuestions ( maxNum ) :
      ops = ['+','-']
      var1 = random.randrange ( maxNum ) 
      var2 = random.randrange ( maxNum )
      maxNum += 1
      operation = random.choice (ops)
      ques = 'What is' + str(var1) + operation + str(var2) + '?'
      if operation == '+' :
        var1 + var2
      else :
        var1 - var2
      return ques

    difficulty = 0 
    lives = 0
    numofquestion = 0
    correctCount = 0
    while int (difficulty) <= int (0) or int(difficulty) >= int(4) :
        print ('Welcome to the Math Tester')
        print ('Please choose your difficulty')
        difficulty = int (input ( '"1" for Easy \n"2" for Medium \n"3" for Hard\n'))

        if difficulty == 1 :
            print ('Easy Selected, You Have 3 Lives')
            lives , maxNum = 3,10

        elif difficulty == 2 :
            print ('Medium Selected, You Have 2 Lives')
            lives , maxNum = 2,25

        elif difficulty == 3 :
            print ('Hard Selected, You Have 1 Life')
            lives , maxNum = 1,50
        for numofquestion in range (10) :

            print ( 'Question', numofquestion + 1, 'of 10,',lives ,'lives remaining.')
            question , answer = generateQuestions (maxNum)

            print ( question)
            userAns = int (input ())

            if answer == userAns :
                print ('Correct!')
                correctCount += 1

            else :
                print ('Incorrect!')
                lives -= 1


        print ('Result :')
        print ('You scored {} / 10.'.format (correctCount))
        print ('{} % - You {}!' .format (( correctCount / 10)*100, 'pass' if correctCount > 4 else 'fail'))

2 个答案:

答案 0 :(得分:0)

您的generateQuestions函数不返回问题和答案:它只返回问题。你确实计算了该函数中的答案,但你甚至没有将它保存在变量中,更不用说将其保存了。

您需要存储该计算并将其与ques一起返回。

(我故意没有给你实际的代码,因为这显然是功课。)

答案 1 :(得分:0)

错误的原因是您只是从函数中返回问题,尽管您希望它也会返回答案。您的功能的以下更改应该有效:

def generateQuestions ( maxNum ) :
    ops = ['+','-']
    var1 = random.randrange ( maxNum ) 
    var2 = random.randrange ( maxNum )
    maxNum += 1
    operation = random.choice (ops)
    ques = 'What is' + str(var1) + operation + str(var2) + '?'
    if operation == '+' :
        answer = var1 + var2
    else :
        answer = var1 - var2

    return ques, answer