Getting started with python-2: functions and dictionaries

Functions

Named code blocks used to complete specific tasks.

Function structure

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

Parameters

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

Defaults

We can define our own default values in the parameters

>>> def hello(x,y):...return x-y
...>>> hello(3,7)-4

return value

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

Combining functions and while loops

>>> 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

Delivery list

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!

Pass any number of arguments

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')

Dictionary

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

Use dictionary

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}

Traverse dictionary

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)

Dictionary list

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

Getting started with python-2: functions and dictionaries
Getting started with Python(18)
Getting started with Python(9)
Getting started with Python(4)
Getting started with Python (2)
Getting started with python-1
Getting started with Python(14)
Getting started with Python(7)
Getting started with Python(17)
Getting started with Python(15)
Getting started with Python(10)
Getting started with Python(11)
Getting started with Python(6)
Getting started with Python(3)
Getting started with Python(12)
Getting started with Python(5)
Getting started with Python (18+)
Getting started with Python(13)
Getting started with Python(16)
Getting Started with Python-4: Classes and Objects
Getting started with Numpy in Python
04. Conditional Statements for Getting Started with Python
Getting started with Ubuntu
Getting started python learning steps
Played with stocks and learned Python
07. Python3 functions
Python functions
Python implements singly linked lists and dictionaries
How to get started quickly with Python
Functions in python
Python and Go
How to read and write files with Python
Python introspection and reflection
python requests.get with header
Play WeChat with Python
[python] python2 and python3 under ubuntu
Web Scraping with Python
Python deconstruction and packaging
Python3 configuration and entry.md