for循环用于针对集合中的每个元素的一个代码块,而while循环不断运行,直到指定的条件不满足为止
- 基础版:1-100的累加
# while
i = 1
result = 0
while i <= 100:
result += i
i += 1
print(result) # 5050
- 进阶版 while+if,1-100的偶数和
i = 1
result = 0
while i <= 100:
if i % 2 == 0:
result += i
i += 1
print(result) # 2550
- 使用break退出循环
break是终止循环,直接结束,不在运行余下的代码
i = 0
while i < 10:
if i == 3:
print('吃了' + str(i) + '碗米饭,吃饱了')
break
i += 1
- 使用continue退出
continue是退出本次循环
i = 0
while i < 10:
i += 1
if i == 3:
print('第' + str(i) + ('个苹果有虫子,换下一个'))
continue
print('吃了第' + str(i) + '苹果')
- while+while
一周内每天说三遍,PHP是世界上最好的语言
day = 1
while day < 8:
NB = 1
print('今天是第' + str(day) + '天')
while NB < 4:
print('PHP是世界上最好的语言')
NB += 1
day += 1
- 实践 写九九乘法表
i = 1
while i < 10:
j = 1
while j <= i:
print(f’{i}{j}={ij}’, end=" “)
j += 1
print(”\n")
i += 1