📜  Python 3-循环

📅  最后修改于: 2020-12-23 04:48:08             🧑  作者: Mango


通常,语句按顺序执行-函数的第一个语句首先执行,然后执行第二个,依此类推。在某些情况下,您需要多次执行一个代码块。

编程语言提供了各种控制结构,允许使用更复杂的执行路径。

循环语句使我们可以多次执行一个语句或一组语句。下图说明了循环语句-

循环架构

Python编程语言提供了以下类型的循环来处理循环需求。

Sr.No. Loop Type & Description
1 while loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3 nested loops

You can use one or more loop inside any another while, or for loop.

循环控制语句

循环控制语句从其正常顺序更改执行。当执行离开作用域时,在该作用域中创建的所有自动对象都将被销毁。

Python支持以下控制语句。

Sr.No. Control Statement & Description
1 break statement

Terminates the loop statement and transfers execution to the statement immediately following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

3 pass statement

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

让我们简要地介绍一下循环控制语句。

迭代器和生成器

迭代器是一个对象,它使程序员可以遍历集合的所有元素,而无论其具体实现如何。在Python,迭代器对象实现两个方法, iter()next()

字符串,列表或元组对象可用于创建迭代器。

list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
   print (x, end=" ")
or using next() function
while True:
   try:
      print (next(it))
   except StopIteration:
      sys.exit() #you have to import sys module for this

发电机是产生或产生使用产量的方法值的序列的函数。

调用生成器函数,它甚至不开始执行该函数就返回生成器对象。首次调用next()方法时,该函数开始执行直到到达yield语句,该语句返回yield值。收益保持跟踪,即记住上一次执行,第二个next()调用从上一个值继续。

以下示例定义了一个生成器,该生成器为所有斐波那契数生成一个迭代器。

#!usr/bin/python3

import sys
def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
         return
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

while True:
   try:
      print (next(f), end=" ")
   except StopIteration:
      sys.exit()