Python教程-Python 循环
 
            
            在Python中,有以下几种循环可用于满足循环需求。Python提供了3种循环的选择。所有技术的基本功能都是相同的,尽管语法和检查条件所需的时间量有所不同。
我们可以使用循环命令重复运行单个语句或一组语句。
Python编程语言中提供了以下类型的循环。
| 序号 | 循环名称 | 循环类型和描述 | 
|---|---|---|
| 1 | While 循环 | 在给定条件为TRUE的情况下重复执行一个语句或一组语句。在执行循环体之前测试条件。 | 
| 2 | For 循环 | 此类型的循环多次执行代码块,并缩写管理循环变量的代码。 | 
| 3 | 嵌套循环 | 我们可以在另一个循环内部迭代循环。 | 
循环控制语句
用于控制循环并改变迭代过程的语句称为控制语句。在执行完成后,循环本地范围内生成的所有对象都会被删除。
Python提供了以下控制语句。我们稍后会详细讨论它们。
让我们快速浏览一下这些循环控制语句的定义。
| 序号 | 控制语句名称 | 描述 | 
|---|---|---|
| 1 | Break 语句 | 此命令终止循环的执行,并将程序的控制转移到循环旁边的语句。 | 
| 2 | Continue 语句 | 此命令跳过循环的当前迭代。一旦Python解释器达到continue语句,continue语句后面的语句将不会被执行。 | 
| 3 | Pass 语句 | 当语句在语法上是必需的,但不需要执行代码时,使用pass语句。 | 
for 循环
Python的for循环旨在在迭代Python的列表、元组、字典或其他可迭代对象时重复执行代码块。遍历序列的过程称为迭代。
for 循环的语法
for value in sequence:  
    { code block }  在这种情况下,变量 value 用于在迭代开始之前保存序列中每个项目的值,直到完成此特定迭代为止。
循环在达到序列的最后一个项目之前迭代。
代码
# Python program to show how the for loop works  
  
# Creating a sequence which is a tuple of numbers  
numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]  
  
# variable to store the square of the number  
square = 0  
  
# Creating an empty list  
squares = []  
  
# Creating a for loop  
for value in numbers:  
    square = value ** 2  
    squares.append(square)  
print("The list of squares is", squares)  输出:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]在 for 循环中使用 else 语句
如前所述,for 循环执行代码块,直到达到序列元素。else 语句在 for 循环执行后紧跟在 for 循环之后执行。
只有在执行完成后,else 语句才会起作用。如果我们退出循环或抛出错误,它将不会被执行。
下面是一个用于更好理解 if-else 语句的代码示例。
代码
# Python program to show how if-else statements work  
  
string = "Python Loop"  
  
# Initiating a loop  
for s in a string:  
    # giving a condition in if block  
    if s == "o":  
        print("If block")  
    # if condition is not satisfied then else block will be executed  
    else:  
        print(s)  输出:
P
y
t
h
If block
n
L
If block
If block
p现在类似地,在 for 循环中使用 else。
语法:
for value in sequence:  
     # executes the statements until sequences are exhausted  
else:  
     # executes these statements when for loop is completed  代码
# Python program to show how to use else statement with for loop  
  
# Creating a sequence  
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)  
  
# Initiating the loop  
for value in tuple_:  
    if value % 2 != 0:  
        print(value)  
# giving an else statement  
else:  
    print("These are the odd numbers present in the tuple")  输出:
3
9
3
9
7
These are the odd numbers present in the tuplerange() 函数
借助 range() 函数,我们可以生成一系列数字。range(10) 将生成从 0 到 9 的值(10个数字)。
我们可以以 range(start, stop, step size) 的方式指定特定的起始、停止和步长值。如果未指定步长,它默认为 1。
由于它在构造后不会创建它所“包含”的每个值,因此 range 对象可以被描述为“缓慢”的。它提供了 in、len 和 getitem 操作,但它不是迭代器。
下面的示例将说明这一点。
代码
# Python program to show the working of range() function  
  
print(range(15))  
  
print(list(range(15)))  
  
print(list(range(4, 9)))  
  
print(list(range(5, 25, 4)))  输出:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]为了在 for 循环中遍历一系列项目,我们可以在循环中应用 range() 方法。我们可以使用索引来通过将其与可迭代的 len() 函数结合使用,遍历给定序列。以下是一个示例。
代码
# Python program to iterate over a sequence with the help of indexing  
  
tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")  
  
# iterating over tuple_ using range() function  
for iterator in range(len(tuple_)):  
    print(tuple_[iterator].upper())  输出:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGEWhile 循环
在Python中,while 循环用于迭代,直到满足指定条件。然而,当条件变为假时,循环之后的程序语句会被执行一次。
while 循环的语法如下:
while <condition>:  
    { code block }  在程序中,所有跟随结构性命令的编码语句都定义了一个代码块。这些语句的缩进相同。Python使用缩进将语句分组在一起。
代码
# Python program to show how to use a while loop  
counter = 0  
# Initiating the loop  
while counter < 10: # giving the condition  
    counter = counter + 3  
    print("Python Loops")  输出:
Python Loops
Python Loops
Python Loops
Python Loops在 while 循环中使用 else 语句
如前面在 for 循环部分中所讨论的,我们也可以在 while 循环中使用 else 语句。它的语法相同。
代码
#Python program to show how to use else statement with the while loop  
counter = 0  
  
# Iterating through the while loop  
while (counter < 10):      
    counter = counter + 3  
    print("Python Loops") # Executed untile condition is met  
# Once the condition of while loop gives False this statement will be executed  
else:  
    print("Code block inside the else statement")  输出:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement单语句 while 块
循环可以在单个语句中声明,如下所示。这类似于 if-else 块,在其中我们可以在一行中编写代码块。
代码
# Python program to show how to write a single statement while loop  
counter = 0  
while (count < 3): print("Python Loops")  循环控制语句
现在,我们将详细讨论循环控制语句。我们将为每个控制语句看一个示例。
Continue 语句
它将控制返回到循环的开始。
代码
# Python program to show how the continue statement works  
  
# Initiating the loop  
for string in "Python Loops":  
    if string == "o" or string == "p" or string == "t":  
         continue  
    print('Current Letter:', string)  输出:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:  
Current Letter: L
Current Letter: sBreak 语句
在到达 break 语句时,它停止循环的执行。
代码
# Python program to show how the break statement works  
  
# Initiating the loop  
for string in "Python Loops":  
    if string == 'L':  
         break  
    print('Current Letter: ', string)  输出:
Current Letter:  P
Current Letter:  y
Current Letter:  t
Current Letter:  h
Current Letter:  o
Current Letter:  n
Current Letter:   Pass 语句
Pass 语句用于创建空循环。Pass 语句也用于类、函数和空控制语句。
代码
# Python program to show how the pass statement works  
for a string in "Python Loops":  
    pass  
print( 'Last Letter:', string) 输出:
Last Letter: s 
          
          
         