![](/img/trans.png)
[英]How to get script to read file, accept user input, and display specific line from user input
[英]How to accept user input from within a function?
我是 Python 的新手。 此代码片段应该定义一个函数 getinput(),它应该接受用户输入并将该值放入变量 stuff 中。 然后我调用该函数,并打印变量 stuff 的值。
def getinput():
stuff = input("Please enter something.")
getinput()
print(stuff)
问题是程序没有按预期工作,我收到错误消息:
NameError: name 'stuff' is not defined
相比之下,没有定义和调用函数,这段代码工作得很好:
stuff = input("Please enter something.")
print(stuff)
我不明白为什么会这样。
请帮忙。 我正在学习 Python 以通过他的学校课程指导我的孩子,我相信我正在使用带有 Python 3.7.11 的 Google Colab。
函数中定义的变量在该函数的范围内是局部的,但是,您可以从函数返回值,这样您就可以像这样执行您想要的操作:
def getinput():
sth = input("Please enter something.")
return sth
stuff = getinput()
print(stuff)
你可以做很多打印stuff
的可能性 -
def getinput():
stuff = input("Please enter something.")
print(stuff)
getinput()
您可以在函数内部打印它并调用它
def getinput():
stuff = input("Please enter something.")
return stuff
print(getinput())
您可以返回的stuff
并把它打印(最佳解决方案)
def getinput():
global stuff
stuff = input("Please enter something.")
getinput()
print(stuff)
或者你可以使用 global 关键字
在 Python 中,有一个变量作用域的概念。 您在函数内创建了一个 stuff 变量,该变量只能在那里使用。 函数之外没有这样的变量。 你可以这样做:
def getinput():
getinput.stuff = input('Please enter something')
getinput()
print(getinput.stuff)
或者你可以从函数返回值:
def getinput():
stuff = input('Please enter something')
return stuff
s = getinput()
print(s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.