Variable parameters for functions in Python

Source: Internet
Author: User
Preface

Defining functions in Python can be done with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of the parameters definition must be: required, default, variable, and keyword parameters. 4

Variable parameters (*)

Variable parameters, as the name implies, 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 variable parameters.

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

When we don't know how to define a function with a few parameters, variable parameters can be used.

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

If a function is defined as follows:

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

Called when we can call this:

FunctionTest (1) or functiontest (or functiontest)

You can pass in multiple parameters later.

Take a look at the example code and see how it applies:

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? Everyone can do their own operation to see, in order to be about the function of the variable parameters in Python all content, I hope this article for you to learn or use Python can help, if there is doubt can message exchange.

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.