程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Graphical Python | function

編輯:Python

author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tuto...
This paper addresses :http://www.showmeai.tech/article-detail/81
Statement : copyright , For reprint, please contact the platform and the author and indicate the source


1.Python function

Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .

Function can improve the modularity of application , And code reuse . You already know Python Many built-in functions are provided , such as print(). But you can also create your own functions , This is called a user-defined function .

2. Define a function

You can define a function that you want to function , Here are the simple rules :

  • Function code block to def Key words start with , Followed by function identifier name and parentheses ().
  • Any arguments and arguments passed in must be placed between parentheses , Parentheses can be used to define parameters .
  • The first line of the function optionally uses the document string — Used to store function descriptions .
  • The function content is colon : start , And indent .
  • return [ expression ] End function , Optionally return a value to the caller , Without expression return It's equivalent to returning to None.

(1) grammar

Python Define function use def keyword , The general format is as follows :

def Function name ( parameter list ):
The body of the function 

By default , Parameter values and parameter names match in the order defined in the function declaration . Here is an example code ( The code can be in On-line python3 Environmental Science Run in ):

Let's use functions to output "Hello World!":

def hello() :
print("Hello World!")
hello()

More complex applications , Function with parameter variables :

def my_max(a, b):
if a > b:
return a
else:
return b
a = 4
b = 5
print(my_max(a, b))

The output of the above example :

5

Calculate the area function , Here is an example code ( The code can be in On-line python3 Environmental Science Run in ):

# Calculate the area function
def cal_area(width, height):
return width * height
def my_welcome(name):
print("Welcome", name)
my_welcome("ShowMeAI")
w = 4
h = 5
print("width =", w, " height =", h, " area =", cal_area(w, h))

The output of the above example :

Welcome ShowMeAI
width = 4 height = 5 area = 20

3. Function call

Define a function : Give the function a name , Specifies the parameters contained in the function , And code block structure .

After the basic structure of this function is completed , You can do this through another function call , You can also go straight from Python Command prompt execution .

The following code calls print_myself() function :

# Defined function
def print_myself( str ):
# Print any incoming strings
print (str)
return
# Call function
print_myself(" Call user-defined functions !")
print_myself(" Call the same function again ")

The output of the above example :

 Call user-defined functions !
Call the same function again 

4. Parameter passing

stay python in , Type belongs to object , Variables have no type :

a=[1,2,3]
a="ShowMeAI"

In the above code ,[1,2,3] yes List type ,"ShowMeAI" yes String type , Variables a There is no type , It's just a reference to an object ( A pointer ), It can point to List Type object , It can also point to String Type object .

(1) Changeable (mutable) And cannot be changed (immutable) object

stay python in ,strings, tuples, and numbers Is an object that cannot be changed , and list,dict And so on are modifiable objects .

  • Immutable type : Variable assignment a=10 After the assignment a=5, This is actually a new generation of int The value object 5, let a Pointing to it , and 10 To be discarded , Not change a Value , It's equivalent to a new generation of a.
  • Variable type : Variable assignment l=[1,2,3,4] After the assignment l[2]=5 Will be list l The third element value of changes , In itself l Didn't move , Only part of its internal value has been modified .

python Parameter passing of function

  • Immutable type : similar C++ Value transfer of , Such as integers 、 character string 、 Tuples . Such as func(a), It's just a Value , No impact a Object itself . If in func(a) Internal modification a Value , Is a newly generated a The object of .
  • Variable type : similar C++ By reference , Such as list , Dictionaries . Such as func(l), Will be l Really pass it on , After modification func External l It will also be affected

python Everything in is the object , Strictly speaking, we can't say value passing or reference passing , We should talk about immutable objects and mutable objects .

(2)python Pass immutable object instance

adopt id() Function to see the memory address change :

def my_change(a):
print(id(a)) # It's pointing to the same object
a=10
print(id(a)) # A new object
a=5
print(id(a))
my_change(a)

The output of the above example is :

9788736
9788736
9788896

