Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if required variable has been passed

Tags:

python

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

like image 655
Cube. Avatar asked Jul 22 '26 18:07

Cube.


1 Answers

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.

like image 154
Kevin Avatar answered Jul 24 '26 08:07

Kevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!