ChuannBlog

2.9 循环控制

while循环

while 条件: 循环体的代码1 循环体的代码2 循环体的代码3

# 2.while循环打印0-9
count = 0
while count < 10:
    print(count)
    count += 1

# 3.while死循环打印ok
while True: #死循环
    print('ok')

# 4.while死循环打印ok2
while 1: #死循环
    print('ok')

# 5.break语句打印0-4
break:跳出本层循环
count = 0
while count < 10:
    if count == 5:
        break
    print(count)
    count += 1

# 6.continue语句不打印4,5,6
continue:跳出本次循环
0 1 2 3 7 8 9
count = 0
while count < 10:
    if count >=4 and count <=6:
        count += 1
        continue
    print(count)
    count += 1

# 7.猜年龄(死循环无限猜)
OLDBOY_AGE = 56
while 1:
    age = input('猜一猜年龄>>: ')
    age = int(age)

    if age > OLDBOY_AGE:
        print('太大了')
    elif age < OLDBOY_AGE:
        print('太小了')
    else:
        print('猜对了')
        break

# 8.猜年龄2(猜三次)(循环条件控制)
OLDBOY_AGE = 56
count = 1
while count <= 3:
    age = input('猜一猜年龄>>: ')
    age = int(age)

    if age > OLDBOY_AGE:
        print('太大了')
        count += 1
    elif age < OLDBOY_AGE:
        print('太小了')
        count += 1
    else:
        print('猜对了')
        break

# 9.猜年龄3(猜三次)(循环体if控制)
OLDBOY_AGE = 56
count = 1
while True:
    if count > 3:
        print('您猜的次数超过限制')
        break
    age = input('猜一猜年龄>>: ')
    age = int(age)

    if age > OLDBOY_AGE:
        print('太大了')
    elif age < OLDBOY_AGE:
        print('太小了')
    else:
        print('猜对了')
        break
    count += 1

# 10.分数变成绩
while True:
    score = input('>>: ')
    score = int(score)

    if score >= 90:
        print('A')
    if score >= 80:
        print('B')
    if score >= 70:
        print('C')
    if score >= 60:
        print('D')
    if score < 60:
        print('E')

# 11.猜年龄4(循环体if控制)(优化版本)
OLDBOY_AGE = 56
count = 0
while True:
    if count > 2:
        break
    age = input('猜一猜年龄>>: ')
    age = int(age)
    if age > OLDBOY_AGE:
        print('太大了')
    if age < OLDBOY_AGE:
        print('太小了')
    if age == OLDBOY_AGE:
        print('猜对了')
        break
    count += 1

for循环

不依赖索引
for 单项 in 序列:
循环体

for item in dict:
    print(dicr[item])
for i in range(10,0,-2)
    print(i)