在函数中使用大括号的问题

Problem using curly brackets in functions

answer = int(input("What is {number1} * {number2} ?")) 在没有函数的情况下使用时工作正常,但是当我把它放在函数中时,它会抛出错误 Traceback (most recent call last): File "C:\Users\hjg\Downloads\test4.py", line 17, in <module> answer = eval(input("What is", number1, "*", number2, "?")) NameError: name 'number1' is not defined >>>.

import random, math

def quiz(answer):
    number1 = random.randint(0,9)
    number2 = random.randint(0,9)


    if answer == correctanswer:
        return print("Correct")
    else:
       return print("Incorrect.")


answer = int(input("What is {number1} * {number2} ?"))
correctanswer = number1 * number2


quiz(number1, number2)

这是因为你的范围。 number1 和 number2 在您引用它们的地方不存在。

您必须将变量放在顶部才能使其成为全局变量。

import random, math
number1 = random.randint(0,9)
number2 = random.randint(0,9)

def quiz(answer):
    correctanswer = number1 * number2
    if answer == correctanswer:
        return print("Correct")
    else:
       return print("Incorrect.")

answer = int(input(f"What is {number1} * {number2} ?"))
quiz(answer)

如果您在函数内声明 number1number2,您将只能在函数内访问它们。您可以修改测验函数,以便在其中获取输入,也可以在函数外部初始化变量。

你的函数也只有一个参数,但你传递了两个。您也不需要导入 math。基本算术(加、减、乘、除等)内置于 Python 的核心中,您只需要 math 包即可完成更复杂的事情,例如三角函数或摆弄 Pi。

例如:

import random

def quiz(question, correctanswer):
    answer = int(input(question))
    if answer == correctanswer:
        return print("Correct")
    else:
       return print("Incorrect.")

number1 = random.randint(0, 9)
number2 = random.randint(0, 9)

quiz(f"What is {number1} * {number2} ?", number1 * number2)

我建议您继续阅读 scoping

您对自己的代码有点困惑。 number1 和 number2 应该在函数之外,函数只需要获取 1 个参数。 试试这个:

      import random

      def quiz(answer: int):
      correctanswer = number1 * number2
      if answer == correctanswer:
        return print("Correct")
      else:
        return print("Incorrect.")

      number1 = random.randint(0,9)
      number2 = random.randint(0,9)
      answer = int(input(f"What is {number1} * {number2} ?"))
      quiz(answer)