[英]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(...))
). 我有一个函数,需要传入一个参数(
whateverName(n)
)。我想检查参数是否确实被传递,如果不是,我想显示一个提示,询问所需的参数应该是( n = int(raw_input(...))
)。 Any ideas how this can be done (note: I'm a rookie in Python)? 有什么想法可以做到这一点(注意:我是Python的新秀)?
Give n
a default value of None, and check for it in the function body. 给
n
一个默认值None,然后在函数体中检查它。
>>> 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. 当然,这意味着即使用户确定
n
是他想要的值,该用户也将无法调用frob(None)
。 But in this particular case, frob
can only successfully handle integers anyway, so the user shouldn't need to call frob(None)
anyway. 但是在这种特殊情况下,
frob
无论如何都只能成功处理整数,因此用户无论如何都不需要调用frob(None)
。
Try: 尝试:
def whatever(n=None):
if n is None:
n = input("Enter n:")
print(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.