2015-07-03 39 views
0

我如何設置一個全局變量等於用戶在方法中的輸入?例如,我試着做下面的代碼,但它沒有工作。我怎樣才能使一個全局變量等於用戶在Python中的方法內的輸入?

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) 

但是然後我調用該方法時無法更改該變量。例如,如果我也想問用戶的年齡等。

+0

看來你需要[指針](http://stackoverflow.com/questions/1145722/simulating-pointers-in-python) – hoss

回答

0

爲什麼要使用這樣的全局?如果你更清潔和清晰:

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) 
1

爲什麼你不能讓函數返回輸入的字符串?

示例 -

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) 
0

您不能訪問一個全球性的在你想要的方式。如果您希望能夠「選擇」全局你可以這樣做:

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) 
相關問題