循环结构

循环结构

1. 什么是循环结构

  • 是一种控制程序结构,反复执行一块代码,只到满足条件为止

2.while 循环

2.1 语法

while condition:
	# 循环体
  • while 是循环关键字

  • condition 是循环条件,当条件为True时,会一直执行循环体

  • 循环体 是需要重复执行的代码块

2.2 使用

count = 0
while count < 3:
  count += 1
  print("hello world")
print("循环结束了") 

# 输出结果
hello world
hello world
hello world
循环结束了

2.3 循环案例

# 登录功能
# 字典存储用户的登录信息
# 输入框输入 用户名和密码
# 可以尝试 3 次 ----> 用户名或密码错误的话就要重新输入了!
# 第一次的时候告诉你还有两次
# 最后一次的时候告诉你还愿意继续尝试吗?
# 如果选择继续尝试的话 ---> 继续尝试输入y,结束输入n

user_pwd = {"chenxu": "123"}
count = 3
while count > 0:
    user = input("请输入用户名:")
    pwd = input("请输入密码:")
    count -= 1
    if user in user_pwd and pwd == user_pwd[user]:
        print("登陆成功")
        break
    if count > 0:
        print(f"账号或密码错误,你还{count}次机会")
    else:
        data = input("机会以用完,是否继续,y/n:》》》》")
        if data == "y":
            count = 3
        else:
            print("感谢使用")

3. for循环

3.1 语法

for variable in sequence:
    # 循环体
  • for是循环关键字
  • variable 是循环变量,他会每次在循环中取 sequence的一个值
  • sequence是一个序列,可以i是 str、list、tuple
  • 循环体是需要重复执行的代码块

3.2使用案例

num_list = [1,2,3,4]
for i in num_list:
  print(i)
print("循环结束")

# 输出结果
1
2
3
4
循环结束

4. break

  • break结束循环,用于在while循环中帮你终止循环。
  • break结束循环后。break后的代码不在执行
  • 如果while循环嵌套了很多层,要想退出每一层循环则需要在每一层循环都有一个break

4.1 语法

while condition:
		# 循环体
  	if True:
      	break # 退出循环

4.2 使用案例

# 案例1
print("开始")
while True:
	print("1")
	break
	print("2")
	print("3")
print("结束")

# 输出结果
开始
1
结束


# 案例2 登录案例(while循环嵌套-break)
username = "serein"
password = "123"
count = 0
while count < 3:  # 第一层循环
    inp_name = input("请输入用户名:")
    inp_pwd = input("请输入密码:")
    if inp_name == username and inp_pwd == password:
        print("登陆成功")
        while True:  # 第二层循环
            cmd = input('>>: ')
            if cmd == 'quit':
                break  # 用于结束本层循环,即第二层循环
            print('run <%s>' % cmd)
        break  # 用于结束本层循环,即第一层循环
    else:
        print("输入的用户名或密码错误!")
        count += 1

5. continue

  • continue,在循环中用于 结束本次循环,开始下一次循环

5.1 语法

while condition:
		# 循环体
  	if True:
      	break # 退出循环

5.2 使用案例

count = 0

while count < 5:
    count += 1
    if count == 3:
        continue  # 当 count 等于 3 时,跳过当前循环,继续下一次循环
    print(count)
# 输出结果
1
2
4
5

补充

break 用于完全退出循环,而 continue 用于跳过当前循环的剩余部分,直接进入下一次循环

6. 标志位

6.1 语法

flag = True  # 初始化标志位

while flag:
    # 循环体
    if some_condition:
        flag = False  # 修改标志位,退出循环

6.2 使用案例

flag = True  # 初始化标志位

while flag:
    user_input = input("请输入:")
    if user_input == 'exit':
        flag = False  # 当用户输入 'exit' 时,修改标志位,退出循环
    else:
        print("用户输入:", user_input)

【补充】range关键字

1. 遍历数字序列

1.1 语法

for i in range(stop):
    # 循环体
for i in range(start, stop):
    # 循环体
for i in range(start, stop, step):
    # 循环体

1.2 使用

for i in range(5):
    print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4
for i in range(2, 6):
    print(i)
# 输出:
# 2
# 3
# 4
# 5
for i in range(1, 10, 2):
    print(i)
# 输出:
# 1
# 3
# 5
# 7
# 9

2. 指定区间

2.1 语法

range(start, stop, step)

2.2 使用

for i in range(2, 6):
    print(i)
# 输出:
# 2
# 3
# 4
# 5

3. 步长

3.1 语法

range(start, stop, step)

3.2 使用

for i in range(1, 10, 2):
    print(i)
# 输出:
# 1
# 3
# 5
# 7
# 9

4. range + len 遍历序列

4.1 原理

my_list = ['apple', 'banana', 'orange']
for i in range(len(my_list)):
    # 循环体

4.2 使用

my_list = ['apple', 'banana', 'orange']
for i in range(len(my_list)):
    print(f"Index {i}: {my_list[i]}")
# 输出:
# Index 0: apple
# Index 1: banana
# Index 2: orange

5. range创建

5.1 原理

numbers = list(range(start, stop, step))

5.2 使用

numbers = list(range(1, 6))
print(numbers)
# 输出:[1, 2, 3, 4, 5]

6. 循环分支嵌套

  • 循环结构和分支结构可以嵌套在一起,形成复杂的程序逻辑。
for i in range(5):
    print("Outer loop, current value:", i)

    for j in range(3):
        print("Inner loop, current value:", j)

print("Nested loops finished!")
  • 上述代码中,外层循环 for i in range(5): 执行五次,内层循环 for j in range(3): 每次外层循环执行时都会执行三次。这样就形成了嵌套的循环结构。
while 1:
    score = input("请输入您的成绩>>")  # "100"

    if score.isdigit():
        score = int(score)  # 100
        if score > 100 or score < 0:
            print("您的输入有误!")
        elif score > 90:
            print("成绩优秀")
        elif score > 70:  # else if
            print("成绩良好")
        elif score > 60:
            print("成绩及格")
        else:
            print("成绩不及格")
    else:
        print("请输入一个数字")
posted @ 2023-11-29 20:42  Formerly0^0  阅读(57)  评论(0)    收藏  举报