Default parameters of a function

Source: Internet
Author: User

Default parameter values
For some functions, you may want some of its parameters to be optional, and if the user does not want to provide values for these parameters, the parameters will use the default values. This function is done using the default parameter values. You can assign default parameter values to parameters by adding the assignment operator (=) and the default value after the parameter name of the function definition.
Note that the default parameter value should be a parameter. More precisely, the default parameter values should be immutable-this will be explained in detail in a later section. Keep this in mind from now on.
Using default parameter values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Example 7.5 using default parameter values

#!/usr/bin/python#Filename:func_default.pydefSay (Message,times=1):PrintMessage *Times ;#if (a==1):#modifying default parameter values#times=2#Print message * times;#a=1Say'Hello') Say (' World', 5)

Output
$ python func_default.py
Hello
Worldworldworldworldworld

How it works
The function named say is used to print a string any number of times required. If we do not provide a value, then by default, the string will be printed only once. We do this by assigning a default parameter value to the parameter times.
When using say for the first time, we provide only one string, and the function prints the string only once. In the second use of say, we provided a string and a parameter of 5, indicating that we wanted to say this string message 5 times.
Important only those parameters at the end of the formal parameter list can have default argument values, which means that you cannot declare a parameter with a default value and then declare a formal parameter that has no default value when declaring a function parameter. This is because the value assigned to the parameter is assigned according to the position. For example, Def func (A, b=5) is valid, but def func (a=5, b) is not valid.

Default parameters of a function

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.