table of Contents
Through the loop by the number of cycles, a structure traversal circulation operation is formed
randow library (random number generation)
Through the loop , the number of press cycles through the loop structure formed of a Run
for <loop variable> in <traverse Structure>:
<Statement block>
Each cycle, the resulting element into the loop variable, and executes a block of statements;
Counting cycle:
for i in range(N)#执行n次,每次i+1
<语句块>
for i in range(M,N,K)#执行特定次,N-M次,步长为K
<语句块>
String traversal cycle:
for c in s:#s是字符串,遍历完每个字符截止
<语句块>
List traversal cycle:
for item in ls :#ls是一个列表,遍历其每个元素
<语句块>
File traversal cycle
for line in fi:#fi是一个标识符,遍历其每行
<语句块>
Infinite loop:
while <条件>:
<Statement block>
Reserved words, BREAK, the Continue , with c
Advanced Usage:
while<条件>:
<语句块>
else:
<语句块>#for循环一样可以用,若循环里没有发生break退出,即执行else的内容
randow library (random number generation)
Substantially random number function: seed (seed) in generating a random number seed corresponding to the reproducible results random (): generates a decimal from 0.0 to 1.0
randint (a, b) generating an integer between ab
randrange (m, n [, k ]) between mn, in steps of k
getrandbits (k) to generate a random number k bit long
Uniform (A, B) , a random decimal between ab
choice (seq) from a randomly selected sequence number
shuffle (seq) in which the elements are arranged randomly
Pi Calculated:
#蒙特卡洛方法算圆周率
from random import random
from time import perf_counter
DARTS = 1000*10000
hits = 0.0
start = perf_counter()
for i in range(DARTS):
x,y = random(),random()
dist = pow(x ** 2 + y ** 2,0.5)
if dist <= 1.0:
hits += 1
pi = 4 *(hits/DARTS)
print("圆周率为{}",format(pi))
print(“程序运行的时间为:{}”format(perf_counter()-start))