- for 循环
for i in range(5):
if i == 3:
continue
print("loop", i)
print("==========")
运行结果:
for i in range(1, 10, 2): # 表示循环从1开始到10,步长为2
print("loop", i)
print("==========")
运行结果:
2. while 循环
(1)
count = 0
while True:
count += 1
if count == 5:
break
print("第", count, "次打印")
print("==========")
(2)
count = 0
while count < 4:
count += 1
print("第", count, "次打印")
print("==========")
这两种方法结果相同:
以下是一个用 while 循环写的猜数字的小游戏
# Author:Li Xiaolong
from random import randint
num = randint(0, 100)
count = 0
while count < 5:
guess_num = int(input("请输入你所猜测的数字(0-100):"))
if guess_num == num:
print("恭喜你,猜对了!")
break
elif guess_num > num:
print("抱歉,猜大了...")
else:
print("抱歉,猜小了...")
count += 1
if count == 5:
r = input("你猜测次数已达上限,你想要继续猜吗?(y/n):")
if r == 'y':
count = 0
else:
print("游戏结束")