掌握 Python 中“For”和“While”循环的使用

大家好!今天我们还有另一个令人兴奋的讨论话题,那就是何时在 Python 中使用'while'or循环。'for'

在本文中,我们将借助插图详细探讨 Python 的'for'循环和“while”循环。

Python 循环简介

循环可以定义为重复某些内容(通常是代码,因为我们谈论的是编码语言),直到满足特定条件。d

主要有两种类型的循环。它们如下:-

  • For循环
  • While 循环

理解“For”循环

在 Python 中,'for' 循环迭代序列,例如列表、元组、字符串或任何可迭代对象。

基本语法和解释

for iterator_var in sequence:
    statements(s)

示例:迭代列表

  • 正如上面的代码中提到的,变量获取序列内项目的值。 'iterator_var'
  • 是循环将被迭代的代码块。它可以是任何数据类型,例如字符串、列表和元组。 'sequence'
  • 'statement(s)'是将在循环的每次迭代中执行的代码块。

探索“for”循环的示例代码

1
2
3
Fruits = ["Apple", "Lemon", "Orange", "Strawberry"] #accessing items of the list using for loop
for var in Fruits:
      print(var)

输出

1
2
3
4
Apple
Lemon
Orange
Strawberry

这将在控制台中显示如下:

基本 For 循环代码

在上面的示例中,'for'循环迭代 Fruits 列表并打印每个 Fruits。

“for”循环中的 Break 语句

'break' 使用该语句时,它立即退出循环并继续下一个循环。

以下是使用 Break 语句的 For 循环示例:

numbers = [10,20,30,40,50,60,70,80,90,100]
for num in numbers:
     if num == 60: #print number 10 to 50 , terminating number 60
        break
     print(num)

输出将是

10
20
30
40
50

这是上述代码的附加图像

For 循环中的 Break 语句

Range() 函数

同样,我们可以使用该'range()' 函数来生成数字序列。

让我们探索一下 Range() 函数在 for 循环中的用法:

1
2
3
numbers = [10,20,30,40,50,60,70,80,90,100]
for num in range(30): #generates a sequence of numbers from 0 to 29
     print(num)

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 号
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

输出
输出 4 1

继续声明

在Python中,'continue'循环中的语句结束当前迭代并跳到下一次迭代。

1
2
3
4
5
numbers = [10,20,30,40,50,60,70,80,90,100]
for num in range(10,101): #prints each number only if it is an even number that ie 10 to 100
      if num%2==1:
           continue
      print(num)

在此示例中,名为的列表'numbers'包含整数 10 到 100(含 10 和 100)。语句将执行数字 10 到 100(含),并且该语句将使用‘%’(模数)运算符检查该数字是偶数还是奇数如果是奇数,则将执行该语句。 'range' 'if' 'continue'

输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 号
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

代码显示如下:

输出
输出
输出

Python 中的 For 循环中的 Else 语句

当循环完成对元素序列的迭代时,将执行循环'else'中的语句 'for'

在此示例中, 'for'循环遍历'numbers'列表:

1
2
3
4
5
6
7
numbers = [1,2,3,4,5,6,7,8]
for num in numbers:
     if num == 4:
        print(" Number 4 in the list")
        break
else: #the statement will not be executed because the loop is terminated with a 'break' statement.
     print("Number 4 not in the list")

输出:

1
Number 4 in the list

那么我们在控制台看一下执行后的代码:

For循环中的Else语句

Python 中的 For 循环中的 If 语句

在 Python 中, 'if' 循环中的语句有条件地执行每个项目的代码。

If 语句的基本示例:

1
2
3
4
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
    if num%2 == 0: # checks if it is divisible by 2 , using the modulo operator '%'
       print(num)

所以,代码的输出是:

1
2
3
4
5
6
The code above will print all the even numbers.
2
4
6
8
10

这是控制台中的代码片段:

For 循环中的 If 语句

解释:

  • 指定的列表'numbers'包含从 1 到 10 的整数。
  • 该语句使用模运算符 (%)'if'检查元素是否为偶数
  • 如果数字是偶数,则执行 print 语句并打印该数字。

何时以及为何使用“for”循环

'for'循环迭代序列,例如列表、元组、字符串或任何可迭代对象。

然而,以下是我们可以'for'在 Python 中使用循环的场景:-

  • 迭代序列的每个元素。
  • 迭代一个数字范围。
  • 迭代字符串、字典。

以下是我们应该在 Python 中使用循环的一些原因'for'

  • 迭代数据类型。
  • 让代码更简单。
  • 提高效率。

探索 Python 中的“While”循环

'while' 循环中,可以执行直到条件为真的一组语句。

基本语法和示例

1
2
while(condition):
    #Code

这里,是判断该值是否为or 的'condition'表达式,如果,代码将执行到下一部分。将再次评估条件,如果仍然是,则循环继续执行。该过程一直持续到条件为'True''False' 'True''True''False'

