7.while 循环

while循环

while 条件:

  条件满足时,做的事情1

  条件满足时,做的事情2

  条件满足时,做的事情3

...省略...

只要条件满足,会无限循环执行,条件不满足,执行结束

条件需提供布尔类型结果,True继续,False停止

空格缩进不能忘

请规划好循环终止条件,否则将无限循环

i = 0
while i < 5:
    print(f"{i}")
    i += 1
0
1
2
3
4
# 1-100累加的和
i = 1
sum = 0
while i <= 100:
    sum += i
    i += 1
print(f"1-100累加的和是:{sum}")
1-100累加的和是:5050
# while循环猜数字
import random
num = random.randint(1,100)
count = 0
flag = True
while flag == True:
    numin = int(input("请输入你的猜的数字:"))
    count += 1
    if numin == num:
        print("猜对了")
        flag = False
    else:
        if numin > num:
           print("大了")
        else:
           print("小了")

print(f"你猜了{count}次!")
小了
大了
大了
大了
猜对了
你猜了5次!

while循环

while 条件1:

  条件满足时,做的事情1

  条件满足时,做的事情2

  条件满足时,做的事情3

  while 条件2:

    条件满足时,做的事情1

    条件满足时,做的事情2

    条件满足时,做的事情3

...省略...

基于空格缩进来决定层次关系

i = 1
while i <= 10:
    print(f"今天是第{i}天,攒钱")
    j = 1
    while j <= 5:
        print(f"攒了{j}百块")
        j += 1
    print(f"攒钱")
    i += 1
print(f"坚持了{i - 1}天")

案例

print语句输出不换行操作

print("Hello",end = '')

print("World",end = '')

特殊符号: \t 效果等同于键盘上按下: tab键 可以让多行字符串对齐

#print("Hello",end = '')
#print("World",end = '')

#print("I\tlove")
#print("hello\tworld")

# 九九乘法表
i = 1
while i <= 9:
    j = 1
    while j <= i:
        print(f"{j} * {i} = {i*j}\t",end = '')
        j += 1
    print()
    i += 1
1 * 1 = 1
1 * 2 = 2   2 * 2 = 4
1 * 3 = 3   2 * 3 = 6   3 * 3 = 9
1 * 4 = 4   2 * 4 = 8   3 * 4 = 12  4 * 4 = 16
1 * 5 = 5   2 * 5 = 10  3 * 5 = 15  4 * 5 = 20  5 * 5 = 25
1 * 6 = 6   2 * 6 = 12  3 * 6 = 18  4 * 6 = 24  5 * 6 = 30  6 * 6 = 36
1 * 7 = 7   2 * 7 = 14  3 * 7 = 21  4 * 7 = 28  5 * 7 = 35  6 * 7 = 42  7 * 7 = 49
1 * 8 = 8   2 * 8 = 16  3 * 8 = 24  4 * 8 = 32  5 * 8 = 40  6 * 8 = 48  7 * 8 = 56  8 * 8 = 64
1 * 9 = 9   2 * 9 = 18  3 * 9 = 27  4 * 9 = 36  5 * 9 = 45  6 * 9 = 54  7 * 9 = 63  8 * 9 = 72  9 * 9 = 81