Reputation: 481
Is it possible to have input as a default value for a function?
For example,
f(x=input('>')):
print(x)
The problem is, it makes me input a value even when I supply an x
value. How would I do this correctly?
Upvotes: 2
Views: 2944
Reputation: 160377
Python will evaluate the default arguments you define for a function, you'll get the prompt during definition either you like it or not. The value entered at the input prompt will then be assigned as the default for x
.
If you want a default value that will use input
if no other meaningful value is provided, use the common idiom involving None
and drop input
in the body of the function, instead:
def f(x=None):
if x is None:
x = input('> ')
print(x)
Now, if you're thinking, I still want to somehow do this with default arguments, then you'll need to create a function that re-creates your function with every invocation:
def f():
def _(x = input('> ')):
print(x)
return _()
I don't see what benefit this would bring other than appeasing your curiosity, though :-)
Upvotes: 4
Reputation: 3859
May be this is what you want.
def f(x=None):
if not x:
x = input('>')
print(x)
Upvotes: 1