文章目录
- [1 while循环的基础语法](#1 while循环的基础语法)
- [2 while循环的基础案例](#2 while循环的基础案例)
- [3 while循环的嵌套应用](#3 while循环的嵌套应用)
- [4 while循环的嵌套案例](#4 while循环的嵌套案例)
- [5 for循环的基础语法](#5 for循环的基础语法)
- [6 for循环的嵌套案例](#6 for循环的嵌套案例)
- [7 循环中断:break和continue](#7 循环中断:break和continue)
1 while循环的基础语法
python
i = 0
while i < 100:
print("你好")
i += 1
2 while循环的基础案例
案例1
python
a = 1
sum = 0
while a <=100:
sum += a
a += 1
print(sum)
案例2
python
import random
num = random.randint(1,100)
count = 0
flag = True
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}次")
3 while循环的嵌套应用
while嵌套循环的基本格式
while嵌套循环的应用
python
i = 1
while i <= 100:
print(f"今天是第{i}天,准备表白")
j = 1
while j <= 10:
print(f"送给小明{j}朵玫瑰")
j += 1
print("小明我喜欢你")
i += 1
print(f"坚持到第{i-1}天,表白成功")
4 while循环的嵌套案例
python
i = 1
while i <=9:
j = 1
while j <= i:
print(f"{j} * {i} = {j * i}\t",end="")
j += 1
i += 1
print()
5 for循环的基础语法
基础语法
python
name = "itheima"
for i in name:
print(i)
案例
python
name = "itheima is a brand of itcast"
count = 0
for i in name:
if i == 'a':
count += 1
print(count)
range语句
变量作用域
6 for循环的嵌套案例
python
i = 0
for i in range(1,100):
print(f"今天是向小明表白的第{i}天")
for j in range(1,11):
print(f"给小明的第{j}朵花")
print(f"第{i}天,表白成功")
print("小明我喜欢你")
python
for i in range(1,10):
for j in range(1,i+1):
print(f"{j} * {i} = {j * i}\t",end='')
print()