range() 函数
会生成数列range(10),你也可以使用 range(4,9) 指定区间的值,也可以使 range() 以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做’步长’),range(0, 10, 3)、range(-10, -100, -30)。
break 与 continue
break:跳出并停止循环
continue:跳出本次循环
for循环
for floor in range(1, 6):
print(f"当前在{floor}层".center(50, '-'))
if floor == 3:
print("不走三层....")
continue # 停止本次循环,进入下一次循环
for room in range(1, 10):
if floor == 4 and room == 4:
print("见鬼了....die at yong....")
break # 结束本次循环.....
print(f"当前房间是{floor}0{room}室.")
print("hahaha, still here....")
或者
#-------------
for floor in range(1, 6):
print(f"当前在{floor}层".center(50, '-'))
if floor == 3:
print("不走三层....")
continue # 停止本次循环,进入下一次循环
for room in range(1, 10):
if floor == 4 and room == 4:
print("见鬼了....die at yong....")
break # 结束本次循环.....
print(f"当前房间是{floor}0{room}室.")
else:# 当循环正常结束时输出
print("hahaha, still here....")
小例子100以内的素数
for i in range(2, 101):
is_prim_num = True
for j in range(2, i):
if i % j == 0:
is_prim_num = False
break
if is_prim_num:
print(i, " is prim num")
# 法2
for i in range(2, 101):
for j in range(2, i):
if i % j == 0:
break
else:
print(i, " is prim num")
while循环
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('循环结束。')
#------------
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
else: # 当循环正常结束时输出,如果中间break则不显示
print('循环结束。')