最简单的循环10次
#_*_coding:utf-8_*_ __author__ = 'Alex Li' for i in range(10): print("loop:", i )
输出
loop: 0 loop: 1 loop: 2 loop: 3 loop: 4 loop: 5 loop: 6 loop: 7 loop: 8 loop: 9
需求一:还是上面的程序,但是遇到大于5的循环次数就不走了,直接跳出本次循环进入下一次循环
for i in range(10): if i>5: continue #不往下走了,跳出本次循环直接进入下一次循环 print("Result:", i )
Result: 0
Result: 1
Result: 2
Result: 3
Result: 4
Result: 5
需求二:还是上面的程序,但是遇到小于5的循环次数就不走了,直接跳出本次循环进入下一次循环
for i in range(0,10):
if i < 5:
continue
print("Result:",i)
Result: 5
Result: 6
Result: 7
Result: 8
Result: 9
需求三:还是上面的程序,但是遇到等于5的循环次数就不走了,直接跳出本次循环进入下一次循环
for i in range(0,10):
if i == 5:
continue
print("Result:",i)
Result: 0
Result: 1
Result: 2
Result: 3
Result: 4
Result: 6 #没有5,直接从4到6了
Result: 7
Result: 8
Result: 9
# --------------break测试,结束当前循环--------------- for i in range(5): print(i,"======") for city in range(5): print(city) if city > 3: break
0 ======
0
1
2
3
4
1 ======
0
1
2
3
4
2 ======
0
1
2
3
4
3 ======
0
1
2
3
4
4 ======
0
1
2
3
4
# Author: George.Wang # for i in range(10): # print("Result:",i) # for i in range(0,10,2): # 这里的0是开始数,10是结束数,2是步长数 # print("Result:",i) ''' my_age=10 for i in range(3): guess_age = int(input("Please input my age:")) if guess_age == my_age: print("Congratulations! you got my age.") break elif guess_age > my_age: print("I'm sorry, your answer is bigger than my age.let's try again.") else: print("I'm sorry, your answer is smaller than my age.let's try again.") else: print("you have tried three times, plase restart again.") '''