循环结构
- 循环结构是一种程序控制结构,用于反复执行一组语句,直到满足某个条件
【一】while循环
(1)语法
while
是循环的关键字
condition
是循环的条件,当条件为真时,循环体会一直执行
(2)使用
| count = 0 |
| while count < 5: |
| count += 1 |
| if count == 3: |
| print(f'已跳过{count}') |
| continue |
| if count == 4: |
| break |
| 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 |
| if count == 8: |
| break |
| print(count) |
(3)循环分支(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]) |
本文作者:ssrheart
本文链接:https://www.cnblogs.com/ssrheart/p/17869615.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步