Definition, use, and parameter transfer implementation code for Python def functions _python

Source: Internet
Author: User
Tags in python

In Python programming, you can use functions to define some programs that need to be called repeatedly, in basic form:

def function name (parameter 1, Parameter 2, ..., parameter n):

The execution statement function name is the representation name of the call, and the argument is an incoming parameter, which can be more defined or not.

# example 1: simple function using
# coding=gb2312

# defines the function
def hello ():
  print ' Hello python! '
  
# Call Function    
Hello ()
  
>>> Hello python!

Functions can have parameters and return values, parameters will match from left to right, parameters can set the default value, when the function is not given the corresponding parameters, the default values are assigned.

# example 2: Cumulative calculated value
# coding=gb2312

# defines function
def myadd (a=1,b=100): Result
  = 0
  i = a while
  i <= b:
   # default value is 1+2+3+......+100 result
    = i  
    i + 1 return result

# print 1+2+......+10 print    
myadd (1,10)
Print Myadd ()    # Use default parameters 1,100
print Myadd   # A assignment 50,b use default
  
>>>
>>> 5050
>>> 3825

When the parameters of a Python function are passed, it is worth noting that when a parameter is passed in, the variable is treated as a temporary assignment to the parameter variable, and the object is referenced.

 # example 3: # coding=gb2312 def Testpara (p1,p2): P1 = p2.append (' hello ') L = [] # define A Array pair like a = 20 # Assign a value to variable a Testpara (a,l) # variable A and object array l as parameters incoming print a # The value for V in L: # printing the member Print v >&G of an array object T;> 20 # After calling the function a variable is not valued >>> Hello # While object L array adds 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.