for语法
for 临时变量 in 序列:
序列中存在待处理元素则进入循环体执行代码
range
根据指定的开始位置、结束位置,以及步长,生成数字队列
- 原型:range(start, stop[, step])
- 在for中使用:
for 临时变量 in range(…):
列表中存在待处理元素则进入循环体执行代码
例子
#求100以内的素数
nums = [True]*100
for i in range(2,100):
for j in range(2,i):
if i % j == 0:
num[i]= False
for i in range (2,100):
if nums[i]:
print (i,end = ',')
#求杨辉三角
n = int(input('请输入三角形高度:'))#层数
layer = 1#当前层
values = [1]#当前层内容
while layer <= n:
new_values = [1]#下一层内容
index = 0#绘制元素编号
while index < len(values):
print('%d '%values[index],end='')
if (index < len(values) - 1):
new_values.append(values[index]+ values[index + 1])
index += 1
new_values.append(1)
values = new_values
print('')
layer += 1