You can see that before and after calling the function , Formal parameter and argument point to the same object ( object id identical ), After modifying the formal parameters inside the function , Formal parameters point to different id.

(3) Pass variable object instance

The variable object modifies the parameters in the function , So in the function that calls this function , The original parameters have also been changed . Here is an example code ( The code can be in On-line python3 Environmental Science Run in ):

def change_list( mylist ):
" Modify the incoming list "
mylist.append([1,2,3,4])
print (" Value in function : ", mylist)
return
# call changeme function
mylist = [10,20,30]
change_list( mylist )
print (" Value outside the function : ", mylist)

Objects that pass in functions and add new content at the end use the same reference . So the output is as follows :

 Value in function : [10, 20, 30, [1, 2, 3, 4]]
Value outside the function : [10, 20, 30, [1, 2, 3, 4]]

5. Parameters

Here are the formal parameter types that can be used when calling a function :

  • Required parameters
  • Key parameters
  • Default parameters
  • Indefinite length parameter

(1) Required parameters

The required parameters must be passed into the function in the correct order . The number of calls must be the same as when they were declared .

call print_myself() function , You have to pass in a parameter , Otherwise, there will be grammatical errors :

def print_myself( str ):
" Print any incoming strings "
print(str)
return
# call print_myself function , Without parameters, an error will be reported
print_myself()

The output of the above example :

Traceback (most recent call last):
File "test.py", line 10, in <module>
print_myself()
TypeError: print_myself() missing 1 required positional argument: 'str'

(2) Key parameters

Keyword parameters are closely related to function calls , Function calls use key arguments to determine the value of the arguments passed in .

Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared , because Python The interpreter can match parameter values with parameter names .

The following example is in the function print_myself() Call with parameter name :

def print_myself( str ):
" Print any incoming strings "
print(str)
return
# call print_myself function
print_myself( str = "ShowMeAI Knowledge community ")

The output of the above example :

ShowMeAI Knowledge community 

The following example code ( On-line python3 Environmental Science ) It is demonstrated that the use of function parameters does not need to use the specified order :

def print_info( name, age ):
" Print any incoming strings "
print (" name : ", name)
print (" Age : ", age)
return
# call print_info function
print_info( age=30, name="ShowMeAI" )

The output of the above example :

 name : ShowMeAI
Age : 30

(3) Default parameters

When you call a function , If no parameters are passed , Then the default parameters . The following code ( On-line python3 Environmental Science ) If there is no incoming age Parameters , The default value is used :

def print_info( name, age = 35 ):
" Print any incoming strings "
print (" name : ", name)
print (" Age : ", age)
return
# call print_info function
print_info( age=30, name="ShowMeAI" )
print("------------------------")
print_info( name="ShowMeAI" )

The output of the above example :

 name : ShowMeAI
Age : 30
------------------------
name : ShowMeAI
Age : 35

(4) Indefinite length parameter

You may need a function that can handle more arguments than it was originally declared . These parameters are called indefinite length parameters , And above 2 The parameters are different , Declaration will not be named . The basic grammar is as follows :

def function_name([formal_args,] *var_args_tuple ):
" function _ docstring "
function_suite
return [expression]

With an asterisk * The parameters of will be in tuples (tuple) The form of import , Store all unnamed variable parameters .

def print_info( arg1, *vartuple ):
" Print any incoming parameters "
print(" Output : ")
print(arg1)
print(vartuple)
# call print_info function
print_info( 100, 90, 80 )

The output of the above example :

 Output :
100
(90, 80)

If no parameters are specified in the function call , It's just an empty tuple . We can also avoid passing unnamed variables to functions . The following code ( On-line python3 Environmental Science ):

def print_info( arg1, *vartuple ):
" Print any incoming parameters "
print(" Output : ")
print(arg1)
for var in vartuple:
print (var)
return
# call printinfo function
print_info( 100 )
print_info( 90, 80, 70 )

The output of the above example :

 Output :
100
Output :
90
80
70

There is also a parameter with two asterisks ** The basic grammar is as follows :

