Python learning: definition, use, and parameter transfer of Def Functions

Source: Internet
Author: User

In Python programmingProgram, Which can be defined using functions. The basic form is:

Def Function Name (parameter 1, parameter 2 ,......, Parameter n ):
Execution statement
 
 

The name of the function is called, and the parameter is the input parameter, which can be defined or not.#Example 1: simple function usage
#Coding = gb2312

#Define functions
DefHello ():
Print 'Hello python!'

#Call a 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 calculation value
# Coding = gb2312

# Define functions
Def Myadd (a = 1, B = 100 ):
Result = 0
I =
While I <= B: # The default value is 1 + 2 + 3 + ...... + 100
Result + = I
I + = 1
Return Result

#Print 1 + 2 + ...... + 10
PrintMyadd (1, 10)
PrintMyadd ()#Use the default parameter 1,100
PrintMyadd (50)#A is assigned 50 values. B uses 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 = gb2312

Def Testpara (P1, P2 ):
P1 = 10
P2.append ( ' Hello ' )

L = [] # Define an array of Objects
A = 20# Assign a value to variable
Testpara (A, L) # Variable A and object array L are passed as parameters
Print A # Print the value after running parameters
For V In L: # Print members of an array object
Print V

>>> 20 # Variable A is not reset after the function is called.
>>> Hello # The object L Array adds the member hello.

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.