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

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools