while循环

发布时间 2023-12-01 14:29:13作者: ssrheart

循环结构

  • 循环结构是一种程序控制结构,用于反复执行一组语句,直到满足某个条件

【一】while循环

(1)语法

while condition:
    # 循环体
  • while是循环的关键字
  • condition是循环的条件,当条件为真时,循环体会一直执行

(2)使用

count = 0
while count < 5:
    count += 1
    if count == 3:
        print(f'已跳过{count}')
        continue # 退出当次循环
    if count == 4:
        break # 退出当前while循环
    print(count)
count = 0
tag = True
while count < 10 and tag:
    count += 1
    if count == 3:
        print(f'已跳过{count}')
        continue
    if count == 4:
        print('我要改变tag了')
        tag = False # 标志位tag
    if count == 8:
        break
    print(count)

(3)循环分支(else)

  • 在while循环的后面可以跟else语句
count=1
while count<3:
    print(count)
    count +=1
else:
    break

(4)练习(字典登录)

user_pwd = {'heart': '123', 'god': '456'}
count = 3
tag = True

while count > 0 and tag:
    username_input = input('请输入用户名:>>>')
    userpwd_input = input('请输入密码:>>>')
    count -= 1
    if username_input in user_pwd and userpwd_input == user_pwd.get(username_input):
        print('登录成功!')
        tag = False
    else:
        print(f'登陆失败!用户名或密码不正确!还有{count}次机会')
        if count == 0:
            continue_input=input('还需要继续尝试吗?(y/n)')
            if continue_input == 'y':
                count=3
            else:
                print('感谢使用!')
                tag=False
        continue

【二】for循环+range关键字

(1)语法

for i in range(start,stop,step)
	# 循环体
  • 列表、字符串、元组、字典都可以使用for循环遍历输出
# 列表
num_list = [1, 2, 3, 4, 5]
for i in num_list:
    print(i)
# 字符串
aa = 'heart'
for i in aa:
    print(i)
# 元组
aa_tuple = ('heart', 123)
for i in aa_tuple:
    print(i)
# 字典 (只能取键)
aa_dict = {'heart': '123'}
for i in aa_dict:
    print(i)
# 字典(取值)
aa_dict = {'heart': '123'}
for i in aa_dict:
    print(aa_dict[i])

(2)range关键字

  • 顾头不顾尾 ---range(1,5) 从1取到4,取不到5
for i in range(1,5)
	print(i)

(3)range + len 遍历序列

num_list=[1,2,3]
for i in range(0,len(num_list)):
    print(num_list[i])