for,while循环
最简单的循环10次
|
1
2
3
4
5
6
|
#_*_coding:utf-8_*___author__ = 'Alex Li'for i in range(10): print("loop:", i ) |
输出:
|
1
2
3
4
5
6
7
8
9
10
|
loop: 0loop: 1loop: 2loop: 3loop: 4loop: 5loop: 6loop: 7loop: 8loop: 9 |
需求一:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳入下一次循环
|
1
2
3
4
|
for i in range(10): if i<5: continue #不往下走了,直接进入下一次loop print("loop:", i ) |
需求二:还是上面的程序,但是遇到大于5的循环次数就不走了,直接退出
|
1
2
3
4
|
for i in range(10): if i>5: break #不往下走了,直接跳出整个loop print("loop:", i ) |
十五、while loop
有一种循环叫死循环,一经触发,就运行个天荒地老、海枯石烂。
海枯石烂代码
|
1
2
3
4
5
|
count = 0while True: print("你是风儿我是沙,缠缠绵绵到天涯...",count) count +=1 |
其实除了时间,没有什么是永恒的,死loop还是少写为好
上面的代码循环100次就退出吧
|
1
2
3
4
5
6
7
8
|
count = 0while True: print("你是风儿我是沙,缠缠绵绵到天涯...",count) count +=1 if count == 100: print("去你妈的风和沙,你们这些脱了裤子是人,穿上裤子是鬼的臭男人..") break |
回到上面for 循环的例子,如何实现让用户不断的猜年龄,但只给最多3次机会,再猜不对就退出程序。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#!/usr/bin/env python# -*- coding: utf-8 -*-my_age = 28count = 0while count < 3: user_input = int(input("input your guess num:")) if user_input == my_age: print("Congratulations, you got it !") break elif user_input < my_age: print("Oops,think bigger!") else: print("think smaller!") count += 1 #每次loop 计数器+1else: print("猜这么多次都不对,你个笨蛋.") |

浙公网安备 33010602011771号