Python打印未解决的引用

2024-09-30 14:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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)

Tags: orandtoyouhelloinputreturndef
3条回答

n仅在函数main中定义。为了在main之外访问n,您需要从main返回它

def main():
    n = askforname()
    hello(n)
    printchoice()
    kalle()
    return n

并捕获返回值:

n = main()

然后,您可以访问n获取您想要的任何内容:

print(n)

问题是goodye(n)不知道“n”是什么,因为“n”是main()函数的局部变量,其作用域仅限于main。其他函数不会识别这个变量,因为它的作用域不是全局的。它是main()的局部变量。 要访问其他函数中的“n”,可以在调用main()函数之前全局声明它,与其他函数分开。你知道吗

#To Change Global Variable In Funtions Add Global Before The Variable 
def askforname():
    global n = str(input("Please enter your name: "))
    return n

代码中的问题是,在没有首先定义n的情况下,将变量n传递给goodbye(n)函数。由于名称n没有指向任何值,因此它是一个未解决的引用。你知道吗

main()中定义n不会使main()之外的函数可以访问它。这种规则称为范围规则。变量的作用域是可以自由访问的代码区域,包括定义变量的区域。你知道吗

在这种情况下,n的作用域仅限于main()函数。这意味着n对于main()之外的函数不可用;因此n是未定义的,您不能将其(不存在的)值传递给另一个函数。你知道吗

您可以在main()之外定义n,以便其他函数可以访问它:

...

def main():
    hello(n)  # here n references a global variable
    printchoice()
    kalle()

...

# n is defined globally outside main()
n = askforname()
main()
goodbye(n)

相关问题 更多 >