如何将全局变量设置为等于用户在方法中的输入?例如,我尝试执行以下代码,但它不起作用。
def ask_question(var, question):
global var
var = str(input(question))
ask_question(name, "what's your name?")
print("Welcome",name)
如果我做这样的事情,它是有效的。
def ask_question(ques):
global name
name = str(input(ques))
ask_question("what's your name?")
print("Welcome",name)
但是在调用该方法时,我无法更改变量。例如,如果我也想询问用户的年龄等,
为什么不能让函数只返回输入的字符串?
示例-
def ask_question(ques):
return str(input(ques))
然后,您可以将返回的字符串以-的形式分配给脚本中的变量
name = ask_question("what's your name?")
print("Welcome",name)
age = ask_question("what's your age?")
print("Your age is ", age)
为什么要使用这样的全局?更干净更清晰如果你:
def ask_question(ques):
return str(input(ques))
name = ask_question("what's your name?")
print("Welcome",name)
age = ask_question("what's your age?")
print("You're this old:",age)
您无法以所需方式访问全局。如果你想能够"选择"全局,你可以做:
def ask_question(var, question):
globals()[var] = str(input(question))
ask_question("name", "what's your name?")
print("Welcome",name)
但我同意其他人的看法,做一些类似的事情会更清楚
def ask_question(question):
return str(input(question))
name = ask_question("what's your name?")
print("Welcome",name)