def function_name([formal_args,] **var_args_dict ):
" function _ docstring "
function_suite
return [expression]

Added two asterisks ** Will be imported as a dictionary .

def print_info( arg1, **vardict ):
" Print any incoming parameters "
print(" Output : ")
print(arg1)
print(vardict)
# call print_info function
print_info(1, a=2,b=3)

The output of the above example :

 Output :
1
{'a': 2, 'b': 3}

When you declare a function , Asterisk in parameter * Can appear alone , for example :

def f(a,b,*,c):
return a+b+c

If the asterisk appears alone * The parameter after must be passed in with the keyword .

def f(a,b,*,c):
return a+b+c
f(1,2,c=3) # normal
f(1,2,3) # Report errors 

6. Anonymous functions

python Use lambda To create anonymous functions .

So called anonymity , It means to stop using def Statement defines a function in this standard form .

  • lambda It's just an expression , Function volume ratio def Simple a lot .
  • lambda The subject of is an expression , Not a block of code . Only in lambda Expressions encapsulate limited logic .
  • lambda Function has its own namespace , And can't access parameters outside their parameter list or in the global namespace .
  • although lambda The function looks like it can only write one line , But it's not the same as C or C++ Inline function , The purpose of the latter is not to occupy stack memory when calling small functions so as to increase the running efficiency .

(1) grammar

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

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

The following example :

my_sum = lambda arg1, arg2: arg1 + arg2
# call my_sum function
print (" The sum is : ", my_sum( 10, 20 ))
print (" The sum is : ", my_sum( 20, 20 ))

The output of the above example :

 The sum is : 30
The sum is : 40

7.return sentence

return [ expression ] Statement is used to exit a function , Optionally return an expression... To the caller . Without parameter value return Statement returns None. None of the previous examples demonstrated how to return a value , The following example demonstrates return Usage of sentences :

def my_sum( arg1, arg2 ):
# return 2 The sum of parameters ."
total = arg1 + arg2
print(" Within the function : ", total)
return total
# call sum function
total = my_sum( 10, 20 )
print(" Out of function : ", total)

The output of the above example :

 Within the function : 30
Out of function : 30

8. Force position parameters

Python3.8+ Added a function parameter Syntax / Used to indicate that the function parameter must use the specified positional parameter , Cannot use the form of keyword parameter .

In the following example , Shape parameter a and b You must use the specified positional parameter ,c or d It can be a location parameter or a keyword parameter , and e and f Keyword parameter required :

def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)

The following usage is correct :

f(10, 20, 30, d=40, e=50, f=60)

The following usage method will make mistakes :

f(10, b=20, c=30, d=40, e=50, f=60) # b Cannot use the form of keyword parameter
f(10, 20, 30, 40, 50, f=60) # e Must be in the form of a keyword parameter 

9. Video tutorial

Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition

https://www.bilibili.com/vide...

Data and code download

The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can surf the Internet scientifically can also use google colab One click operation and interactive operation learning Oh !

This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :

  • Python Quick reference table

Expand references

  • Python course —Python3 file
  • Python course - Liao Xuefeng's official website

ShowMeAI Recommended articles

  • python Introduce
  • python Installation and environment configuration
  • python Basic grammar
  • python Basic data type
  • python Operator
  • python Condition control and if sentence
  • python Loop statement
  • python while loop
  • python for loop
  • python break sentence
  • python continue sentence
  • python pass sentence
  • python String and operation
  • python list
  • python Tuples
  • python Dictionaries
  • python aggregate
  • python function
  • python Iterators and generators
  • python data structure
  • python modular
  • python File read and write
  • python File and directory operations
  • python Error and exception handling
  • python object-oriented programming
  • python Namespace and scope
  • python Time and date

ShowMeAI A series of tutorials are recommended

  • The illustration Python Programming : From introduction to mastery
  • Graphical data analysis : From introduction to mastery
  • The illustration AI Mathematical basis : From introduction to mastery
  • Illustrate big data technology : From introduction to mastery


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved