Python Default Parameters

Source: Internet
Author: User

Defining Default Parameters

When defining a function, you can also have default parameters.

For example, the python's own int () function, in fact, there are two parameters, we can both pass a parameter, and can pass two parameters:

>>> Int (' 123 ') 123>>> int (' 123 ', 8) 83

The second argument of the Int () function is the conversion, if not passed, the default is decimal (base=10), and if passed, use the passed in parameters.

As you can see, the function's default parameter is to simplify the call , and you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.

Let's define a function that calculates the n-th square of x:

#coding =gbkdef Power (x,n): If X==0:return ' please reenter: ' Else:return x**nprint (Power (1,3))

  

Assuming the maximum number of squares is calculated, we can set the default value of N to 2:

def power (x, n=2):    s = 1 while    n > 0:        n = n-1        s = s * x    return s

In this way, you do not need to pass in two parameters to calculate the square:

>>> Power (5) 25

Because the parameters of the function match in order from left to right, the default parameters can only be defined after the required parameters:

# Ok:def Fn1 (A, b=1, c=2):    pass# error:def fn2 (a=1, b):    Pass

Python Default Parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.