Reputation: 513
I have a function which requires a parameter (whateverName(n)
) to be passed in. I want to check if the parameter was indeed passed and if it wasn't, I want to display a prompt asking what the desired parameter should be (n = int(raw_input(...))
). Any ideas how this can be done (note: I'm a rookie in Python)?
Upvotes: 3
Views: 2874
Reputation: 1929
Try:
def whatever(n=None):
if n is None:
n = input("Enter n:")
print(n)
Upvotes: 0
Reputation: 76194
Give n
a default value of None, and check for it in the function body.
>>> def frob(n=None):
... if n is None:
... n = int(raw_input("Please enter a value:"))
... return n**2 + n
...
>>> frob(23)
552
>>> frob()
Please enter a value:42
1806
Of course, this means that the user will be unable to call frob(None)
even if he's sure that's the value he wants n
to have. But in this particular case, frob
can only successfully handle integers anyway, so the user shouldn't need to call frob(None)
anyway.
Upvotes: 5