Python Basics (iii)

Source: Internet
Author: User
Tags function definition

Built-in functions

Built-in functions will check the parameters

1 Print (ABS (-890)) # Seek absolute value 2 Print (Max (32, 63, 52342, 54)) # To find the maximum value 3 # type conversion function 4 Print (int (89.23)) 5 Print (Float (4))
Custom functions
1 #Custom Functions2 defBijiao (x):3     if  notisinstance (x, (int)):4         RaiseTypeError ('Bad operand type')#built-in functions have parameter checks, and custom functions do not have parameter checks.5         #so this function definition is not perfect. The parameter type is checked and only parameters of the integer type are allowed. Data type checking can be implemented with built-in function isinstance (). 6         #once a parameter check has been added, the function can throw an error if it passes in the wrong parameter type. 7     ifX > 18:8         Print('you're an adult .')9     Else:Ten         Print('you're a minor.') OneA = input ('Please enter your age:') AAge =Int (a) - Bijiao (age) -  the defKongo ():#define an empty function: it doesn't do anything. -     Pass#Pass statement does nothing, it can be used as a placeholder, -     #For example, if you do not think about how to write the code of the function, you can put a pass first, so that the code can run.  -  + #return multiple values - ImportMath#using the Math module in Python + defCS (r): Ac = math.pi*r*2 ats = math.pi*r**2#Power is * * -     Print(c, s) -CS (3)#functions that call CS
Default parameters

The default parameter reduces the difficulty of a function call, and when more complex calls are required, more arguments can be passed. The function only needs to define one, whether it is a simple call or a complex call.

When setting default parameters, there are a few things to note:

The first is required parameter before, the default parameter is behind, otherwise the Python interpreter will error

The second is how to set the default parameters.

When the function has more than one parameter, the parameter with large change is put in front, and the parameters with small change are put back. Parameters with small variations can be used as default parameters.

The greatest advantage of using default parameters is that it can reduce the difficulty of calling a function.

* Define default parameters one thing to keep in mind: the default parameter must point to the immutable object!
1 ImportMath2 defMici (x, n = 2):#The n = 2 here is the default parameter, and the default parameter simplifies the invocation of the function. 3y = 14      whilen >0:5y = y*x6n = n-17     returny8 Print(Mici (3))9 Print(Mici (2, 3))Ten  One defEnroll (name, grader, age = 8, city ='Nantong'):#The advantage of the default parameter value is that it can reduce the difficulty of calling a function.  A     Print('Name:', name) -     Print('Grader:', grader) -     Print('Age :', age) the     Print('City :', city) -Enroll'Chen xxx', 59, 20,'Yichun') -Enroll'hu xxx', The city ='Yichun')#you can provide some default parameters in order, not sequentially. When you do not provide partial default parameters in order, you need to write the parameter names.  - #defining default Parameters Keep in mind that the default parameter must point to the immutable object! 
Variable parameters

Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called.

1 #variable Parameters2 defCalc (Numbers):#as the number of arguments is uncertain, we first think that we can put a,b,c ... Passed in as a list or tuple so that the function can be defined as follows3sum =04      forNinchnumbers:5sum = SUM + NN6     Print(sum)7Calc ([1, 2, 3])#call, you need to assemble a list or tuple first8 defCalc1 (*numbers):#we change the function parameters to variable parameters9sum =0Ten      forNinchnumbers: Onesum = SUM + NN A     Print(sum) -Calc1 (1, 3) -Calc1 ()#If you take advantage of mutable parameters, the way you call a function can be simplified so that you define a mutable parameter and define a list or tuple parameter compared to the #just precede the parameter with an * number. Inside the function, the parameter numbers receives a tuple, so the function code is completely unchanged.  - #However, when you call the function, you can pass in any parameter, including 0 parameters -num = [2, 3] -Calc1 (*num)#*nums indicates that all elements of the list are nums as mutable parameters. This writing is quite useful and common. 
Keyword parameters

The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict.

1 #keyword Parameters2 defXinxi (name, age, * *kw):3     Print('Name:', Name,'Age :', Age,'Other :', kw)4Xinxi ('Chen xxx', city=.'Yichun')#pass in city this parameter with parameter name5Xinxi ('hu xxx', thing=.'Buy Buns', city='Yichun')6WY = {' City':'Nantong','Job':'Engineer'}7Xinxi ('Liu xxx', city=wy[.' City'])8Xinxi ('Yao xxx', **wy)#of course, the complex calls above can be simplified.
Named keyword parameters
1 #named keyword parameters2 #for the keyword argument, the caller of the function can pass in any unrestricted keyword argument. 3 defPerson (name, age, *, City, Job):#Unlike the keyword argument **kw, a named keyword parameter requires a special delimiter *,* the parameters that follow are treated as named keyword parameters. 4     Print('Name:', Name,'Age :', Age,'City :', City,'Job:', Job)5Person'Chen xxx', city=.'Yichun', job='Student')#call the person function6 defPerson1 (name, age, *He, City, job):7     Print(Name, age, *He, city, job)8Person1 ('hu xxx', 20, ['I',' Love','Pipiwen'], city='Yichun', job='Student')#If there is already a mutable parameter in the function definition, then the named keyword argument that follows will no longer require a special delimiter *.9 #The named keyword argument must pass in the parameter name, which differs from the positional parameter. If the parameter name is not passed in, the call will errorTen defPerson2 (name, age, *, Job, city='Yichun'): One     Print(name, age, Job, city) APerson2 ('Wang xxx', job=.'Student')#because the call is missing the parameter name City and the Job,python interpreter treats all 4 parameters as positional parameters, the person () function accepts only 2 positional arguments.  - #A named keyword parameter can have a default value, which simplifies the call, because the named keyword parameter city has a default value, which is not passed to the city parameter when called. Again, note the required parameters before the default parameters are behind, otherwise the Python interpreter will error!  - defPerson3 (name, age, City, job):#without *, then City and job will be treated as positional parameters the     Pass
Parameter combinations

To define a function in Python, you can use the required parameters, default parameters, variable parameters, keyword arguments, and named keyword parameters, which can all be combined using 5 parameters. Note, however, that the order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters.

For any function, it can be called in a similar func(*args, **kw) manner, regardless of how its arguments are defined.

Note: Although you can combine up to 5 parameters, do not use too many combinations at the same time, otherwise the function interface is poorly understandable.

Python Basics (iii)

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.