Python functions
Function is an organized, reusable code segment used to implement a single or related function.
Functions can improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
Define a function
You can define a function with the functions you want, the following are simple rules:
The function code block starts with the def keyword, followed by the function identifier name and parentheses ().
Any incoming parameters and independent variables must be placed between parentheses. Parameters can be defined between parentheses.
The first line of a function can optionally use a docstring - used to store function descriptions.
Function content starts with a colon and is indented.
Return[expression] ends the function and optionally returns a value to the caller. Return without an expression is equivalent to returning None.
Syntax
def functionname(parameters):
"Function_docstring"
function_suite
return [expression]
Default case, parameter values and parameter names are by The order of definitions in the function declaration matches.
Example
The following is a simple Python function that takes a string as an input parameter and prints it to a standard display device.
def printme(string):
"Print the incoming string to a standard display device"
print string
Function call
Define a function and only give the function a name , specifies the parameters contained in the function, and the code block structure.
After the basic structure of this function is completed, you can execute it through another function call or directly from the Python prompt.
The following example calls the printme() function:
#!/usr/bin/python
# Function definition is here
def printme( string ):
"Print any incoming String"
print string
# Now you can call printme function
printme("I want to call a user-defined function!");
printme("Call the same function again");
Output result of the above example:
I want to call a user-defined function!
Call the same function again
Pass parameters by value and pass parameters by reference
All parameters (independent variables) In Python everything is passed by reference. If you change the parameters in the function, the original parameters will also be changed in the function that calls this function. For example:
#!/usr/bin/python
# Writable function description
def changeme( mylist ):
"Modify the incoming list"
mylist.append([1 ,2,3,4])
print "Value in function: ", mylist
# Call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Value outside the function: ", mylist
The object passed into the function and the object to add new content at the end use the same reference. Therefore, the output result is as follows:
Values within the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Parameters
The following are the formal parameter types that can be used when calling functions:
Required parameters
Named parameters
Default parameters
Variable length parameters
Required Preparatory parameters
Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.
When calling the printme() function, you must pass in a parameter, otherwise a syntax error will occur:
#!/usr/bin/python
#Writable function description
def printme( string ):
"Print any incoming string"
print string
#Call the printme function
printme()
The output result of the above example:
Traceback (most recent call last):
File "test.py", line 11, in
printme()
TypeError: printme() takes exactly 1 argument (0 given)
named parameters
Named parameters are closely related to function calls. The caller uses the naming of parameters to determine the value of the parameters passed in. You can skip unpassed parameters or pass parameters out of order because the Python interpreter can match parameter names with parameter values. Call the printme() function with named parameters:
#!/usr/bin/python
#Writable function description
def printme( string ):
"Print any incoming string "
print string
#Call the printme function
printme(str = "My string")
The output result of the above example:
My string
next The example can show more clearly that the order of named parameters is not important:
#!/usr/bin/python
#Writable function description
def printinfo(name, age):
"Print Any incoming string "
print "Name: ", name
print "Age ", age
#Call the printinfo function
printinfo(age=50, name="miki" )
Output result of the above example:
Name: miki
Age 50
Default parameters
When calling a function, if the value of the default parameter is not passed in, it is considered to be the default value. The following example will print the default age, if age is not passed in:
#!/usr/bin/python
#Writable function description
def printinfo(name, age = 35):
"Print any incoming string"
print "Name: ", name
print "Age ", age
#Call the printinfo function
printinfo(age=50, name="miki")
printinfo(name="miki")
The output result of the above example:
Name: miki
Age 50
Name: miki
Age 35
Indeterminate length Parameters
You may need a function that can handle more parameters than originally declared. These parameters are called variable-length parameters. Unlike the above two parameters, they will not be named when declared. The basic syntax is as follows:
def functionname([formal_args,] *var_args_tuple ):
"Function_docstring"
function_suite
return [expression]
Starred ( *) variable names will store all unnamed variable parameters. You can also choose not to pass more parameters. The following example:
#!/usr/bin/python
# Writable function description
def printinfo(arg1, *vartuple):
"Print any incoming parameters"
print "Output: "
print arg1
for var in vartuple:
print var
# Call printinfo function
printinfo(10)
printinfo(70, 60, 50 )
and above Example output result:
Output:
10
Output:
70
60
50
Anonymous function
Use lambda keyword Ability to create small anonymous functions. This type of function gets its name from the fact that the standard step of declaring a function with def is omitted.
Lambda function can receive any number of parameters but can only return the value of one expression, and it cannot contain commands or multiple expressions.
Anonymous functions cannot call print directly because lambda requires an expression.
The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
Although the lambda function seems to only be able to write one line, it is not equivalent to the inline function of C or C++. The purpose of the latter is to call small functions without occupying stack memory and thus increase operating efficiency.
Grammar
The syntax of the lambda function only contains one statement, as follows:
lambda [arg1 [,arg2,...argn]]:expression
The following example:
#!/usr/bin/python
#Writable function description
sum = lambda arg1, arg2: arg1 + arg2
#Call the sum function
print "Value of total" : " , sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
The above example output result:
Value of total : 30
Value of total : 40
return statement
return statement [expression] exits the function and optionally returns an expression to the caller. A return statement without parameter values returns None. The previous examples did not demonstrate how to return a value. The following example will tell you how to do it:
#!/usr/bin/python
#Writable function description
def sum( arg1, arg2 ) ; total = sum( 10, 20 );
print "Outside the function : ", total
The above example output result:
Inside the function : 30
Outside the function : 30
Variables Scope
Not all variables in a program can be accessed everywhere. Access permissions depend on where the variable is assigned.
The scope of a variable determines which part of the program you can access. Variable names. The two most basic variable scopes are as follows:
global variables
local variables
variables and local variables
Variables defined inside a function have a local scope, and variables defined outside the function have a global scope Scope.
Local variables can only be accessed within the function in which they are declared, while global variables can be accessed within the entire program scope. When a function is called, all variable names declared within the function will be added to the scope. The following example:
#!/usr/bin/python
total = 0; #Return the sum of the 2 parameters. "
total = arg1 + arg2; # total is a local variable here.
print "Inside the function local total : ", total
return total;
#Call sum Function
sum( 10, 20 );
print "Outside the function global total : ", total
The above example output result:
Inside the function local total : 30
Outside the function global total : 0

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
