简体   繁体   中英

Check if required variable has been passed

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

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.

Try:

def whatever(n=None):
    if n is None:
        n = input("Enter n:")
    print(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM