<> Cyclic structure

Go on .

<>for loop

It is usually used for traversal of iteratable objects .
be careful , When the variables in circulation come out, the extracorporeal circulation will fail
for Circular format :
for variable in Iteratable object : Loop body statement
example :
for x in (1,2,3,4,5): print(x)
For iteratable objects
character string , Output the characters in the string in turn .

Dictionaries
Key of dictionary

or

Dictionary values

Key pair of dictionary

range
range(start,end,step)
start: Starting value , Do not write default 0;end: End value ;step: step , Default to 1.

<>for Syntactic else

Usage and while Of else equally
for variable in Iteratable object Circulatory body else Statement block
I'm going to do some work :
b=['name','age','type','number'] a=[] for i in range(4): an=input(' Please input {0}:'.
format(b[i])) a.append(an) print(' Input completed ',end='! ') if an=='q': print(' Active exit entry ')
break else: c=dict(zip(b,a)) print(' Input completed , The input result is {0}'.format(c))
normal operation : Will carry out else Statement of

break In this case , Not implemented else Statement in

<>break sentence

Can be used for while and for loop , Used to receive the entire loop , When there are nested loops ,break Statement can only jump out of the nearest layer .

<>continue sentence

End this cycle only , The whole cycle continues .
continue After that, it will be prompted that it will not run .

Here's an example : Pay attention to the output
x=0 while True: x+=1 print(' The third {0} round '.format(x),end='\t') a=input() if a=='q':
print('break,circle is over',end='\t') break else: print('no break','\t') if a
== 'c': print('continue,just jump one circle') continue print('it`s wrong ,
continue isn`t work!') else: print('no break and no continue,a full circle')

<> Nested loop exercise

1. Realize such an array

My way of writing :
for x in range(5): for i in range(5): if i<4: print(x,end='\t') else: print(x,
end='\n')
Writing in class
for x in range(5): for i in range(5): print(x,end='\t') print()
Still young , I didn't expect to go straight print() Empty output for line feed
2. Print the multiplication table below

My way of writing
for x in range(1,10,1): for i in range(1,x+1,1): print(str(x),'*',str(i),'=',x*
i,end='\t') print()

What we talked about in class is used .format To format the output
print("{0}*{1}={2}".format(x,i,x*i),end='\t')

3. Use lists and dictionaries to store the following information , And print out the salary higher than 15000 Data for

I wrote it :
l1={'name':' Gao Xiaoyi ',' Age ':'18',' salary ':30000,' city ':' Beijing '} l2={'name':' Gao Xiaoer ',' Age ':'19',
' salary ':20000,' city ':' Shanghai '} l3={'name':' Gao Xiaowu ',' Age ':'20',' salary ':10000,' city ':' Shenzhen '} a=[l1,l2,
l3] for x in a: if x.get(' salary ')>=15000: print(x)

The idea is the same this time , Don't write the code in class .

<> Optimization of loop code

1. Minimize unnecessary calculations within the loop ;
2. In nested loop, forgive and reduce the calculation of inner layer , Take the calculation out ;
3. Fast algorithm of local variable query , Try to use local variables .

<> use zip() Do parallel iterations

There are other ways to do it , It's just that zip This effect can be achieved

<> Inferential creation sequence

<> List derivation

Generate list objects
[ expression for item in Iteratable object ] a=[x**2 for x in range(1,5,1)] print(a)

or
[ expression for item in Iteratable object if Conditional judgment ] a=[x**2 for x in range(1,10,1) if x%2==0] print
(a)

The more complicated ones can even be written :
a=[(x,y)for x in range(3) for y in range(3)] print(a)

Whole life
a=['{0}*{1}={2}'.format(x,y,x*y) for x in range(1,10,1) for y in range(1,x+1,1)
] count=0 for i in range(0,9,1): for b in range(0,i+1,1): print(a[count],end=' '
) count+=1 print() print(' multiplication table ')

<> Dictionary derivation

Generate dictionary object
{key_expression : value_expression for expression in Iteratable object } a1=['name','age','type']
a2=['temmie',23,'dog'] a={a1[i]:a2[i] for i in range(2)} print(a)

A more useful example was given in class : Count the number of letters in a sentence :
text='i am temmie!temmie!!temmie!!!' a={c:text.count(c) for c in text} print(a)
Because the key of the dictionary cannot be repeated , So all the characters should have appeared , But each character appears only once .

<> Set derivation
{expression for expression in Iteratable object }
It's like a dictionary , I won't show it here .

<> Generator derivation ( Generating tuples )

be careful : The generator can be run only once . A generator is an iterative object , It can be used as an iterative object .
gnt=(x for x in range(1,100) if x%9==0) for x in gnt: print(x,end=' ')

<> practice : Draw concentric circles of different colors

First, add the grammar of two little turtles :
1. You can assign variables to simplify the input :t=turtle.Pen(), In this way, it can be written directly when called later t.circle To simplify the input code .
2.turtle.done() You can keep the drawn window open ( In the past, my screenshots were all closed debug Here's a screenshot , Gan !)
3.turtle.speed() To set the drawing speed
import turtle as t t.width('5') t.speed(0) co=('red','orange','yellow','green',
'cyan','blue','purple') for i in range(1,7,1): t.color(co[i]) t.penup() t.goto(0
,-50*i) t.pendown() t.circle(50*i) t.done()

<> practice : Draw chessboard
import turtle as t t.width('5') t.speed(0) for f in range(0,2,1): for i in
range(0,5,1): if f==0: t.penup() t.goto(-100,50*i) t.pendown() t.goto(100,50*i)
else: t.penup() t.goto(50*(i-2),0) t.pendown() t.goto(50*(i-2),200) t.done()

<> function

Functions are reusable blocks of program code . It's the encapsulation of the code , Added function call , Transfer parameters , Return calculation results and other contents .
Query function documents can be used :
help( Function name .__doc__)

<>python Classification of functions in

1. Built in functions : All we can use directly are built-in functions
2. Standard library functions : We passed import Import library , And then use the function .
3. Third party library function : Download and install in the community , use import Imported third party functions .
4. User defined function : We create our own functions .

<> How to define function :
def Function name ([ parameter list ]): ''' Document string ( Explanatory notes )''' Function body / Several sentences
For multiple parameters **,** separate . Function should be preserved without parameters .
example :
establish
def temmie(n): for i in range(1,n+1,1): print('temmie','!'*i)
call
temmie(5)

<> Formal parameter and actual parameter

Formal parameters are used when defining functions , Is a local variable , The part beyond the function will be invalid . Formal parameters do not need to specify a type , The actual parameter and the formal parameter should be corresponding one by one .
def Function name ( Formal parameter 1, Formal parameter 2…)
The argument is when the function is called , The parameters passed are called arguments .
Function name ( Actual parameters 1, Actual parameters 2…)

<> The return value of the function

return Statement can be written or not , Do not write default return None.
Use time format :return expression
return The following statement is not executed .
object = Function name ( Actual parameters ), This gives the return value to the object .
A function is also an object , You can also not pass it to other variables , Use directly as an object .
When multiple values are to be returned , You can use the list , Dictionary to return multiple data .

<> Global variable and local variable ( Scope of variable )

The module in which a variable works is called the scope of the variable . The variables with the same name in different scopes have no influence on each other .
global variable ::
 1. Variables declared outside function and class definitions . The scope is the defined module , Start from the defined position until the end of the module ;
 2. Global variables reduce the versatility and readability of functions , The use of global variables should be avoided as far as possible ;
 3. Global variables are generally used as constants ;
 4. Function to change the value of the global variable , Need to use global Make a statement ;
local variable ::
 1. In function body ( Include formal parameters ) Declared variables ;
 2. References to local variables are faster than references to global variables , Priority to use ;
 3. If the local variable has the same name as the global variable , This hides global variables within the function , Use only local variables with the same name . If you want to use it, use it global Let's make a statement .
Output Global , local variable
Use the following statement
print(locals()) print(globals()) a=100 b=200 def temmie_num(): a=1000 print(a)
global b b=400 print(' This is a local variable ',locals()) print(' This is a global variable ',globals()) temmie_num()

<> Transfer of parameters

The parameter passing of function is essentially : Assignment operation from real parameter to formal parameter .
1. For variable objects
Dictionaries , list , aggregate , Custom objects, etc , The delivery operation is actually the address of the delivered content . Is to operate on the same object .
2. For immutable objects
number , character string , tuple ,function etc. , The pass operation creates a new object .
a=100# number , Immutable object b=[200]# list , Variable object print(type(a),type(b)) print('a And b Your address ',id(a),id(b
)) def temmie(m,n): print('m And n Your address ',m,id(m),n,id(n),' Address passed in ') m=m*2 n.append(20)
print('m And n Your address ',m,id(m),n,id(n)) temmie(a,b)#a It's immutable ,b It's a variable object print(a,b)

But I had a little doubt when I tried , If the list operation is changed to n=n*2 In my words , Its address will change .

<> Shallow copy (copy) And deep copy (deepcopy)

Shallow copy : Do not copy the contents of the sub object , It's just a reference to a child object .
Deep copy : Even the memory of the sub object will be copied , Modifications to child objects do not affect the source object .
Need to import when using copy modular
Let's test it with code :
import copy a=[10,20,[30,40]] b=[50,60,[70,80]] a_c=copy.copy(a) b_c=copy.
deepcopy(b) a_c[2][1]=100 print(a,'\n',a_c) b_c[2][1]=100 print(b,'\n',b_c)
print('a Element address of :',a[0],':',id(a[0]),a[1],':',id(a[1]),a[2][0],':',id(a[2][0]),a[2]
[1],':',id(a[2][1])) print('a_c Element address of :',a_c[0],':',id(a_c[0]),a_c[1],':',id(a_c[1
]),a_c[2][0],':',id(a_c[2][0]),a_c[2][1],':',id(a_c[2][1])) print('b Element address of :',b[0]
,':',id(b[0]),b[1],':',id(b[1]),b[2][0],':',id(b[2][0]),b[2][1],':',id(b[2][1]))
print('b_C Element address of :',b_c[0],':',id(b_c[0]),b_c[1],':',id(b_c[1]),b_c[2][0],':',id(
b_c[2][0]),b_c[2][1],':',id(b_c[2][1]))
result :

Now I'll show my understanding with pictures and pictures :

in other words , If list a There is a small book , This little book remembers how many elements it contains , Where are the elements , Shallow copy is just a list a It's a copy of the same one , And the list a List contained in b My little book is the same as before ; A deep copy copies all the books .

<> Several types of parameters

<> Location parameter

Function call , Arguments are passed in positional order by default , Number and parameter matching is required . Parameters passed by location , be called : Location parameter

<> Default value parameter

for example :def fuction1(a,b,c=1,d=2)
this side c and d This is the default parameter , These values are used by default if they are not given when the function is called , If given, the input value is used . The default parameter must be placed at the end

<> Named parameters

as :def fuction1(a,b,c)
Write on call fuction(c=1,b=2,a=10) Then and write fuction(10,2,1) The effect is the same , But it can be written out of order .

<> Variable parameters

* *param, Collect multiple parameters into a tuple object .
* **param, Collect multiple adoption numbers into a dictionary object . def temmie(a,b,*c): print(a,b,c) def temmie01(a,b,
**c): print(a,b,c) temmie(1,2,3,4,5,6) temmie01(1,2,name='temmie',age=23)
# Pay attention to the way the dictionary says it !!

<> Forcing named parameters

For the above variable parameters , If it comes first , There will be values that do not know from where to which belong to this variable parameter , So if the function is defined as :
*def fuction01(a,b,c)
In this form , Call should write :
fuction01(1,2,3,4,b=1,c=2)
Write the name in this way , Everything else is not specified *a Content of .

<>lambda Expressions and anonymous functions

lambda Expressions can be used to declare anonymous functions , It's a simple way , How to define a function on the same line .
lambda Only one expression is allowed , Cannot contain complex statements , The result of the expression is the return value of the function .
lambda arg1,arg2...:< expression >
arg1,arg2… Equivalent to the parameters of a function ,< expression > Equivalent to function body .

<>eval function

String str Evaluates as a valid expression and returns the result of the evaluation .
eval(source[, globals[, locals]]) -> value
Let's do the whole job :
while True: message=input('temmie say:') if message=='q': print('tteemmiiee
say:see ya!!!!',end='') break else: print('tteemmiiee alsooo say:',end='') eval(
message)

<> Recursive function

Recursive functions refer to : Call your own functions , Call yourself directly or indirectly inside the function body .
Each recursive function must contain the following two parts :1. Termination conditions : Indicates when the recursion ends , Generally used for return values , Don't call yourself again ;2. recursive procedure : Put the first n The value of step and step n-1 Step correlation .
Recursive functions take up a lot of resources , Use with care .
example : Calculate factorial
def fuction01(n): if n==1: return 1 else: return n*fuction01(n-1) a=fuction01(5
) print(a)

<> Nested function ( Internal function )

A function defined inside a function
this is it :
def outer_fuction(): Code block def inner_fuction(): Code block inner_fuction()# The outer function calls the inner function
outer_fuction()# Using external functions
be careful , An internal function can only be used by this external function , The inner function cannot be called from another location .
effect : encapsulation : Nested functions cannot be accessed externally .2. Avoid code duplication inside functions .3. closure ( Not for the time being )

Technology
©2020 ioDraw All rights reserved
Java exercises 1: Simply define a car class New photo album app launched by Microsoft : Using cross platform framework React Native to write Chapter two Fundamentals of programming Programming exercises pandas Time order of webpack Code segmentation import()Vue slot slot: Default slot , Named slot , Scope slot Fundamentals of data analysis ——R language ( Processing missing values )C++ Implementation of matrix meteor shower effect PostMan Advanced Usage , Interface MD5+Secret autograph Sign The 12th Blue Bridge Cup B group C/C++ Provincial competition