【问题标题】:Python quiz program. Could you help me identify where I've gone wrong? ThanksPython 测验程序。你能帮我找出我哪里出错了吗?谢谢
【发布时间】:2018-03-26 18:12:30
【问题描述】:

这是一个小测验程序,循环 5 次,每次循环都会问一个不同的完全随机的问题。我不断收到一个错误,说 (rand_quiz() ) 函数未定义,尽管我已经定义了它。我想我做错了。你能帮我纠正一下吗?代码如下。

import random
import operator

operators = {
            "+":operator.add,
            "-":operator.sub,
            "*":operator.mul,
            "/":operator.truediv,
            }

questions = 0
star = 0


def star_score():

    while questions <= 4:
        star = star + 1
        return star


    def check_ans():

        if que_ans == que:
            print("Correct! You earned yourself a star.")
            star_score()

        elif que_ans != que:
            print("Wrong! Better luck next time.")


        def rand_quiz():
            rand_num1 = random.randint(9, 999)
            rand_num2 = random.randint(9, 999)

            ops = random.choice(list(operators.keys()))

            que = int(operators[ops](rand_num1, rand_num2))

            print("What is",rand_num1, ops, rand_num2)
            que_ans = input(">>>")

            if que_ans.isdigit():
                check_ans()

            else:
                return("Error! Invalid input.")    


def quiz_loop():

    while questions <= 4:
        rand_quiz()


quiz_loop()

【问题讨论】:

  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
  • 你不能从同一个代码中得到这两个问题。 rand_quiz 未在顶层定义:您已将其埋在 check_ans 中,然后是 star_score
  • 这段代码中有各种使用错误。你已经“超越了你自己的腿”——编码远远超出了你目前的能力。我强烈建议您采用增量编程:一次写几行。测试每个新增功能;在继续之前确保它有效。目前,您在调试 50 行代码时遇到了困难,其中至少存在三个致命错误,每个都必须先修复,然后才能看到任何可识别的结果。请参阅这个可爱的 debug 博客以获取调试帮助。

标签: python python-3.x function random


【解决方案1】:

在python中,缩进非常重要。您已经在缩进级别定义了一些函数。您必须在基本级别定义您的函数。

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2022-01-13
    • 2014-03-01
    • 2017-12-19
    • 1970-01-01
    相关资源
    最近更新 更多