程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning (7): range () object &nested loop &99 multiplication table &

編輯:Python

Python Today's share :

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

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

Nested loop :

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

multiplication table

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

Use lists and dictionaries to store table data

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 sentence

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

continue sentence :

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

else sentence

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

Loop code optimization :

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

Use zip() And iterate

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

Inferentially create sequences

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 derivation

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

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

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

Generator derivation ( Generate tuples )

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="")

Draw concentric circles

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 

Drawing board

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

Function usage and underlying analysis

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

Function introduction

The basic concept of function :

1. A program consists of tasks ; A function represents a task or a function
2. Function is a general mechanism for code reuse

python Classification of functions :

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

Definition and use of functions

def Function name ([ parameter list ])
’‘’ docstring ‘’‘
The body of the function / Several sentences

Formal parameters and actual parameters

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved