Describes how to use various functions in Python and how to use python functions.

Source: Internet
Author: User

Describes how to use various functions in Python and how to use python functions.

Functions are organized and reusable code used to execute a single block of related actions. Functions provide better modules for application and code reuse.

As we know, many built-in functions such as print () in Python can also be created. These functions are called user-defined functions.
Define a function

You can define functions to provide the required functions. Below are simple rules to define Python functions.

  • The function block is followed by the START keyword def and the name () in brackets (()).
  • Any input parameters or parameters should be placed in these brackets. You can also define parameters in these parentheses.
  • The first statement of the function can be ?? An optional declaration-document string of this function or document string.
  • The code block in each function starts with a colon (:) And is indented.
  • This statement returns the [expression] to exit the function. It is optional to pass back an expression to the caller. The return value is None without the return parameter.

Syntax:

def functionname( parameters ):  "function_docstring"  function_suite  return [expression]

By default, parameters have a location behavior and need, which are defined to notify them in the same order.
Example:

This is the simplest form of Python functions. This function accepts a string as the input parameter and prints the standard screen.

def printme( str ):  "This prints a passed string into this function"  print str  return

Call a function

Define a function to only give its name, specify the parameters of the code block to be included in the function and structure.

Once the basic structure of a function is determined, you can call it from another function or directly from a Python prompt to execute it. The following example calls the printme () function:

#!/usr/bin/python# Function definition is heredef printme( str ):  "This prints a passed string into this function"  print str;  return;# Now you can call printme functionprintme("I'm first call to user defined function!");printme("Again second call to the same function");

When the above code is executed, the following results are generated:

I'm first call to user defined function!Again second call to the same function

Reference VS value transfer

All parameters are passed through reference in Python. This means that if you change the value of a parameter in a function, the change is also reflected in the call function. For example:

#!/usr/bin/python# Function definition is heredef changeme( mylist ):  "This changes a passed list into this function"  mylist.append([1,2,3,4]);  print "Values inside the function: ", mylist  return# Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist

Here, we keep the reference of the passed object and append the value to the same object. This will produce the following results:

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is also an example in the called function where parameters are passed and referenced by reference.

#!/usr/bin/python# Function definition is heredef changeme( mylist ):  "This changes a passed list into this function"  mylist = [1,2,3,4]; # This would assig new reference in mylist  print "Values inside the function: ", mylist  return# Now you can call changeme functionmylist = [10,20,30];changeme( mylist );print "Values outside the function: ", mylist

The local function changeme on the myList parameter. Changing mylist in the function does not affect mylist. The function does not work. In the end, the following results are generated:

Values inside the function: [1, 2, 3, 4]Values outside the function: [10, 20, 30]

Function parameters:

You can call a function by using the following parameter types:

  • Required Parameters
  • Keyword Parameter
  • Default parameters
  • Variable Length Parameter

Required parameters:

The required parameters are the parameters passed to the function with the correct positional order. Here, the number of parameters called by the function should exactly match the function definition.

To call the printme () function, you must pass a parameter. Otherwise, the following syntax error is returned:

#!/usr/bin/python# Function definition is heredef printme( str ):  "This prints a passed string into this function"  print str;  return;# Now you can call printme functionprintme();

When the above code is executed, the following results are generated:

Traceback (most recent call last): File "test.py", line 11, in <module>  printme();TypeError: printme() takes exactly 1 argument (0 given)

Keyword parameter:

Keyword parameters are related to function calls. When a function call uses a keyword parameter, the caller uses the parameter name to identify the parameter.

This can skip the parameter or escape the order, because the Python interpreter can use the provided parameter to use the keyword of the matched value. You can also use keywords to call the printme () function in the following aspects:

#!/usr/bin/python# Function definition is heredef printme( str ):  "This prints a passed string into this function"  print str;  return;# Now you can call printme functionprintme( str = "My string");

When the above code is executed, the following results are generated:

My string

The following example shows a clearer picture. Note that the order of parameters is irrelevant.

#!/usr/bin/python# Function definition is heredef printinfo( name, age ):  "This prints a passed info into this function"  print "Name: ", name;  print "Age ", age;  return;# Now you can call printinfo functionprintinfo( age=50, name="miki" );

When the above code is executed, the following results are generated:

Name: mikiAge 50

Default parameters:

The default parameter is, assuming a default value, if the parameter of the parameter value of the function call is not provided. The following example provides an idea of the default parameter, which prints the age by default. If you do not pass the value:

#!/usr/bin/python# Function definition is heredef printinfo( name, age = 35 ):  "This prints a passed info into this function"  print "Name: ", name;  print "Age ", age;  return;# Now you can call printinfo functionprintinfo( age=50, name="miki" );printinfo( name="miki" );

When the above code is executed, the following results are generated:

Name: mikiAge 50Name: mikiAge 35

Variable Length parameters:

You may need to process multiple parameters in a function than in a defined function. These parameters are called variable-length parameters, which are not named in the function definition, unlike the required default parameters.

The general syntax of a non-Keyword Variable Parameter Function is as follows:

def functionname([formal_args,] *var_args_tuple ):  "function_docstring"  function_suite  return [expression]

The asterisk (*) is placed to hold all non-Keyword variable parameters before the variable name. This tuple remains empty if no other parameters are specified during function call. The following is a simple example:

#!/usr/bin/python# Function definition is heredef printinfo( arg1, *vartuple ):  "This prints a variable passed arguments"  print "Output is: "  print arg1  for var in vartuple:   print var  return;# Now you can call printinfo functionprintinfo( 10 );printinfo( 70, 60, 50 );

When the above code is executed, the following results are generated:

Output is:10Output is:706050

Anonymous functions:

You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared using the def keyword in a standard way.

  • Lambda can take any number of parameters, but only one value is returned in the form. They cannot contain commands or multiple expressions.
  • Anonymous functions cannot directly call printing because lambda expressions are required.
  • Lambda functions all have their own namespaces and cannot access variables higher than those in their parameter lists and those in global namespaces.
  • Although lambda seems to be a single-line version of a function, they are not in C or C ++, and their purpose is to assign a declaration equivalent to a row by calling the stack allocation of the passed function for performance reasons.

Syntax

The syntax of a lambda function only contains a single statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression

The following is an example to illustrate how the lambda form works:

#!/usr/bin/python# Function definition is heresum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a functionprint "Value of total : ", sum( 10, 20 )print "Value of total : ", sum( 20, 20 )

When the above code is executed, the following results are generated:

Value of total : 30Value of total : 40

Return Statement:

This statement returns the [expression] to exit the function. It is optional to pass back an expression to the caller. The return value is None without the return parameter.

None of the above examples return any value, but if you like it, you can return the value from a function:

#!/usr/bin/python# Function definition is heredef sum( arg1, arg2 ):  # Add both the parameters and return them."  total = arg1 + arg2  print "Inside the function : ", total  return total;# Now you can call sum functiontotal = sum( 10, 20 );print "Outside the function : ", total 

When the above code is executed, the following results are generated:

Inside the function : 30Outside the function : 30

Variable scope:

All variables in the program may not be accessed at all locations in the program. This depends on the declared variable.

The scope of the variable determines the program that can access a part of a specific Identifier. There are two basic categories of variables in Python:

  • Global Variables
  • Local variable

Global and local variables:

This is a variable defined within the function body that has a local range, while those defined outside the function body have a global range.

Local variables can only be declared and accessed within the function, while global variables can be accessed by all functions in the entire program body. When a function is called, all the variables declared in it are included in the scope. The following is a simple example:

#!/usr/bin/pythontotal = 0; # This is global variable.# Function definition is heredef sum( arg1, arg2 ):  # Add both the parameters and return them."  total = arg1 + arg2; # Here total is local variable.  print "Inside the function local total : ", total  return total;# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", total 

When the above code is executed, the following results are generated:

Inside the function local total : 30Outside the function global total : 0

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.