简体   繁体   English

Python function 带可选参数

[英]Python function with optional argument

I'm trying to write a function multiples(n,upperLimit) that returns a list with the multiples of a given number n less than or equal to upperLimit .我正在尝试编写一个 function multiples(n,upperLimit)返回一个列表,其中给定数字n的倍数小于或等于upperLimit What I want to do is make upperLimit an optional parameter with a default value of 10n if the user does not specify any other value.我想要做的是,如果用户没有指定任何其他值,则将upperLimit设置为默认值为10n的可选参数。 How can I do this?我怎样才能做到这一点? I get an error that n hasn't been defined when I write multiples(n,upperLimit=10*n) .当我写multiples(n,upperLimit=10*n)时,我得到一个n hasn't been defined 的错误。 I'm running SageMath 9.1, which I believe is based on Python 3.x.我正在运行 SageMath 9.1,我认为它基于 Python 3.x。 Thank you in advance:)先感谢您:)

Default values are evaluated when the function is defined, not when it's called.默认值是在定义 function 时计算的,而不是在调用它时。 So they can't refer to other parameters, since the parameters don't have a value until the function is called.所以它们不能引用其他参数,因为在调用 function 之前参数没有值。

Use None as the default, then check for this in the function.使用None作为默认值,然后在 function 中检查此项。

def multiples(n, upperLimit = None):
    if upperLimit is None:
        upperLimit = 10 * n
    # rest of code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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