【问题标题】:Python quiz not performing multiple iteration?Python测验不执行多次迭代?
【发布时间】:2015-05-25 16:49:50
【问题描述】:

下面是我的代码。它目前是关于基本学校测验的计划的一部分。我的问题是,当我尝试运行程序时,没有出现任何错误,但它只为用户提供了一个问题。有人可以向我解释为什么会这样。任何帮助深表感谢。

import random, math, sys, re, sqlite3, os
import operator as op

def inputName():
    username=str(input("What is your name?"))
if not re.match("^[A-Za-z ]*$", username) or username=="":
        username=input(str("Please enter a valid name (it must not contain numbers or symbols)."))
        print("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
        username = None
        inputName()
    else:
        return username

def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, num1)

    ops = {
        '+': op.add,
        '-': op.sub,
        '*': op.mul,
        }

    keys = list(ops.keys())
    rand_key = random.choice(keys)
    operation = ops[rand_key]

    correct_result = operation(num1, num2)

    print ("What is {} {} {}?".format(num1, rand_key, num2))
    while True:
            try:
                user_answer = int(input("Your answer: "))
        except ValueError:
            print("Only enter numbers!")
            continue
        else:
            break

    if user_answer != correct_result:
        print ("Incorrect. The right answer is {}".format(correct_result))
       return False
    else:
       print("Correct!")
       return True

    correct_answers = 0
    num_questions = 10

    for i in range(num_questions):
       if test():
            correct_answers +=1

    print("{}: You got {}/{} correct.".format(username, correct_answers,  num_questions))
    return correct_answers

def makeDB():
    if os.path.exists("the_quiz_scores.db.db") == False: #checks if file doesn't exists
        makeFile = open("the_quiz_scores.db.db", "w") #if not, then it will create one
        makeFile.close()
    else:
        return True 

def mainProgram():

    name = inputName()
    maths = test()

mainProgram()

【问题讨论】:

  • 请修正你的缩进
  • 我在移动代码时不断遇到选项卡错误。 @IanAuld
  • 您需要修复您的缩进,因为您的问题很可能是由不良缩进引起的,所以我无法为您编辑您的问题。单击标签下的edit 链接以编辑您的问题。

标签: python mysql python-3.x iteration


【解决方案1】:

在你到达这里之前,你正在点击return 语句,特别是在第 42 和 45 行:

for i in range(num_questions):
       print(range(num_questions))
       if test():
            correct_answers +=1

我建议将此循环移到test() 函数之外,或者将它移到它自己的函数中。一旦你点击了这些返回,你就会退出函数,并且它们下面的任何代码都将永远不会被执行。

类似:

def loop_test(num_questions, username)
    correct_answers = 0
    for _ in range(num_questions):  # it's convention to use _ in a loop where you don't care about the value of the iterator
       if test():
            correct_answers += 1
    print("{}: You got {}/{} correct.".format(username, correct_answers,  num_questions))
    return correct_answers

【讨论】:

  • 非常感谢,当我调用函数时,我是 python 的新手,我想用它的参数调用函数还是让它不带参数。当它在空闲状态下运行时,它表明它被包含在内,然后当我按照告诉它时它被称为未定义。 @IanAuld
  • 您必须在函数定义def foo(a=None, b=5) 中包含任何与此不同的参数。这些是默认参数,除非提供新值,否则将使用指示的值。另一个例外是类方法的self 参数。阅读更多关于参数here
  • 我似乎无法理解这一点。我不确定在这种情况下我应该如何使用参数@IanAuld
  • 例如,如果您想要 10 个问题并且您的用户名存储在变量 name 中,您可以像这样调用函数:loop_test(10, name)。然后,该函数会将这些值替换到适当位置的函数中。一个非常简单的例子是def foo(name): print(name)。尝试使用几个不同的参数运行该函数。
猜你喜欢
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 2011-08-03
  • 2021-01-06
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2020-01-03
相关资源
最近更新 更多