python3(六) for while

# Python的循环有两种,一种是for...in循环,依次把list或tuple中的每个元素迭代出来
names = ['Michael', 'Bob', 'Tracy']
for name in names:
    print(name)
# 计算1-10的整数之和
sumAdd = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sumAdd = sumAdd + x
print(sumAdd)
# python提供一个range()函数,可以生成一个整数序列,再通过list()函数可以转换为list。比如range(5)生成的序列是从0开始小于5的整数:
print(list(range(5)))  # [0, 1, 2, 3, 4]
sum100 = 0
for x in range(101):
    sum100 = sum100 + x
print(sum100)
# while 计算100以内所有奇数之和
sumWhile = 0
n = 99
while n > 0:
    sumWhile = sumWhile + n
    n = n - 2
print(sumWhile)
#  break语句可以提前退出循环。
n = 1
while n <= 100:
    if n > 10:  # 当n = 11时,条件满足,执行break语句
        break  # break语句会结束当前循环
    print(n)
    n = n + 1
print('END')
# 通过continue语句,跳过当前的这次循环,直接开始下一次循环
n = 0
while n < 10:
    n = n + 1
    if n % 2 == 0:  # 如果n是偶数,执行continue语句
        continue  # continue语句会直接继续下一轮循环,后续的print()语句不会执行
    print(n)

 补充-------------------------

你可以在循环内部使用break语句跳出循环,continue语句跳出本次循环

python
for i in range(1, 10):
    if i == 5:
        break
    print(i)
# Prints 1 2 3 4

for i in range(1, 10):
    if i == 5:
        continue
    print(i) 
# Prints 1 2 3 4 6 7 8 9  
python
for i in range(5):
    for j in range(3):
        print(i, j)
# Prints
# 0 0  
# 0 1
# 0 2
# 1 0
# 1 1
# 1 2 
# ...

 

posted @ 2019-09-18 16:45  ~清风煮酒~  阅读(271)  评论(0编辑  收藏  举报