简体   繁体   中英

Making a Exponent parameter optional with a default value of 2

Currently I have my power function set up this way:

def power(base,exponent):
"""calculate the base raised to the power exponent"""
if exponent < 0:
    return base**exponent
elif exponent == 0:
    return 1
else:
    tmp = base
    for counter in range (exponent-1):
        tmp *= base
    return tmp

I need to make the exponent an optional parameter with the default value of 2, I'm unsure what I need to do from here any help would be appreciated.

This is how you set optional parameters:

def power(base,exponent=2):

Note that all of optional must be after required ones. You can list by order power(3, 2) , power(3) But in case you have multiple optional parameters, you can specify using name without having to list all power(3, exponent=2) .

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