python3控制结构

发布时间 2023-04-14 15:55:05作者: 挖洞404

1、介绍
控制结构一般为:
顺序结构,默认的从前到后执行顺序执行即是
条件结构,if结构,python没有switch结构
循环结构,while和for结构,以及迭代器,python不存在do while结构

2、if结构

if 条件判断:
    pass
elif 条件判断:
    pass
else:
    pass

3、while结构

i = 3
while i>0:
    print("+++", i)
    i = i+1
else:
    print("循环结束")

while的else结构是可有可无,完全可以将else代码直接写在while结构外的下一行。一般使用else是为了阅读上可能好看一点

4、for结构
in是必须关键字
in后是range函数,遍历读取从0到指定参数-1
in后是序列对象,遍历读取元素,支持str、list、set、tuple等
但注意,对dict并不是直接支持,而是需要dict调用方法生成其他序列对象

5、迭代器
(1)使用
基于iter内置函数生成迭代器对象,基于next内置函数取出迭代器对象的下一个元素

it = iter("abcd")
print(next(it)) # a
print(next(it)) # b

(2)创建迭代器类型
把一个类作为一个迭代器使用需要在类中实现两个方法 iter() 与 next() 。

class stus:
    def __iter__(self):
        self.id = 1
        return self
    def __next__(self):
        id = self.id
        self.id += 1
        return id
stus = stus()
stuer = iter(stus)
print(next(stuer)) #1
print(next(stuer)) #2