当前位置:首页>python>学Python4️⃣0️⃣ while ...

学Python4️⃣0️⃣ while ...

  • 2026-09-02 19:23:39
学Python4️⃣0️⃣ while ...

学Python4️⃣0️⃣ while ...

作者:小号🎺

今天,我们讲 while … loops。

一般而言,在(当)我们不知道循环范围,循环次数,只知道是否需要循环的条件时,用while循环。

例如:

① 制作一个随机数列表,设随机数为R,0<R<100,当 R<3 时结束。

import randomR = random.randint(1, 100)lst=[R]print(lst)while R >= 3:    R = random.randint(1, 100)    lst.append(R)    print(R)

② 寻找完美黄金周假期

定义:完美黄金周,法定假期和周末两天不重叠,自然衔接,前后均可,无需调休即可享有更长的“假期”。试找出下一个满足上述条件的十一长假。

import datetimeyear = 2026# 不知道要查多少年 → 只能 whilewhile True:    oct1 = datetime.date(year, 10, 1)    weekday = oct1.weekday()  # 0=周一,2=周三    if weekday == 0 or weekday == 2:        print(f"下一个完美国庆黄金周:{year} 年")        break    year += 1

③ 打印一份九九乘法表

# 打印一份九九乘法表i = 1while i <= 9:    j = 1    while j <= i:        print(f'{j}×{i}={i*j}', end='\t')        j += 1    print()    i += 1

今天就到这里。

补充练习:

计算并打印一个“杨辉三角形”(pascal三角形)

# 递归生成第 n 行,内部用 while 计算def pascal(n):    if n == 0:        return [1]    above = pascal(n - 1)    line = [1]    i = 0    # while 循环算中间值    while i < len(above) - 1:        line.append(above[i] + above[i+1])        i += 1    line.append(1)    return line# 用 while 循环打印居中三角rows = 10line_num = 0while line_num < rows:    row = pascal(line_num)    # 居中排版,让它变成正三角形    s = ''    i = 0    while i < len(row):        s += f"{row[i]:<4}"        i += 1    # 前面缩进,实现居中    print(' ' * (rows - line_num) * 2 + s)    line_num += 1

#Python#学Python#大白话#小号#大白小号学Python#原创

最新文章

随机文章