Home >Backend Development >Python Tutorial >Introduction to Python Function Basics
This article will introduce how to organize statements into functions, as well as the concept of parameters and their use in programs. Friends in need can refer to it
Pythond functions are written by a new statement, namely def , def is an executable statement - the function does not exist until Python runs def.
Function is passed by assignment, and parameters are passed to the function by assignment
The def statement will create a function object and assign it to a variable name. The general format of the def statement is as follows:
Copy code The code is as follows:
def function_name(arg1,arg2[,...]):
statement
[return value]
The return value is not required. If there is no return statement, Python returns the value None by default.
Naming rules for function names:
Function names must start with an underscore or a letter, and can contain any combination of letters, numbers, or underscores. No punctuation marks can be used;
Function names are case-sensitive.
Function names cannot be reserved words.
Python uses the concept of namespace to store objects. This namespace is the area where the object acts. Different objects exist in different scopes. The following are the scope rules for different objects:
Each module has its own global scope.
The object defined by the function belongs to the local scope and is only valid within the function and will not affect the objects in the global scope.
The assigned object is of local scope unless declared using the global keyword.
LGB rules are the rules for Python to find names. The following are the LGB rules:
1. Most name references are searched in three scopes: local (Local) first, then global ( Global), again built-in (Build-in).
Copy code The code is as follows:
>>> a=2
>>> b=2
>>> def test(b):
... test=a*b
... return test
>>>print test(10)
20
b is found in the local scope, and a is found in the global scope.
2. If you want to change the object of the global scope in the local scope, you must use the global keyword.
Copy code The code is as follows:
#Situation when global is not used
>>> name="Jims"
>>> def set():
... name="ringkee"
...
>>> set()
>>> print name
Jims
#The situation after using global
>>> name="Jims"
>>> def set1():
.. . global name
... name="ringkee"
...
>>> set1()
>>> print name
ringkee
3. The 'global' declaration maps the assigned name to the scope of a module that contains it.
The parameters of a function are the bridge between the function and the outside world. It can receive values passed from the outside. The rules for parameter passing are as follows:
4. Assigning a parameter name in a function does not affect the caller.
Copy code The code is as follows:
>>> a=1
>>> def test(a):
... a=a+1
... print a
...
>>> test(a)
2
>>> a
1 # The value of a remains unchanged
5. Changing a variable object parameter in a function will affect the caller.
Copy code The code is as follows:
>>> a=1
>>> b=[1,2 ]
>>> def test(a,b):
... a=5
... b[0]=4
... print a,b
...
>>> test(a,b)
5 [4, 2]
>>> a
1
>>> b
[4, 2] # The b value has been changed
The parameter is an object pointer, and there is no need to define the passed object type. For example:
Copy code The code is as follows:
##>>> def test(a,b):
... return a +b
...
>>> test(1,2) #Numeric type
3
>>> test("a","b") #Character Type
'ab'
>>> test([12],[11]) #List
[12, 11]
Tuples parameters:
def function(*ARG)
Dictionary parameters:
def function(**ARG)
Some function rules:
The default value must be in non-default After the parameters;
In a single function definition, only one tuple parameter (*ARG) and one dictionary parameter (**ARG) can be used.
The tuple parameter must come after the connection parameters and default parameters.
Dictionary parameters must be defined last.
1. Commonly used functions
1.abs(x)
abs() returns the absolute value of a number. If a complex number is given, the return value is the modulus of the complex number.
Copy code The code is as follows:
>>>print abs(-100)
100
>>> ;print abs(1+2j)
2.2360679775
2.callable(object)
callable() function is used to test whether the object is callable, and returns 1 if it can (True); otherwise returns 0 (False). Callable objects include functions, methods, code objects, classes, and class instances that have defined "call" methods.
Copy code The code is as follows:
>>> a="123"
>>> print callable(a )
0
>>> print callable(chr)
1
3.cmp(x,y)
cmp() function Compares two objects x and y, and returns an integer based on the comparison result. If x
Copy code The code is as follows:
>>>a=1
>>>b=2
>>>c=2
>>> print cmp(a,b)
-1
>>> print cmp(b,a)
1
>>> print cmp(b,c)
0
4.pmod(x,y)
pmod(x,y) function Completes the division operation and returns the quotient and remainder.
Copy code The code is as follows:
>>> pmod(10,3)
(3, 1)
> ;>> pmod(9,3)
(3, 0)
5.isinstance(object,class-or-type-or-tuple) -> bool
Test object type
Copy code The code is as follows:
>>> a='isinstance test'
> >> b=1234
>>> isinstance(a,str)
True
>>> isinstance(a,int)
False
> >> isinstance(b,str)
False
>>> isinstance(b,int)
True
The following program shows the isinstance function Use:
Copy code The code is as follows:
def displayNumType(num):
print num, 'is',
if isinstance( num, (int, long, float, complex)):
print 'a number of type:', type(num).__name__
else:
print 'not a number at all!!!'
displayNumType(-69)
displayNumType(99999999999999999999999999L)
displayNumType(565.8)
displayNumType(-344.3+34.4j)
displayNumType('xxx')
The result of running the code is as follows:
Copy code The code is as follows:
-69 is a number of type: int
9999999999999999999999999 is a number of type : long
565.8 is a number of type: float
(-344.3+34.4j) is a number of type: complex
xxx is not a number at all!!!
6.len(object) -> integer
The len() function returns the length of strings and sequences.
Copy code The code is as follows:
>>> len("aa")
2
>>> ; len([1,2])
2
7.pow(x,y[,z])
pow() function returns x as the base, y is the power of the exponent. If a z value is given, the function computes the value of x raised to the y power modulo z.
Copy code The code is as follows:
>>> print pow(2,4)
16
>> > print pow(2,4,2)
0
>>> print pow(2.4,3)
13.824
8.range([lower ,]stop[,step])
range() function can generate a continuous ordered list of integers according to parameters.
Copy code The code is as follows:
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1,10,2)
[1, 3, 5, 7, 9]
9.round(x[,n])
The round() function returns the rounded value of the floating point number x. If the n value is given, it represents the number of digits after the decimal point.
Copy code The code is as follows:
>>> round(3.333)
3.0
>>> round (3)
3.0
>>> round(5.9)
6.0
10.type(obj)
type() function can Returns the data type of the object.
Copy code The code is as follows:
>>> type(a)
>>> type(copy)
>>> type(1)
11.xrange([lower,]stop[,step])
The xrange() function is similar to range(), but xrnage() does not create a list, but returns an xrange object. It behaves like a list, but only calculates list values when needed. This feature can save us memory when the list is large.
Copy code The code is as follows:
>>> a=xrange(10)
>>> print a[ 0]
0
>>> print a[1]
1
>>> print a[2]
2
2. Built-in type conversion function
1.chr(i)
chr() function returns the string corresponding to the ASCII code.
Copy code The code is as follows:
>>> print chr(65)
A
>>> print chr(66)
B
>>> print chr(65)+chr(66)
AB
Copy code The code is as follows:
>>> complex("2+1j")
(2+1j)
>>> complex("2")
(2+0j)
>>> complex(2,1)
(2+1j)
>> ;> complex(2L,1)
(2+1j)
Copy code The code is as follows:
>>> float("12")
12.0
>>> ; float(12L)
12.0
>>> float(12.2)
12.199999999999999
Copy code The code is as follows:
>>> hex(16)
'0x10'
>>> ; hex(123)
'0x7b'
Copy code The code is as follows:
>>> long("123")
123L
>>> ; long(11)
11L
Copy code The code is as follows:
>>> list("hello world")
['h', ' e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> list(( 1,2,3,4))
[1, 2, 3, 4]
Copy code The code is as follows:
>>> int(3.3)
3
>>> int (3L)
3
>>> int("13")
13
>>> int("14",15)
19
Copy code The code is as follows:
>>> min(1,2,3,4)
1
> ;>> min((1,2,3),(2,3,4))
(1, 2, 3)
Copy code The code is as follows:
>>> max(1,2,3,4)
4
> ;>> max((1,2,3),(2,3,4))
(2, 3, 4)
Copy code The code is as follows:
>>> oct(8)
'010'
>>> oct( 123)
'0173'
11.ord(x)
ord() function returns the ASCII code or Unicode value of a string parameter.
Copy code The code is as follows:
>>> ord("a")
97
>>> ; ord(u"a")
97
12.str(obj)
str() function converts the object into a printable string.
Copy code The code is as follows:
>>> str("4")
'4'
>> ;> str(4)
'4'
>>> str(3+2j)
'(3+2j)'
13.tuple (x)
tuple() function converts sequence objects into tuples.
Copy code The code is as follows:
>>> tuple("hello world")
('h', 'e' , 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd')
>>> tuple([1, 2,3,4])
(1, 2, 3, 4)
3. Sequence processing function
1. len(), max() and len() in common functions min() can also be used with sequences.
2.filter(function,list)
When filter() is called, it applies a function to each item in the sequence and returns all the values when the function returns true items, thereby filtering out any items that return a false value.
Copy code The code is as follows:
>>> def nobad(s):
... Return s.find(" bad") == -1
...
>>> s = ["bad","good","bade","we"]
>>> filter(nobad,s)
['good', 'we']
This example filters out all items containing "bad" by applying the nobad() function to all items in the s sequence. item.
3.map(function,list[,list])
The map() function applies a function to all items in the sequence and returns a list.
Copy code The code is as follows:
>>> import string
>>> s=["python", "zope","linux"]
>>> map(string.capitalize,s)
['Python', 'Zope', 'Linux']
map() can also be applied to multiple lists at the same time. For example:
Copy code The code is as follows:
##>>> import operator
>>> s=[1, 2,3]; t=[3,2,1]
>>> map(operator.mul,s,t) # s[i]*t[j]
[3, 4 , 3]
Copy code The code is as follows:
>>> a=[1,2];b=[3,4]; c=[5,6]
>>> map(None,a,b,c)
[(1, 3, 5), (2, 4, 6)]
Copy code The code is as follows:
>>> import operator
>>> reduce(operator.mul,[ 2,3,4,5]) # ((2*3)*4)*5
120
>>> reduce(operator.mul,[2,3,4,5], 1) # (((1*2)*3)*4)*5
120
>>> reduce(operator.mul,[2,3,4,5],2) # (((2*2)*3)*4)*5
240
##5.zip(seq[,seq,...])
zip( ) function combines corresponding items from two or more sequences and returns them in tuple format, stopping after processing all items in the shortest sequence.
Copy codeThe code is as follows:
>>> zip([1,2,3],[4,5],[7 ,8,9])[(1, 4, 7), (2, 5, 8)]
If the parameter is a sequence, zip() will be a tuple The format returns each item, such as:
The code is as follows:
>>> zip((1,2,3,4 ,5))[(1,), (2,), (3,), (4,), (5,)]
>>> zip([1,2,3 ,4,5])
[(1,), (2,), (3,), (4,), (5,)]
4. Other
def statements are executed in real time. When it runs, it creates and assigns a new function object to a variable name. All Python statements are executed in real time, unlike independent The compilation time process like this
Because it is a statement, def can appear wherever a statement can appear--even nested in other statements:
Copy code The code is as follows:
if test:
def fun():
...
else:
def func():
...
...
func()
You can assign the function to a different variable name and call it through the new variable name:
othername=func( )
othername()
Create function
The built-in callable function can be used to determine whether the function is callable:
Copy code The code is as follows:
>>> import math
>>> x=1
>>> y=math.sqrt
>>> ; callable(x)
False
>>> callable(y)
True
Use the del statement to define the function:
Copy code The code is as follows:
>>> def hello(name):
return 'Hello, '+name+'!'
>>> ; print hello('world')
Hello, world!
>>> print hello('Gumby')
Hello, Gumby!
Write a fibnacci Sequence function:
Copy code The code is as follows:
>>> def fibs(num):
result=[0,1 ]
for i in range(num-2):
result.append(result[-2]+result[-1])
return result
>>> fibs(10 )
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs(15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Assigning values to parameters within a function will not change the value of any external variables:
Copy code The code is as follows:
>>> def try_to_change(n):
n='Mr.Gumby'
>> ;> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'
Since strings (and tuples and numbers) are immutable, they will not change when used as parameters, but what happens if a mutable data structure such as a list is used as a parameter:
Copy code The code is as follows:
>>> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'
>>> def change(n):
n[0]='Mr.Gumby'
> ;>> name=['Mrs.Entity','Mrs.Thing']
>>> change(name)
>>> name
['Mr. Gumby', 'Mrs.Thing']
The parameters have changed, which is the important difference from the previous example
Do it again without using a function:
Copy code The code is as follows:
>>> name=['Mrs.Entity','Mrs.Thing']
>>> n=name #One more time, simulate parameter passing behavior
>>> n[0]='Mr.Gumby' #Change list
>>> name
['Mr. Gumby', 'Mrs.Thing']
When two variables refer to a list at the same time, they do refer to a list at the same time. To avoid this situation, you can make a copy of the list. When slicing in a sequence, the returned slice is always a copy, so if you copy the slice of the entire list, you will get a copy:
Copy code The code is as follows:
>>> names=['Mrs.Entity','Mrs.Thing']
>>> n=names[:]
>> > n is names
False
>>> n==names
True
Changing n at this time will not affect names:
Copy code The code is as follows:
>>> n[0]='Mr.Gumby'
>>> n
['Mr.Gumby', 'Mrs.Thing']
>>> names
['Mrs.Entity', 'Mrs.Thing']
>>> change(names[:])
>>> names
['Mrs.Entity', 'Mrs.Thing']
Keyword parameters and default values
The order of parameters can be determined by providing the parameter name (but Parameter names and values must correspond):
Copy code The code is as follows:
>>> def hello(greeting, name):
print '%s,%s!'%(greeting, name)
>>> hello(greeting='hello',name='world!')
hello,world!!
The most powerful thing about keyword parameters is that you can provide default values for parameters in parameters:
Copy code The code is as follows:
>>> def hello_1(greeting='hello',name='world!'):
print '%s,%s!'%(greeting,name)
> >> hello_1()
hello,world!!
>>> hello_1('Greetings')
Greetings,world!!
>>> hello_1(' Greeting','universe')
Greeting,universe!
If you want greeting to use the default value:
Copy the code The code is as follows:
>>> hello_1(name='Gumby')
hello,Gumby!
You can provide any number of parameters to the function, and it is not easy to implement. Difficulty:
Copy code code is as follows:
# & GT; & GT; Def Print_params (*Params):
Print Params
>>> print_params('Testing')
('Testing',)
>>> print_params(1,2,3)
(1, 2, 3)
Mixing common parameters:
Copy code The code is as follows:
>>> def print_params_2(title, *params):
print title
print params
>>> print_params_2('params:',1,2,3)
params:
(1, 2, 3)
>>> print_params_2('Nothing:')
Nothing:
()
The asterisk means "collect the remaining positional parameters ”, if no elements are provided for collection, params is an empty tuple
But keyword parameters cannot be processed:
Copy code The code is as follows:
>>> print_params_2('Hmm...',something=42)
Traceback (most recent call last):
File "
print_params_2('Hmm...',something=42)
TypeError: print_params_2() got an unexpected keyword argument 'something'
Try Use "**":
Copy code The code is as follows:
>>> def print_params(**params):
print params
>>> print_params(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> def parames(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar
>>> parames(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{ 'foo': 1, 'bar': 2}
>>> parames(1,2)
1 2 3
()
{}
>> > def print_params_3(**params):
print params
>>> print_params_3(x=1,y=2,z=3)
{'y': 2 , 'x': 1, 'z': 3}
>>> #Returns a dictionary instead of a tuple
>>> #Combine '#' and '##'
>>> def print_params_4(x,y,z=3,*pospar,**keypar):
print x,y,z
print pospar
print keypar
>>> print_params_4(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1,2)
1 2 3
()
{}
The above is the detailed content of Introduction to Python Function Basics. For more information, please follow other related articles on the PHP Chinese website!