我是python的绝对初学者,我试图理解为什么最后一行行不通。PyCharm声明“n”是一个未解决的引用,我确保函数返回字符串输入。是线路本身的问题还是功能的问题?你知道吗
def askforname():
n = str(input("Please enter your name: "))
return n
def printchoice():
print("You are starving and go down to the kitchen.")
print("You are now confronted with an eon defining choice, spaghetti or lasagna")
def hello(n):
print("Hello " + n + "!")
def choiceone():
choicelasagna = str(input("Type \"Lasagna\" to pick lasagna and type \"Spaghetti\" to pick spaghetti: "))
return choicelasagna
def kalle():
ch = choiceone()
if ch == "Lasagna" or "lasagna":
print("You cooked some warm lasagna and enjoyed it")
else:
print("You cooked some spaghetti and enjoyed it")
def main():
n = askforname()
hello(n)
printchoice()
kalle()
def goodbye(n):
print("Goodbye" + n)
def request():
print("")
main()
goodbye(n)
n
仅在函数main
中定义。为了在main
之外访问n
,您需要从main
返回它并捕获返回值:
然后,您可以访问
n
获取您想要的任何内容:问题是goodye(n)不知道“n”是什么,因为“n”是main()函数的局部变量,其作用域仅限于main。其他函数不会识别这个变量,因为它的作用域不是全局的。它是main()的局部变量。 要访问其他函数中的“n”,可以在调用main()函数之前全局声明它,与其他函数分开。你知道吗
代码中的问题是,在没有首先定义
n
的情况下,将变量n
传递给goodbye(n)
函数。由于名称n
没有指向任何值,因此它是一个未解决的引用。你知道吗在
main()
中定义n
不会使main()
之外的函数可以访问它。这种规则称为范围规则。变量的作用域是可以自由访问的代码区域,包括定义变量的区域。你知道吗在这种情况下,
n
的作用域仅限于main()
函数。这意味着n
对于main()
之外的函数不可用;因此n
是未定义的,您不能将其(不存在的)值传递给另一个函数。你知道吗您可以在
main()
之外定义n
,以便其他函数可以访问它:相关问题 更多 >
编程相关推荐