while循环三要素:初始值、循环条件、变量更新
count = 1 # 初始值 while count<=5: # 循环条件 print("我在学习while循环") #循环体 count += 1 # 变量更新 print(count)
累加计算
total = 0 count = 1 # 初始值 while count<=100: # 循环条件 total = count + total count += 1 # 变量更新 print("总和:", total)
改变步长,只加偶数
total = 0 count = 2 # 初始值 while count<=100: # 循环条件 total = count + total count += 2 # 变量更新 print("偶数总和:", total)
只加奇数
total = 0 count = 1 # 初始值 while count<=100: # 循环条件 total = count + total count += 2 # 变量更新 print("奇数总和:", total)
喝水
cup = 1 # 初始值 target = 8 while cup<=target: # 循环条件 input() print(f"喝了第{cup}杯水") cup += 1 # 变量更新 print("喝水完成")
条件判断嵌入,计算1到100能同时被3和5整除的数的和
total = 0 count = 1 # 初始值 while count<=100: # 循环条件 if count % 15 == 0: print(count) total = count + total count += 1 # 变量更新 print("总和:", total)
while循环嵌套
i = 1 while i < 10: j = 0 while j < i: print("*",end="") j += 1 print() i += 1
九九乘法表
# 遍历字符串
for letter in "python":
print(letter)
#遍历列表
f = ["apple","banana",2,["apple_1"]]
for i in f:
print(i)
# range()函数, 生成数字序列
# 1、 range(n):单参数,生成0到n-1的序列
for i in range(5):
print("我在学习for循环")
print(i)
# 累加计算
total = 0
count = 1 # 初始值
while count<=100: # 循环条件
total = count + total
print("总和:", total)
# 2、 range(a,b):双参数. 生成a到b-1的序列[a,b]
total = 0
for count in range(1,101):
print(count)
total = count + total
print("总和:",total)
# 3、 range(a,b,step):三参数, 生成a到b-1、步长为step的序列
total = 0
for count in range(5,1,-1):
total = count + total
print("偶数求和:",total)
# 喝水
target = 9
for cup in range(target): # 循环条件
input()
print(f"喝了第{cup}杯水")
print("喝水完成")