0

How can i set a global variable to equal a user's input within a method? For example, I tried doing the following code but it does't work.

def ask_question(var, question):
    global var
    var = str(input(question))

ask_question(name, "what's your name?")
print("Welcome",name)

If I do something like this it works.

def ask_question(ques):
    global name
    name = str(input(ques))

ask_question("what's your name?")
print("Welcome",name) 

but then i can't change the variable when calling the method. For example if I also want to ask the user's age etc.

pupa
  • 71
  • 9
  • Seems you need [pointers](http://stackoverflow.com/questions/1145722/simulating-pointers-in-python) – hoss Jul 03 '15 at 15:26

3 Answers3

1

Why cannot you make the function just return the inputted string?

Example -

def ask_question(ques):
   return str(input(ques))

Then you can assign the returned strings to the variables in your script as -

name = ask_question("what's your name?")
print("Welcome",name) 
age = ask_question("what's your age?")
print("Your age is ", age)
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

Why use a global like that? Much cleaner and clearer if you:

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

You cannot access a global in the way you want. If you want to be able to "select" the global you could do:

def ask_question(var, question):
    globals()[var] = str(input(question))

ask_question("name", "what's your name?")
print("Welcome",name)

But I agree with the others that it would be much more clear to do something like:

def ask_question(question):
    return str(input(question))

name = ask_question("what's your name?")
print("Welcome",name) 
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72