A brief talk on the variable parameters of functions in Python _python

Source: Internet
Author: User
Tags function definition in python

Objective

To define a function in Python, you can use required parameters, default parameters, variable parameters, and keyword parameters, all 4 of which can be used together, or only some of them, but note that the order in which the parameters are defined must be: required, default, variable, and key parameters.

Variable parameters (*)

Variable parameters, as the name suggests, its parameters are variable, such as lists, dictionaries, and so on. If we need a function to handle a variable number of parameters, we can use the variable parameters.

When we look at a lot of Python source code, we often see the function definition of a function (* parameter 1, * * Parameter 2), this * parameter and the * * parameter are variable parameters, which is a bit confusing. In fact, as long as the definition of the function variable parameters are clear, it is not difficult to understand.

When we do not know how to define a function with several parameters, the variable parameters can be used.

In Python, a parameter with a * is used to accept a variable number of parameters.

If a function is defined as follows:

def functiontest (*args): ..... 
 .... 
 ....

Call when we can call this:

FunctionTest (1) 
or 
functiontest (1,2) 
or 
functiontest (1,2,3)

You can pass in more than one parameter later.

Look at the example code, see how the * is specific application of the bar:

def get_sum (*numbers): 
 sum = 0 
 for n in numbers: 
  sum + = n return 
 sum 
  
#在这里写下你的代码来调用get_sum来求5个数字的和, and output this result 
print (Get_sum (1,2,3,4,5))

What would be the result? You can do it by yourself and look at the entire contents of the variable parameters of the function in Python, hopefully this article will help you learn or use Python, if you have questions you can exchange messages.

Related Article

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.