The content of this article is the basic knowledge of Python functions. Now I share it with you. Friends in need can refer to the content in the article
Function: If you need a certain piece of code multiple times when developing a program, but in order to improve writing efficiency and code reuse, code blocks with independent functions are organized into a small module
This is the function
Function definition and call
Define function
The format of defining a function is as follows:
def function name():
Code
Call the function
After defining the function, it is equivalent to having a code with certain functions. If you want these codes to be executed, you need to call it
Calling the function is very simple , the call can be completed through the function name ()
Function parameters (1)
In order to make a function more general, that is, if you want it to calculate the sum of two numbers, just Let it calculate the sum of two numbers. When defining the function, you can let the function receive data.
This solves this problem. This is the parameter of the function
Define with parameters Function
Examples are as follows:
def add2num(a, b):
c = a+b
print c
Call with parameters Function
Take calling the add2num(a, b) function above as an example:
def add2num(a, b):
c = a+b
print c
Add2num(11, 22) #When calling a function with parameters, you need to pass the data in parentheses
Summary
Parameters in parentheses when defining , used to receive parameters, are called "formal parameters"
The parameters in parentheses when calling are used to pass to the function, called "actual parameters"
Function return Value (1)
Introduction to "return value"
The so-called "return value" is the final result given to the caller after the function in the program completes one thing
Function with return value
If you want to return the result to the caller in the function, you need to use return
in the function. The following example:
def add2num(a, b):
c = a+b
# Save the return value of the function
In the example of "buying cigarettes" mentioned at the beginning of this section, when your son gives you the cigarette at the end, you must be from your son Take it over in your hand, right? The same is true for programs. If a function returns a data, and you want to use this data, you need to save it
An example of the return value of the saved function is as follows:
# Define function
def add2num(a, b):
return a+b
#Call the function and save the return value of the function
result = add2num(100,98)
#Because result has saved the return value of add2num, so it can be used next
Function return value (2)
Can we return multiple values in python?
>>> def pid(a, b):
... shang = a//b
... yushu = a%b
... return shang . yu
1
The essence is to use the tuple
4 types of functions
The function depends on whether there are parameters and whether there is a return value , can be combined with each other, there are 4 types in total
No parameters, no return value
’ ’ ’ s ’ s 1 ‐ ‐ ‐ t t to t t t t ’ ’ s ’ s ’ s ’ s ’ s ’
This type of function cannot accept parameters and has no return value. Generally, to print functions similar to the prompt light, use this type of function
No parameters, return value Value function
, , , , , , herself - herself herself herself she herself she She Shen Shen Shen Shen Shen her out her out there heron to do herself in. #DEF GETTEMPERATURE ():
#Here is some of the processing process of getting the temperature
#In order to simulate the return of a data
RETURN 24
## TEMPERAN = = getTemperature ()
PRINT ('The current temperature is:%d'%temporarative)
Result:
## This current temperature is: 24
& lt; Functions with parameters and no return value
This type of function can receive parameters, but cannot return data. Generally, this type of function is used when setting data for certain variables without requiring a result
# & lt; 4 & gt; there are parameters, and there are functions with returning value
This kind of functions, which can not only receive parameters, but also return a certain data. Generally, it is like data processing and applications that require results. , use this kind of function
# Calculate the cumulative sum of 1~num
def calculateNum(num):
‐ to calculate the cumulative sum of 1~num i & lt; = num:
Result = result + i
i + = 1
## Regent result
ain = Calculatenum (100) #A 'The cumulative sum of 1~100 is: %d'%result)
Result:
The cumulative sum of 1 to 100 is: 5050
’ s ’ s ’ ’ s t . ## The following example will print the default AGE. name
PRINT "Age", Age
#n n n
Printinfo (name = "miki")
Printinfo (Age = 9, name = "miki")
The output result of the above example:
Name: Miki
Age 9
Note: Parameters with the default value must be at the end of the parameter list.
t;", line 1
Syntaxerror: NON-Default Argument Follows Default ARGUMENT
# 2. Performance parameters
Sometimes it may need a function to process more parameters than when the original statement. These parameters are called variable-length parameters and are not named when declared.
The basic syntax is as follows:
## function_suite
return [ Expression]
Added a variable (*) variable ARGS will store all the unnamed variable parameters, ARGS is the meta -group; and the variable KWARGS plus ** will store the naming parameters,
is shape as shaped like it key=value parameters, kwargs is a dictionary.
> print "a =", a
. for key , value in kwargs.items():
m = 6, n = 7, p = 8)#注意 m m m m m m
A = 1
B = 2
ARGS = (3, 4, 5)
Kwargs:
p = 8
; c = (3, 4, 5)
>>> fun(1, 2, *c, **d) # Pay attention to the parameter passing method of tuples and dictionaries
, 5)
;> ;>
args = ( (3, 4, 5), {'p': 8, 'm': 6, 'n': 7})
3. Quote Chuanyin
The variables of the variable type and unchanged types are used as function parameters, respectively?
Does Python have pointer parameter passing similar to that in C language?
## >>> a_int = 1
; 1
>> selfAdd(a_list)
>>> a_list
For immutable types, the dependent variable cannot be modified, so the operation will not affect the variable itself
; for variable types, the operation in the function body may change the passed parameter variable.
Nested calls of functions
def testB():
print('---- testB start----')
print('Here It is the code executed by the testB function --- testA start----')
testB()
testA() - testA start----
---- testB start----
---- Here is the code for testB function execution
---- testB end----
---- testA end----
## Thinking & Implementation 1
Write a function to print a horizontal line
Print a custom number of horizontal lines
# Print a horizontal line
def printNumLine(num):
i=0
Because the printOneLine function has completed the function of printing horizontal lines,
only needs to call this function multiple times
While I & lt; num:
Printoneline ()
I+= 1
PRINTNUMLINE (3)
## thinking & Implementation 2
##的和
写一个函数求三个数的平均值
参考代码2
# 求3个数的和
def sum3Number(a,b, c):
return a+b+c # return 的后面可以是数值,也可是一个表达式
# 完成对3个数求平均值
def average3Number(a,b, c):
# Because the sum3Number function has already completed the sum of 3 numbers, so it only needs to be called
# That is, the 3 received numbers can be passed as actual parameters
sumResult = sum3Number(a,b,c)
aveResult = sumResult/3.0
average3Number( ) , you can define local variables with the same name, but using each one will not affect
The role of local variables, in order to temporarily save data, you need to define variables in the function for storage, this is its role
Global variables
If a variable can be used in a function or in other functions, such a variable is a global variable
The demo is as follows:
# Define global variables
a = 100
def test1():
print(a)
def test2():
print(a)
# Calling functions
test1()
test2()
# If you modify a global variable in a function, you need to use global to declare it, otherwise an error will occur.
If the name of the global variable is the same as the name of the local variable, then the local variable is used. A little trick to make the powerful dragon not overpower the local snake
recursive function
If a function does not call other functions internally, but itself, this function is a recursive function.
For example, let’s calculate the factorial n! = 1 * 2 * 3 * ... * n
def calNum(num):
i = 1
return = 1
while i while i return *= i
i+=1
return result
ret = calNum(3)
print(ret)
Anonymous function
Use the lambda keyword to create a small anonymous function. This type of function gets its name from the fact that the standard step of declaring a function with def is omitted.
The syntax of the lambda function only contains one statement, as follows:
lambda [arg1 [,arg2,...argn]]:expression
The following example:
sum = lambda arg1, arg2: arg1 + arg2
#Call sum function
print "Value of total: ", sum(10, 20)
print "Value of total : ", sum(20, 20)
The output result of the above example:
Value of total: 30
Value of total: 40
The Lambda function can receive any number of parameters but can only return the value of an expression
Anonymous functions cannot call print directly because lambda requires an expression
Application scenarios
Functions are passed as parameters
Self Define function
, , , , , , # = 1
using using use with using ’ through through ’ through ’ using ’s ’ using ’s ’ using ‐ ‐ ‐ ‐ ‐ to be sorted by age or name?
stus = [
{"name":"wangwu", "age":17}
]
Sort by name:
>>> stus.sort(key = lambda x: x['name'])
>>> stus
[{'age': 19, 'name': 'lisi'}, {'age': 17, 'name': 'wangwu '}, {'age': 18, 'name': 'zhangsan'}]
Sort by age:
>>> stus.sort(key = lambda x: x['age'])
>>> stus
[{'age': 17, 'name': 'wangwu'}, {'age': 18, 'name': 'zhangsan '}, {'age': 19, 'name': 'lisi'}]
Notes on using functions
1. Custom function
No parameters, no return value
def function name():
Statement
statement
Return The value that needs to be returned
Note:
Is there any back function? It depends on whether there is Return, because only Return can return data
In development, functions are often designed according to needs whether they need to return a value.
In a function, there can be multiple return statements, but as long as one return statement is executed, it means that the call of this function is completed
With parameters and no return value
because Pass some data together, and the called function needs to use parameters to receive it
Value
# DEF Function Title (List of Shape Peris):
Sentence
RETURN The value you need to return
# & LT; The call function
& lt; 1 & gt;
If the call function is tangible when defined, then the parameters should be passed when calling
# & lt; 3 & gt; Consistent with the requirements in ;1>Variables defined in a function can only be used in this function (local variables)
Variables defined outside the function can be used in all functions (global variables)
Related recommendations:
Introduction to Python basic functions
The above is the detailed content of Function basics (python). For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

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.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.