Python—— 18.语句结构

1.条件

if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3

2.循环

2.1 while
a = 0
while a < 10:
    print(a)
    a += 1       
2.2 for
xiaobin = [1,2,3,4,5,6,7,8,9]
for x in xiaobin:
    print(x)       

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

for x in range(5,10):
    print(x)  

for x in range(0,10,2):
    print(x)           
for x in range(0,-10,-2):
    print(x)           

2.3 break 和 continue

3.迭代器(iter)

3.1 迭代方法

迭代器有两个基本的方法:iter() 和 next()。

In [35]: iter?                                                                                                                         
Docstring:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object.  In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
Type:      builtin_function_or_method

In [42]: next?                                                                                                                         
Docstring:
next(iterator[, default])

Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
Type:      builtin_function_or_method

3.2 迭代器创建

重写类的 iter() 与 next() 。
创建一个返回数字的迭代器,初始值为 1,逐步递增 1:

class IterClass:
      def __iter__(self):
        self.a = 1
        return self
     
      def __next__(self):
        x = self.a
        self.a += 1
        return x
     
iter1= IterClass()
coustomIter= iter(iter1)
     
print(next(coustomIter))
print(next(coustomIter))

4.生成器(generator)

使用了 yield 的函数被称为生成器(generator)。
yield就是 return 返回一个值(这个值就是生成器),并且记住这个返回的位置,下次迭代就从这个位置后(下一行)开始。

[root@node2 temp]# vim p1.py
#!/share/python/python3.7/bin/ipython3
def yield_function():
    print("begin")
    yield "hello"
    print("end")
 
test = yield_function()
print(next(test))       
print(next(test))      

————Blueicex 2020/2/22 22:35 [email protected]

发布了118 篇原创文章 · 获赞 1 · 访问量 4497

猜你喜欢

转载自blog.csdn.net/blueicex2017/article/details/104450103
18.
今日推荐