Pythondef function definition, use, and parameter transfer implementation code

Source: Internet
Author: User
In Python programming, you can use functions to define some programs that require repeated calls. in Python, def is used to define functions, for python programming programs that require repeated calls, you can use functions to define them. The basic form is as follows:

Def function name (parameter 1, parameter 2 ,......, Parameter N ):

The name of the function called by the execution statement is the input parameter, which can be defined or not required.

# Example 1: Use a simple function # coding = gb2312 # define the function def hello (): print 'Hello python! '# Call the function hello () >>> hello python!

A function can contain parameters and return values. parameters are matched from left to right. default values can be set for parameters. when a function is used, values are assigned by default.

# Example 2: accumulate calculated value # coding = gb2312 # define function def myadd (a = 1, B = 100): result = 0 I = a while I <= B: # The default value is 1 + 2 + 3 + ...... + 100 result + = I + = 1 return result # Print 1 + 2 + ...... + 10 print myadd (1,100) print myadd () # use the default parameter print myadd (50) # a value of 50, B use the default value >>> 55 >>> 5050 >>> 3825

When passing parameters of a Python function, it is worth noting that if the input parameter is a variable, it will be temporarily assigned to the parameter variable. if it is an object, it will be referenced.

# Example 3: # coding = gb2312def testpara (p1, p2): p1 = 10 p2.append ('Hello ') l = [] # define an array for image a = 20 # assign testpara (a, l) to variable) # Input print a as a parameter between variable a and object array l # print the value of the running parameter for v in l: # print the print v >>> 20 # The a variable is not reset after the function is called >>> hello # The member hello is added to the l array of the object.

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.