python循环函数 python循环累加求和

python关于for循环的几个函数for ... in ...
// for ... in 字符串
for i in 'abc':
print(i)
'''
a
b
c
'''
// for ... in 数组
for i in ['a', 'b', 'c']:
print(i)
'''
a
b
c
'''
// for ... in 元组
for i in ('a', 'b', 'c'):
print(i)
'''
a
b
c
'''
// for ... in 字典(得到python循环函数的是字典python循环函数的key)
for k in {'学号':30,'姓名':'小明'}:
print(k)
'''
姓名
学号
'''
// for ... in 字典.items()(得到python循环函数的是字典python循环函数的key, value)
for k, v in {'学号':30,'姓名':'小明'}.items():
print(k, v)
'''
姓名 小明
学号 30
'''
for ... in range(...)
// for ... in range(num)
for i in range(3):
print(i)
'''
1
2
'''
// for ... in range(num1, num2)
for i in range(1, 3):
print(i)
'''
1
2
'''
// for ... in range(num1, num2, num3)
for i in range(3, 1, -1):
print(i)
'''
3
2
'''
for i in range(1, 5, 2):
print(i)
'''
1
3
'''
倒叙
for i in reversed([1,2,3,4]):
print(i)
’‘’
4
3
2
1
‘’‘
又想得到遍历次数python循环函数 , 又想得到数组值
for i,e in enumerate(array):
for i,e in enumerate(['21dw', 55, 22, 'rw']):
print(i, e)
'''
0 21dw
1 55
2 22
3 rw
'''
列表生成式
[...for ... in array]]
print([x * x for x in [2, 34, 324, 43]])
【python循环函数 python循环累加求和】'''
[4, 1156, 104976, 1849]
'''
//相当于
list = []
for x in [2, 34, 324, 43]:
list.append(x * x)
print(list)
python循环、递归for 变量 in range(次数):被执行python循环函数的语句变量:表示每次循环的次数python循环函数 , 0-1之间
range(n)n表示产生0到n-1的整数序列共N个range(m,n)产生m到n-1的整数序列python循环函数 , 共n-m个
循环for语句:for 循环变量 in遍历结构:语句体1else:语句体2
无限循环: while条件: 语句块
while 条件:语句体1 else: 语句体2
循环保留字:breakcontinue
方法1:from random import random
from time import perf_counter
DARTS=1000
hits=0.0
start =perf_counter()
for i in range(1,DARTS+1):
x,y=random(),random()
dist=pow(x**2+y**2,0.5)
if dist=1.0:
hits =hits+1
pi=4*(hits/DARTS)
print("圆周率是:{}".format(pi))
print("运行时间是{:.5f}s".format(perf_counter()-start))
方法2:
pi=0
n=100
for k in range(n):
pi += 1/pow(16,k)*(\
4/(8*k+1)-2/(8*k+4) - \
1/(8*k+5) - 1/(8*k+6))
print("圆周率值是:{}".format(pi))
def 函数名 (0个或者多个):函数体renturn 返回值
def 函数名 (非可选参数python循环函数 , 可选参数):函数体renturn 返回值
参数传递的两种方式:位置传递python循环函数,名称传递
科赫雪花:
import turtle
def koch(size,n):
if n==0:
turtle.fd(size)
else:
for angle in [0,60,-120,60]:
turtle.left(angle)
koch(size/3,n-1)
def main():
turtle.setup(400,200)
turtle.penup()
turtle.pendown()
turtle.pensize(2)
l=3
koch(600,l)
turtle.right(120)
turtle.pencolor('blue')
koch(600,l)
turtle.right(120)
turtle.pencolor('red')
koch(600,l)
turtle.speed(3000)
turtle.hideturtle()

推荐阅读