Python: for 循环

一、For 语法结构和基于数字(range)的循环

for x in range(5):
    print('hello')

二、基于列表list,元组tuple的循环

numbers1 = [1,2,3,4,5]
numbers2 = (6,7,2,5)
name = "zhang"
for x in numbers1:
    print(x)
for x in numbers2:
    print(x)
for x in name:
    print(x)

列表、元组、字典、集合、字符串等都可以用 for 来遍历

三、跳过单次循环

for x in [3,4,5,8,9]:
    if (x % 3 == 0):
        continue    
    print(x)

continue 跳过本轮循环后面的语句,马上进入下一轮循环,仍然在 for 循环里面

四、马上退出循环

numbers = [3,4,5,8,9]
for x in numbers:
    if (x == 5):
        break
    print(x)
print("程序结束了")

Python: for 循环

break 直接退出循环,而不是退出程序,仍然可以执行for循环之外的东西

实例1:一个for循环,从1 到100,如果是3的倍数输出’Y‘;如果是5的倍数输出’N‘;如果又是3的倍数又是5的倍数,输出’Hello‘;其他都直接输出数字自己

for x in range(1,101):
    if (x % 3 == 0):
        print('Y')
    elif (x % 5 == 0):
        print('N')
    elif (x % 3 == 0 & x % 5 == 0):
        print('Hello')
    else:
        print(x)

实例2:上面实例1 再增加一个条件:如果是7的倍数就什么都不做;如果碰到66就退出。

for x in range(1,101):
    if (x % 3 == 0 and x % 15 != 0):
        print('Y')
        if (x == 66):
            break
    elif (x % 5 == 0 and x % 15 != 0):
        print('N')
    elif (x % 15 == 0):
        print('Hello')
    elif (x % 7 == 0):
        continue
    else:
        print(x)

五、嵌套循环

weeks = ['Monday','Tuesday','Friday']
for x in weeks:
    for n in x:
        print(n)
    print("-------")

六、一次性退出嵌套循环

weeks = ['Monday','Tuesday','Friday']
is_found = False
for x in weeks:
    if (is_found):
        break
    for n in x:
        if(n == 'a'):
            is_found = True
            break
        print(n)
    print("-------")

Python: for 循环

七、 显示循环的index和值

scores = [98,97,95,86,23]
for order,s in enumerate(scores):
    print(order+1,s)

Python: for 循环

enumerate 这个函数的基本应用就是用来遍历一个集合对象,它在遍历的同时还可以得到当前元素的索引位置。

八、可循环类--随机数循环

import random
class RandomCount:
    def __iter__(self):
        return self
    def __next__(self):
        return random.randint(1,10)

rc = RandomCount()
for s in rc:
    print(s)

上一篇:Java基本语法-Day2


下一篇:【省选模拟】2 月