现在我们可以看一个基本示例,探索“while”循环的应用:

1
2
3
4
x =1
while x < 8: #will continue to execute as long as x is less than 8
    print(x)
    x += 1

输出如下:

1
2
3
4
5
6
7
1
2
3
4
5
6
7

在此示例中,循环从 ‘x’ 等于 1 开始,并继续执行代码,直到值 ‘x’ 不再小于 8。当 ‘x’ 变为 8 时,循环不再继续执行。

因此,该代码将执行 7 次。

While 循环基本示例

while 循环中的 Break 语句

正如我们在循环中看到的那样,我们'for'将在循环中使用相同的过程。 'while'

Break语句在循环中的应用示例'while'

1
2
3
4
5
6
x=1
while x < 8: #Loop continues as long as x is less than 8
      if  x==6: #Check if x is equal to 6
            break #terminates the loop
     print(x)
     x += 1 #incrementing the value of x by 1

输出将是:

1
2
3
4
5
1
2
3
4
5

执行后的代码图像以及输出:

While 循环中的 Break 语句

下面是对上面代码的解释:

  • 将值 1 赋给变量'x'
  • 'while'只要 x 小于 8,就运行循环。
  • 评估是否'x'等于 6。
  • 如果'x'等于6,则循环将停止执行并使用该语句退出迭代 'break',如果不等于,则循环将继续执行。
  • 将的值增加'x' 1。
  • 重复循环过程,直到该值不再小于8。

while 循环中的 Range() 函数

由于我们已经了解了该'range()'函数,现在让我们关注它在'while'循环中的工作原理。

通过示例探索 Range() 函数在 While 循环中的应用:

1
2
3
4
x=1
while x in range(6): # iterates over the values  from 1 to 5
    print(x)
    x += 1

这将输出:

1
2
3
4
5
1
2
3
4
5

在这里,'while'循环将继续运行,直到条件为真。因此,这将输出数字 1 到 5,因为每次迭代的值都会增加 1。 'x in range(6)''x'

我们看一下控制台中的实现代码:

While 循环中的 Range() 函数

“While”循环中的Continue语句

我们都知道,在Python中,循环中的“继续”语句会结束当前迭代并跳到下一次迭代。现在,我们将在循环中实现该语句 'continue''while'

使用示例探索“While”循环中“Continue”语句的应用:

1
2
3
4
5
6
i=0
while i < 7:
    i += 1
    if i==4:#skip the number 4 and move on to the next iteration
        continue
    print(i)

输出:

1
2
3
4
5
6
1
2
3
5
6
7

兹附上代码图片:

While 循环中的Continue 语句

解释:-

  • 该代码将变量初始化 'i'为 0。
  • 循环'while'将执行到'i'小于 7。
  • 如果“i”等于 4,则将执行“Continue”语句,这将立即使循环跳到下一次迭代。

while 循环中的 Else 语句

在Python中, 'else'语句用于确定'while'循环迭代完成后要执行哪个代码块。

我们举一个简单的例子来详细说明else语句:

1
2
3
4
5
6
i=1
while i <= 9:
    print(i)
    i += 1
else:
    print("Loop completed successfully")

这将输出:

1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
Loop completed successfully

附图:

While 循环中的 Else 语句

循环 'while'将迭代直到'i'小于或等于 9。循环将终止,并且当达到 10'else'时将执行该块。 'i'

while 循环中的 If 语句

'if'循环内的语句'while'检查条件,如果条件为真,则将进一步执行特定的代码块。

让我们通过一个基本示例 来理解 While 循环中的 If 语句:

1
2
3
4
5
6
7
i = 1
while i <= 9:
    if i%2==0:
        print(i,"is even")
    else:
        print(i,"is odd")
    i += 1

输出将是:

1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd

控制台执行后的代码:

While 循环中的 If 语句

在本例中,'while'只要'i'小于或等于 9 就会执行。

该代码将检查 'x' 使用(模)运算符是偶数还是奇数。如果是偶数,则块内的代码将执行并打印该数字是偶数或奇数。 %'x'

何时以及为何使用“while”循环

在Python中,'while'循环是一组可以执行直到条件为真的语句。

在 Python 中,我们可以在多种情况下使用循环 'while'

例如:-

  • 当需要执行迭代直到满足条件时。
  • 将一个过程重复设定的次数。
  • 当我们没有关于代码块执行时间的正确信息时,也可以使用它。

结论

在 Python 中,forwhile 循环对于迭代序列和根据特定条件执行代码块至关重要。当您需要迭代已知序列(例如列表、元组或字符串)时,“For”循环是理想的选择。它们在处理数据类型方面提供了简单性和效率。另一方面,当需要执行一组语句直到满足特定条件时,“While”循环非常有用。它们适用于您不知道代码块应执行多少次的情况。掌握这两种类型的循环有助于提高您的 Python 编程和解决问题的技能。

参考