function : Reusable blocks of code simply put: The statements that we use are used to execute the statements each time a name is called;
function definition:
Create a function using the keyword DEF statement
Def sayHello (): Print ("Hello world!");
Call defined functions directly using function names
SayHello ();
Output Result:
Hello world!
If the function has more than one return value such as:
def remainder (b): #a, B is called formal parameter q = a//b #取商 r = a-q*b return (q,r); res, res2 = remainder (24,6); #传递进函数的叫做实参print (Res,res2);
Output Result:
4 0
The function arguments can provide a way to use the default values:
def setData (name,age = '): Print (name+ "Hello, you are full" +age+ "can register this game!"); SetData ("Huyan burning");
Output Result:
Huyan Hello, you are over 18 can register this game!
There is also a way to do this regardless of the parameter order :
SetData (age= 22,name = ' Chun Rui ')
Output Result:
Hello, Chun Rui, you are over 22 can register this game!
Create variables in functions, scopes are local if you want to modify global variables inside a function, you can use the global statement
Count = 10;def num (): Global count; if (count<=10): Count + = 1; print (count); Num () print (count);
Output Result:
11
11
How to print a document in a function use System special properties __doc__:
def myData (name): ' This is a way of extracting my personal information '; Print (' I call ' +name); MyData (' history ');p rint (mydata.__doc__);
Output results
My name He.
This is a way to extract my personal information
Collect parameters : the parameter before plus * indicates the collection of the remaining positional parameters if no collected elements are provided to collect the parameters as empty tuples
def Demo (*param): print ("parameter length is:", Len (param), "parameter in the title is:", param[1]);D Emo (1, ' Timely Rain ', ' Song Jiang ', ' Day of the Star ');
Output Result:
Parameter length is: 4 The title of the parameter is: Timely rain
if additional parameters need to be passed when using the Collect parameter , use the method:
def Demo (*param,book): print ("parameter length is:", Len (param), "parameter in the title is:", param[1], ' characters from ', book);D Emo (1, ' Timely Rain ', ' Song Jiang ', ' The Day of the Stars ', book= " Water Margin ");
Output Result:
Parameter length is: 4 The title of the parameter is: timely rain characters from the water Margin
This article is from the "Hong Dachun Technical column" blog, please be sure to keep this source http://hongdachun.blog.51cto.com/9586598/1766917
Functions in Python