简体   繁体   中英

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 . 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. How can I do this? I get an error that n hasn't been defined when I write multiples(n,upperLimit=10*n) . I'm running SageMath 9.1, which I believe is based on Python 3.x. Thank you in advance:)

Default values are evaluated when the function is defined, not when it's called. So they can't refer to other parameters, since the parameters don't have a value until the function is called.

Use None as the default, then check for this in the function.

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

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