Named code blocks used to complete specific tasks.
The function code block starts with the def keyword, followed by the function identifier name and parentheses (). Any incoming parameters and arguments must be placed between parentheses. The parentheses can be used to define parameters. The first line of the function can optionally use a docstring—used to store the function description. The function content starts with a colon and is indented. return ends the function, optionally returning a value to the caller. Return without expression is equivalent to returning None.
Create a simple hello function
>>> def hello():...print('hello,world')...>>>hello()
hello,world
When defining a function, the parameters in () are formal parameters, and the input values are actual parameters. In the example below, hello(x) is the formal parameter and 7 is the actual parameter.
>>> def hello(x):...return x
>>> hello(7)7
We can define our own default values in the parameters
>>> def hello(x,y):...return x-y
...>>> hello(3,7)-4
The value returned by the function is the return value
>>> def hello(x):...return x*3...>>>hello(3)9
If the incoming object is not an unmodifiable object, such as an integer or floating-point number, although the value is modified in the function, the original object will not be changed.
If ten lists are passed in, the list is still referenced in the function. If the function changes, the original variables will also change
>>> def hello(x):... x=2...>>> x=3>>>print(x)3>>>hello(x)>>>print(x)3
We can find that x has not become 2
>>> def hello(x):... x[1]=2>>> x=[2,4,6]>>>hello(x)>>>print(x)[2,2,6]
You can see that x changed the value after executing this function
Back to dictionary
>>> def person(name,score):
person={'name':name,'score':score}return person
>>> person("Tom",90){'name':'Tom','score':90}
Nested functions inside functions
The following example is a nested function in a function. The return value returns a function, and the x in it is the parameter x of the fun function.
>>> def fun(x)
def fun2(y):return x+y
return fun2
>>> a=fun(3) ######When we set a=fun(3)When we are equivalent to passing in the parameter x=3,The returned a is a function of fun2.
>>> type(a)<class'function'>>>>a(8) ######If we pass in the parameter again, it is equivalent to passing in the y value.
11
>>> def person(name,score):
person={'name':name,'score':score}return person
while True:print('please tell me your name and score:')
name=input('name:')if name =='q':break
score=input('score:')if score =='q':break
people=person(name,score)print(people)
please tell me your name and score:
name:Tom
score:80{'name':'Tom','score':'80'}
please tell me your name and score:
name:q
We can add the contents of the loop to pass the list in the function
>>> def hello(x):...for name in x:...print('hello'+name+'!')...>>> t=['tom','mary','hh']>>>hello(t)
hellotom!
hellomary!
hellohh!
Add * to the formal parameter, which means that more than one actual parameter can be passed in
>>> def vegetable(*x):...print(x)...>>>vegetable('spinage')('spinage',)>>>vegetable('spinage','chinese leaf')('spinage','chinese leaf')
In python, a dictionary is a series of key-value pairs. Each key is associated with a value. The key can be used to access the corresponding value. The key can be a number, a string, a list or even a dictionary.
If you want to save the names and grades of classmates in a class in a list, you can use the list plus tuples
data=[('tom',89),('mary',90),('haha',100)]
data
[(' tom',89),('mary',90),('haha',100)]
For the above list, if we want to query whether there is tom in the list, we need to compare everything in the list, which will be slower, so we want to query the corresponding value according to a certain feature, which is in the form of a dictionary. A key-value pair composed of key_value, the data structure is called map, and python is a dictionary
Let's create a dictionary
scores={'tom':90,'mary':80,'mike':70,'jak':100}
scores
{' tom':90,'mary':80,'mike':70,'jak':100}
len(scores)###See how many key-value pairs there are
4
scores['tom'] ###Get the corresponding value 90 according to the key tom
90
scores.get('tom')
90
scores['bob']=88 ###Add key-value pairs to the dictionary
scores
{' tom':90,'mary':80,'mike':70,'jak':100,'bob':88}
scores['tom']='toom' ###Modify the value in the dictionary
scores
{' tom':'toom','mary':80,'mike':70,'jak':100,'bob':88}
del scores['tom'] ####Delete key-value pair
scores
{' mary':80,'mike':70,'jak':100,'bob':88}
scores
{' mary':80,'mike':70,'jak':100,'bob':88}
for key,value in scores.items(): ###Traverse all key-value pairs
print(key)print(value)
mary
80
mike
70
jak
100
bob
88
for name in scores.keys(): #####Loop through all keys
print(name)
mary
mike
jak
bob
for score in scores.values(): ####Iterate over all values
print(score)
807010088
scoresheet={'mike':(60,80,90),'tom':(80,70,99),'mary':(78,90,57)}for key in scoresheet.keys():print(key,scoresheet[key])
mike(60,80,90)tom(80,70,99)mary(78,90,57)
Include dictionary in list
alion={'hh':1,'hhw':2,'hhh':3}
alion2={'yy':1,'yyy':2,'yyyy':3}
alion3={"uu":1,'uuu':2,"uuuu":3}
alionall=[alion,alion2,alion3]
alionall
[{' hh':1,'hhw':2,'hhh':3},{'yy':1,'yyy':2,'yyyy':3},{'uu':1,'uuu':2,'uuuu':3}]
for alien in alionall:print(alien)
{' hh':1,'hhw':2,'hhh':3}{'yy':1,'yyy':2,'yyyy':3}{'uu':1,'uuu':2,'uuuu':3}
for alien in alionall[:2]:print(alien)
{' hh':1,'hhw':2,'hhh':3}{'yy':1,'yyy':2,'yyyy':3}
Store list in dictionary
apple={'color':['red','yellow'],'shape':['round','square']}
for things in apple.values():print(things)
[' red','yellow']['round','square']
for key in apple.keys():print(key)
color
shape
Include dictionary in dictionary
people={'tom':{'math':80,'english':90},'mary':{'math':90,'english':70}}for name,project in people.items():print(name,project)
tom {'math':80,'english':90}
mary {'math':90,'english':70}
for name,pro in people.items():print(name,pro)
tom {'math':80,'english':90}
mary {'math':90,'english':70}
Recommended Posts