Self-taught Python's function

Source: Internet
Author: User

Python functions are simpler than other languages, do not need pointers, and do not have parameter types, as long as the formal parameters can be written.

A small example realizes the addition of two numbers

def fun (a,b):
    c=a+b
    Print (c)
Fun (2,3)

It is so simple to achieve. Output is 5

Note that there must be a consistent number of parameters passed here, meaning that the function requires two parameters, you can not pass one, or it will be an error.

In addition, the type is also limited, for example, your function is to perform the addition, you pass the string, of course, no problem, if your function is to perform subtraction, it will be an error.


There is also a situation in the definition of a function, the need for an initial value, that is, do not pass parameters, the function performs the default effect. For example, the addition function above, I do not want to pass parameters, then you set the default parameters.

or the above function:

def fun (a=100,b=200):
    c=a+b
    Print (c)
fun () # #300
Fun (1,2) # #3
Fun (1) # #201

Here, even though we call fun () without passing arguments, there is no error, because he has the default parameter, the result of execution is 300.

If you pass the argument, the default argument will be invalidated.

If more than one parameter is invoked, the part that is not specified will be the default.

Of course, there may also be a situation, that is, when passing the parameters, we do not want to give the previous a pass parameters, we want to give the following B pass parameters, then what to do. It's actually the same.

The call is written like this:

Fun (b=100)

This is to tell the program that the front argument a I do not pass, just to parameter B is 100.

The result of this output is 200.

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.