猿问

在定义的函数中定义变量时出错(Python)

考虑以下代码(我在运行时收到名称错误)


item = input("What food???")

def itemcheck():

    if item == "chex":

        cereal = "Yummy"

    else:

        cereal = "Yuck!"


itemcheck()

print(cereal)

错误是未定义名称“谷物”。我犯了什么错误/我该如何解决?在您自己的函数中定义变量的正确方法是什么?


婷婷同学_
浏览 285回答 3
3回答

烙印99

您的代码应该更加优化。你可以试试这个:def itemcheck():    if item == "chex":        return "Yummy"    else:        return "Yuck!"item = input("What food???")cereal = itemcheck()print(cereal)您在cereal函数内部定义,而不是在全局范围内定义。这就是您无法cereal在函数之外访问的原因。

斯蒂芬大帝

使用全局变量在函数内部定义的变量是该函数的局部变量。但是,如果将其声明为全局变量,则可以在函数外部访问它。item = input("What food???")def itemcheck():    global cereal    if item == "chex":        cereal = "Yummy"    else:        cereal = "Yuck!"itemcheck()print(cereal).使用返回语句您可以创建一个 return 语句,该语句指定要传递回调用该函数的代码的值。item = input("What food???")def itemcheck():    if item == "chex":        return "Yummy"    else:        return "Yuck!"print(itemcheck())

LEATH

item = input("What food???")def itemcheck():    if item == "chex":        cereal = "Yummy"    else:        cereal = "Yuck!"    return cerealcereal = itemcheck()print(cereal)您没有从函数中返回谷物。由于在函数中声明了谷物,除非您从函数中返回它,否则在函数完成调用后它不存在。所以你需要在函数退出之前返回它。
随时随地看视频慕课网APP

相关分类

Python
我要回答