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



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.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.
