range() object & Nested loop & multiplication table & Use lists and dictionaries to store table data &break sentence &continue sentence &else sentence & Loop code optimization & Use zip() And iterate & The derived type & function
range Object is an iteratable object , Used to generate a sequence of numbers in a specified range . The format is : range(start,end,step)
The generated numerical sequence is from start Start to end end ( It doesn't contain end). If not filled in start, Default from 0 Start .step It's an optional step , The default is 1. Here are some typical cases :
for i in range(10) Generating sequences :0 1 2 3 4 5 6 7 8 9
for i in range(3,10) Generating sequences :3 4 5 6 7 8 9
for i in range(3,10,2) Generating sequences :3 5 7 9
One circulation can be embedded in another , Commonly referred to as “ Nested loop ”
for x in range(5):
for y in range(5):
print(x, end="\t")
print()
# The result is :
# 0 0 0 0 0
# 1 1 1 1 1
# 2 2 2 2 2
# 3 3 3 3 3
# 4 4 4 4 4
for x in range(1, 10):
for y in range(1, x+1):
print("{0}x{1}={2}".format(y, x, x*y), end="\t")
print()
# The result is :
# 1x1=1
# 1x2=2 2x2=4
# 1x3=3 2x3=6 3x3=9
# 1x4=4 2x4=8 3x4=12 4x4=16
# 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
# 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
# 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
# 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
# 1x9=9 2x9=18 3x9=27 4x9=36 5x9=45 6x9=54 7x9=63 8x9=72 9x9=81
r1 = dict(name=' higher ', age=16)
r2 = dict(name=' high ', age=17)
r3 = dict(name=' three ', age=18)
tb = [r1, r2, r3]
for x in tb:
print(x)
#break Statements can be used for while and for loop , To end the cycle , When there are nested loops ,break Statement can only jump out of the nearest loop
while True:
a = input(" Please enter a character ( Input q perhaps Q end ):")
if a.upper().__eq__('Q'):
print(" The loop ends ")
break
else:
print(a)
Used to end this cycle , Go on for the next time . When multiple loops are nested ,continue It is also applied to the nearest layer of loop
while True:
a = input(" Please enter a character ( Input q perhaps Q end ):")
if a.upper().__eq__('Q'):
print(" The loop ends ")
break
else:
continue
while,for The loop can be accompanied by a else sentence ( Optional ), If for,while The statement is not break End of sentence , Will perform else Clause , Otherwise, do not execute
while Conditional expression :
else:
Sentence block
perhaps :
for Variable in Iteratable object :
The loop body
# The result is :
# 0
# 1
# 2
# 3
# Output completed
for i in range(4):
print(i)
else:
print(" Output completed ")
1. Minimize unnecessary calculations inside the loop
2. Nested loop , Minimize the calculation of inner circulation , Lift out as much as possible
3. Local variable query is faster , Try to use local variables
Other optimization tools :
1. Concatenate multiple strings , Use join() Instead of using +
2. List to insert and delete elements , Try to operate at the end of the list
We can go through zip() Function iterates over multiple sequences in parallel ,zip() Function in the shortest sequence “ run out ” It will stop when it's over
name = (" test 1", " Test two ")
age = (16, 18)
The result is :
test 1-16
Test two -18
for name, age in zip(name, age):
print("{0}-{1}".format(name, age))
A derivation is a way for one or more iterators to quickly create a sequence . It can combine loop and conditional judgment , To avoid lengthy code , The derivation is typical Python style , Will use it to represent that you have exceeded Python Beginner's level
List objects are generated by list derivation , The grammar is as follows :
[ expression for item in Iteratable object ]
perhaps :{ expression for item in Iteratable object if conditional }
# The result is :[1, 2, 3, 4]
print([x for x in range(1, 5)])
# The result is :[10, 20, 30]
print([x*2 for x in range(1, 20) if x%5 == 0])
cells = [(row, col) for row in range(1, 10) for col in range(1, 10)] # Two loops
for cell in cells:
print(cell)
Dictionary derivation generates dictionary objects , The format is as follows :
{key_expression : value:expression for expression in Iteratable object } Similar list derivation , Dictionary derivation can also add if conditional , Multiple for loop
my_text = 'i love you'
char_count = {
c:my_text.count(c) for c in my_text}
# The result is :{'i': 1, ' ': 2, 'l': 1, 'o': 2, 'v': 1, 'e': 1, 'y': 1, 'u': 1}
print(char_count)
Set derivation generates a set , The syntax is similar to that of a list derivation :
{ expression for item in Iteratable object }
perhaps :{ expression for item in Iteratable object if conditional }
# The result is :{99, 36, 72, 9, 45, 81, 18, 54, 90, 27, 63}
print({
x for x in range(1, 100) if x%9 == 0})
Tuples have no derivation , What it generates is a " Generator object ", A generator can only run once . The first iteration can get the data , The second iteration found that the data was gone .
gnt = (x for x in range(1, 100) if x%9 == 0)
for x in gnt:
print(x, end="")
for x in gnt:
print(x, end="")
import turtle
t =turtle.Pen()
my_colors = ("red", "green", "black")
t.width(4)
# Execution speed
t.speed(0)
for i in range(100):
t.penup()
t.goto(0, -i*10)
t.pendown()
t.color(my_colors[i%len(my_colors)])
t.circle(10+10*i)
# t.goto(0, -50)
# t.circle(100)
# t.goto(0, -100)
# t.circle(150)
turtle.done() # The program is finished , The window is still there
import turtle as t
# Drawing board
width = 30
num = 18
x1 = [(-400, 400), (-400+width*num, 400)]
y1 = [(-400, 400),(-400, 400-width*num)]
t.speed(10)
for i in range(0, 19):
t.penup()
t.goto(x1[0][0], x1[0][1]-30*i)
t.pendown()
t.goto(x1[1][0], x1[1][1]-30*i)
for i in range(0, 19):
t.penup()
t.goto(y1[0][0]+30*i, y1[0][1])
t.pendown()
t.goto(y1[1][0]+30*i, y1[1][1])
t.done()
Functions are reusable blocks of program code , Function function , It can not only realize the reuse of code , Better code consistency . Consistency means , Just modify the code of the function , Then all places where the function is called can be reflected
When writing a function , It just encapsulates the code , And added function call , Pass parameters , Return calculation results, etc
1. A program consists of tasks ; A function represents a task or a function
2. Function is a general mechanism for code reuse
1. Built in functions : What we use str(),list(),len() These are built-in functions , We can use it directly .
2. Standard library functions : We can go through import Statement import library , Then use the function defined in it
3. Third party library functions :Python The community also provides a lot of high-quality Libraries , After downloading and installing these libraries , through import Statement import , You can then use the functions of these third-party libraries
4. User defined functions : User defined functions , This obviously suits us better
def Function name ([ parameter list ])
’‘’ docstring ‘’‘
The body of the function / Several sentences
Formal parameters do not need to declare types , There is no need to specify the return value type of the function
The argument list must correspond to the formal parameter list one by one
a and b Is a formal parameter
def a(a, b):
print(a)
1 and 2 For reference
a(1, 2)
# docstring ( Comments on functions )
def a(a, b):
''' Here's the function annotation '''
print(a)
a(1, 2)
# Print notes
help(a.__doc__)