Let's talk about variable parameters of functions in Python.

Source: Internet
Author: User

Let's talk about variable parameters of functions in Python.

Preface

Define functions in Python. You can use required parameters, default parameters, variable parameters, and keyword parameters. These four parameters can be used together or only use some of them, the order of parameter definitions must be: mandatory parameter, default parameter, variable parameter, and keyword parameter.

Variable parameters (*)

Variable parameters, as the name implies, are variable parameters, such as lists and dictionaries. If you need a function to process variable parameters, you can use variable parameters.

When we look at a lot of Python source code, we often see a function definition such as * parameter 1, ** parameter 2). This * parameter and ** parameter are variable parameters, it can be confusing for a moment. In fact, it is not difficult to understand the definition of variable parameters of a function.

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

In Python, parameters with * are used to accept variable numbers of parameters.

If a function is defined as follows:

Def functionTest (* args ):............

We can call this method as follows:

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

Multiple parameters can be input later.

Take a look at the instance code and observe * how to apply it:

Def get_sum (* numbers): sum = 0 for n in numbers: sum + = n return sum # Write your code here to call get_sum to calculate the sum of the five numbers, and print (get_sum (, 5) the result ))

What is the result? You can start to understand all the variable parameters of functions in Python. I hope this article will help you learn or use python, if you have any questions, leave a message.

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.