Python 的while循环

while循环:

# while 条件:
#     条件满足时做的事情

例子: 求1-100的和

i = 0
s = 0
while i < 100:
    print("第%d次" % i)
    i += 1  # 循环终止的条件
    s=s+i
    print("和为%d" % s)

例子2: 猜1-100大小,并给出大小提示

import random
num = random.randint(1, 100)
flag = True
count = 0
while flag:
    guess_num = int(input("请输入你猜测的数字:"))
    count += 1
    if guess_num == num:
        print("猜中了")
        flag = False  # 终止循环
    else:
        if guess_num > num:
            print("猜大了")
        else:
            print("猜小了")
print(f"总共猜测了{count}次")

while嵌套循环:

例子:九九乘法表

i = 1
while i <= 9:
    j = 1
    while j <= i:
        # \t :对齐     end=''  :print语句不换行
        print(f"{j}*{i}={i * j}\t", end='')
        j += 1
    i += 1
    # 输出换行
    print()
\t      : 对齐    
end=''  : print语句不换行

你可能感兴趣的:(python)