how to use a raw_input as argument in a function in python 3

Gabriel Cesar picture Gabriel Cesar · Jan 6, 2017 · Viewed 19.2k times · Source

I'm trying to write a simple program with python 3 for practice. What I want to do is draw a function that takes an user input() as argument. I have tried storing the input() in a variable, but everytime I try to proceed the variable calls itself asking for the input(), so it doesn't store anything. I have also tried something like this:

def function(input('give me a '), input('give me b ')):
    # do stuff with the inputs

but it gives syntax error in the parenthesis.

Any idea on how to set a function to use user's input() as arguments?

Answer

elethan picture elethan · Jan 6, 2017

It depends on what you are trying to do. Most likely you want to pass the user input to the function call rather than the definition:

def function(a, b):
    print(a, b)

a = input('give me a ')
b = input('give me b ')

function(a, b)

However, if you want to pass a given user input as the default argument to a function, you could do it like this:

def function(a=input('give me a '), b=input('give me b ')):
    print(a, b)

function()  # prints whatever the user inputted when the file was initially run

The reason your code raises an exception is because the content in the () in a function definition (as opposed to a function call, i.e., function()) is the names of the parameters rather than the arguments passed to the function. You can use input() in this part of the function signature only if you assign it as a default value to be associated with a parameter name, as I did above. This second use case seems pretty strange though, and every time function() is called it will be passed the same arguments as defaults that the user initially entered. Even if that is what you want to do, you should probably do this instead:

input_a = input('give me a ')
input_b = input('give me b ')

def function(a=input_a, b=input_b:
    print(a, b)

function()

Alternatively, if you want to get a different pair of inputs every time the function is called (this actually seems most likely now that I think about it):

def function():
    a = input('give me a ')
    b = input('give me b ')
    print(a, b)