学习Python 的 While 和 For 循环

283 阅读7分钟

在用Python或其他编程语言编程时,为了创建可以做许多不同事情的动态程序,理解循环是非常重要的。循环是一种编程结构,它将一段代码重复若干次,直到达到预期的结果。编程的大部分威力在于有能力将重复性任务自动化,而循环是完成这项工作的工具。在本教程中,我们将研究Python中的while和for循环,以及每个循环如何工作的几个例子。


介绍 while循环

python while loop
有的时候,你需要在你的程序中做一次以上的事情。换句话说,我们需要一个循环,而Python中最简单的循环机制是while循环。只要有一个特定的条件,一个while 循环就会运行。 True.while循环的语法看起来像这样。

while test_expression:
    Body of while

一个数到3的简单程序是while语句的第一个很好的例子。

count = 1
while count <= 3:
    print(count)
    count += 1
1
2
3

第一步是将1的值分配给 **count**变量。接下来,我们检查存储在 **count**小于或等于数字3。如果这个表达式的值为 True,那么在 **count**被打印出来。下一步是将1添加到 **count**变量,这样就完成了一次迭代。然后这个过程再次开始,直到 **count**不再小于或等于3。

python while loop flowchart

while 循环由以下部分组成。

  • while关键字
  • 一个评估为TrueFalse表达式,也称为条件
  • 一个冒号**:**字符
  • 缩进的while循环的主体,或子句

避免无限循环

突出显示的一行在while循环中是超级重要的。它被用来增加变量的值。 **count**变量的增量。

count = 1
while count <= 3:
    print(count)
    count += 1

如果你从来没有给变量加过1,那么这个循环中的表达式将 **count**变量,那么这个循环中的表达式就会一直评估为 True.这意味着这个程序将永远简单地打印出数字1。所以带计数器的while循环有助于防止这种情况。如果你碰巧写了一个无限的while循环,一个键盘中断可以阻止它。这可以通过使用CTRL-C组合键来实现。你可能需要一种方法来手动结束while循环。

控制一个无限循环的方法是 break

你可以用break关键字跳出while循环。这是在你想要一个半无限循环的时候使用的。换句话说,你想一直循环下去,直到特定的事情发生,但你不确定何时会发生。这方面的一个好例子是什么?一个让你输入一个词的程序如何,程序将反向打印这个字符串。程序将继续无限循环,直到你输入'q'字符退出,这将打破循环。这是一个在while循环中使用if语句的例子。

while True:
    word = input('Enter a string and I will print it backwards(type q to quit): ')
    if word == 'q':
        break
    print(word[::-1])
Enter a string and I will print it backwards(type q to quit): Python
nohtyP
Enter a string and I will print it backwards(type q to quit): Wow it works!
!skrow ti woW
Enter a string and I will print it backwards(type q to quit): q

Process finished with exit code 0

这个程序使用input()函数从键盘上读取用户的输入,然后反向打印该字符串。只要用户没有输入一个'q'字符,那么程序就会继续运行。如果他们确实只输入了字母'q',那么该中断语句就会运行,无限循环就会停止。

while True:
    word = input('Enter a string and I will print it backwards(type q to quit): ')
    if word == 'q':
        break
    print(word[::-1])

跳到前面去 continue

你可以使用continue关键字,根据条件测试的结果,返回到循环的起点。当程序到达continue语句时,程序会直接跳回到循环的起点,并重新评估循环的条件。例如,考虑一个从1到10计数但只打印偶数的循环。

num = 0
while num <= 10:
    num += 1
    if num % 2 != 0:
        continue
    print(num)
2
4
6
8
10

使用 **else**使用 break

如果你有一个在while循环中使用break语句的程序,但break语句从未被调用,控制权就会转移到一个可选的else结构。你在一个while循环中使用这种方法,该循环检查某些东西,一旦发现就会中断。如果while循环完成了,但没有发现任何东西,那么else就会运行。这个小程序检查的是长度为4个字符的单词。如果它没有找到4个字符的单词,则运行else子句。

words = ['cat', 'rat', 'bat']
i = 0
while i < len(words):
    word = words[i]
    if len(word) == 4:
        print(f'{word} has 4 characters')
        break
    i += 1
else:
    print('No words have 4 characters')
No words have 4 characters

我们可以改变单词列表,使其包括一个4字符的单词,看看程序的反应。

words = ['cat', 'rat', 'bat', 'brat']
i = 0
while i < len(words):
    word = words[i]
    if len(word) == 4:
        print(f'{word} has 4 characters')
        break
    i += 1
else:
    print('No words have 4 characters')
brat has 4 characters

多个条件在一个 **while**循环

一个while语句可以有多个条件。下面是一个在while循环中使用多个条件的例子。只要任何一个条件变成假的,迭代就会停止。

color, number, count = 'red', 7, 0
while color == 'red' and number == 7 and count < 3:
    if count == 0:
        print('color is ', color)
    elif count == 1:
        print(number, ' is the number')
    else:
        print('while statement multiple conditions example')
    count += 1
color is  red
7  is the number
while statement multiple conditions example

嵌套 **while**循环在Python中的应用

你可以将一个 while循环中的另一个while循环,以创建所谓的嵌套的while循环

outer = 1
inner = 5
print('Outer|Inner')
while outer <= 4:
    while inner <= 8:
        print(outer, '---|---', inner)
        inner += 1
        outer += 1
Outer|Inner
1 ---|--- 5
2 ---|--- 6
3 ---|--- 7
4 ---|--- 8

**while**循环用户输入

通过在while循环中使用input()函数,在while条件中使用布尔值True,可以实现反复从你的程序的用户那里获得用户输入的模式。让我们看看这是如何工作的。

number = 3
while True:
    what_number = input('What number is it? [type q to quit]:  ')
    if what_number == 'q':
        print('Thanks for guessing!')
        break
    if int(what_number) == number:
        print('You got it!')
        break
What number is it? [type q to quit]:  1
What number is it? [type q to quit]:  2
What number is it? [type q to quit]:  3
You got it!

迭代 **for**循环

python for loop
Python中的迭代器非常好,因为它允许你在数据结构上循环,即使你不知道它们有多大。也可以对即时创建的数据进行迭代。这可以确保计算机在处理非常大的数据集时不会耗尽内存。这就把我们引向了Python中的for循环。我们学习了while 循环,它在其条件是的情况下反复循环 True.当你想运行一个代码块一定的次数时,你可以使用for循环与 Python**range()**函数相结合。在 Python 中有两种类型的循环。我们已经看到了 while 循环,现在我们可以看一下 for 循环。我们使用 for 循环来迭代一个序列。一个序列是像列表、元组、字符串或任何可迭代的对象。当在一个序列上循环时,这被称为遍历。for 循环的语法如下。

for val in sequence:
	Body of for

通过列表的for循环

trees = ['Pine', 'Maple', 'Cedar']
for tree in trees:
    print(tree)
Pine
Maple
Cedar

这样的列表是 Python 的可迭代对象之一。字符串、图元、字典、集合和其他一些元素也是可迭代对象。当我们在一个列表或元组上迭代时,我们一次访问一个项目。对于字符串的迭代,你是一次访问一个字符

下面是另一个练习,我们在for循环中循环一些问题。

questions = ['Whats up?', 'How are you?', 'What time is it?']
for question in questions:
    print(question)
Whats up?
How are you?
What time is it?

通过元组的for循环

boats = ('Row', 'Motor', 'Sail')
for boat in boats:
    print(boat + ' Boat')
Row Boat
Motor Boat
Sail Boat

通过字符串的for循环

for letter in 'Winnipesaukee':
    print(letter)
W
i
n
n
i
p
e
s
a
u
k
e
e

for loop through dictionary
当在一个字典上迭代时,你有几个不同的选择。你可以只迭代键,只迭代值,或者同时迭代键和值。要在 for 循环中访问 dictionary 的值,你需要使用**.values()方法。要用 for 循环同时访问一个 dictionary 的 key 和 values,可以使用.items()**方法。

通过 dictionary keys 的 for 循环

forecast = {'Mon': 'Rainy', 'Tues': 'Partly Cloudy', 'Wed': 'Sunny', 'Thu': 'Windy', 'Fri': 'Warm', 'Sat': 'Hot',
            'Sun': 'Clear'}

for day in forecast:
    print(day)
Mon
Tues
Wed
Thu
Fri
Sat
Sun

通过字典的值进行 for 循环

forecast = {'Mon': 'Rainy', 'Tues': 'Partly Cloudy', 'Wed': 'Sunny', 'Thu': 'Windy', 'Fri': 'Warm', 'Sat': 'Hot',
            'Sun': 'Clear'}

for weather in forecast.values():
    print(weather)
Rainy
Partly Cloudy
Sunny
Windy
Warm
Hot
Clear

通过字典的键和值的 for 循环


forecast = {'Mon': 'Rainy', 'Tues': 'Partly Cloudy', 'Wed': 'Sunny', 'Thu': 'Windy', 'Fri': 'Warm', 'Sat': 'Hot',
            'Sun': 'Clear'}

for day, weather in forecast.items():
    print(day + ' will be ' + weather)
Mon will be Rainy
Tues will be Partly Cloudy
Wed will be Sunny
Thu will be Windy
Fri will be Warm
Sat will be Hot
Sun will be Clear

for 循环与计数器
通过在 for 循环中使用**range()**函数,你可以访问一个索引,这个索引可以用来访问列表中的每一个项目

str_nums = ['one', 'two', 'three', 'four', 'five']
for counter in range(5):
    print(counter, str_nums[counter])
0 one
1 two
2 three
3 four
4 five

一个更常见的和pythonic的方法是通过使用**enumerate()**函数来实现。通过使用enumerate()函数,你可以在python for 循环中访问多个变量。这个例子使用了两个循环变量。 **counter**和 val.
for 循环,使用enumerate的计数器

str_nums = ['one', 'two', 'three', 'four', 'five']
for counter, val in enumerate(str_nums):
    print(counter, val)
0 one
1 two
2 three
3 four
4 five

**break 和 **continue**语句 **与for循环

你可以使用 **break**和 continue语句在 for循环,就像我们在 while循环。continue语句将跳到for循环的计数器的下一个值,就像程序执行到了循环的末端并返回到起点一样。breakcontinue语句只在whilefor循环中起作用。如果你试图在其他地方使用这些语句,Python 将抛出一个错误。

for letter in 'Programming':
    if letter == 'a':
        print('Found "r", Breaking Out Of Loop Now')
        break
    print('Current Letter :', letter)
Current Letter : P
Current Letter : r
Current Letter : o
Current Letter : g
Current Letter : r
Found "r", Breaking Out Of Loop Now

在下面这个例子中,当num变量在迭代过程中等于7时,继续语句被用来跳过循环的其余部分。

for num in range(10):
    if num == 7:
        print('Seven is not so lucky')
        continue
    print(num)
0
1
2
3
4
5
6
Seven is not so lucky
8
9

检查 **break**使用与 **else**在 **for**循环

就像 while循环。 for有一个可选的 else子句,你可以用它来检查for循环是否正常完成。如果一个 break没有被调用,就会运行else语句。当你想检查之前的for循环是否运行完成,而不是被break提前停止时,这就很有用。下面例子中的for循环在寻找字母 "Z "的同时打印了字符串 "Programming "的每个字母。因为它从未被找到,所以break语句从未被击中,而else子句被运行。

for letter in 'Programming':
    if letter == 'Z':
        print('Found "Z", Breaking Out Of Loop Now')
        break
    print('Current Letter :', letter)
else:
    print('Did Not Find "Z"')
Current Letter : P
Current Letter : r
Current Letter : o
Current Letter : g
Current Letter : r
Current Letter : a
Current Letter : m
Current Letter : m
Current Letter : i
Current Letter : n
Current Letter : g
Did Not Find "Z"

使用 **range()**函数与 **for**循环

range()函数返回一个给定范围内的数字流。range()函数的好处是,你可以在不使用大量内存的情况下创建大范围。不需要首先声明一个大的数据结构,如列表或元组。当你想执行一个代码块一定的次数时,你可以使用for循环和range()函数。

嵌套 **for**Python中的循环

Python 中嵌套 for 循环的语法如下。

for [first iterating variable] in [outer loop]: # Outer loop
    [do something]  # Optional
    for [second iterating variable] in [nested loop]:   # Nested loop
        [do something]

一个嵌套的循环是这样工作的。

  • 程序首先运行外循环,执行其第一次迭代。
  • 这个第一次迭代触发了内部嵌套循环,该循环运行到结束。
  • 程序返回到外循环的顶部,完成第二次迭代。
  • 嵌套循环再次运行至完成。
  • 程序返回到外循环的顶部,直到序列完成或中断语句停止该过程。

下面是Python中嵌套for循环的一些练习。

nums = [1, 2, 3]
letters = ['xx', 'yy', 'zz']

for number in nums:
    print(number)
    for letter in letters:
        print(letter)
1
xx
yy
zz
2
xx
yy
zz
3
xx
yy
zz
columns = [1, 2, 3]
rows = [1, 2, 3, 4]
for column in columns:
    if column == 1:
        print('      |', end='')
    print('column', column, '|', end='')
    if column == 3:
        print()
        for row in rows:
            print('row', row, f'| r{row}, c1  | r{row}, c2  | r{row}, c3  |')
      |column 1 |column 2 |column 3 |
row 1 | r1, c1  | r1, c2  | r1, c3  |
row 2 | r2, c1  | r2, c2  | r2, c3  |
row 3 | r3, c1  | r3, c2  | r3, c3  |
row 4 | r4, c1  | r4, c2  | r4, c3  |

向后循环

有许多方法可以使用 while 和 for 循环来进行反向循环。让我们看看在 Python 中使用 while 和 for 循环向后循环的几个例子。

while 向后循环

countdown = ['Blastoff!', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
start = 10
while start >= 0:
    print(countdown[start])
    start -= 1
10
9
8
7
6
5
4
3
2
1
Blastoff!

for 向后循环
在使用 for 循环时要向后循环,你要使用 range() 函数,同时指定startstopstep参数。步骤是第三个参数,当使用 -1 作为参数时,这告诉 Python 向后计数或循环。

countdown = ['Blastoff!', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
for i in range(10, -1, -1):
    print(countdown[i])
10
9
8
7
6
5
4
3
2
1
Blastoff!

一次在几个迭代表上循环!

现在我们对Python中使用whilefor的循环有了一定的了解,你可能想利用你的超能力,一次在多个事物上循环。这可以通过内置的 Python zip() 函数实现。例如,如果你有两个列表,你可以同时在两个列表上循环,同时访问每个列表的每个索引--或者说是并行的。

letters = ['a', 'b', 'c']
numbers = [0, 1, 2]
for letter, number in zip(letters, numbers):
    print(f'Letter: {letter}')
    print(f'Number: {number}')
    print('------------------')
Letter: a
Number: 0
------------------
Letter: b
Number: 1
------------------
Letter: c
Number: 2
------------------

Python While 和 For 循环总结

用所谓的comprehensions [在一行中]做[for循环]也是可能的。如果你有兴趣的话,可以去看看。本教程涵盖了很多关于在Python中使用whilefor进行循环的内容。我们看到了如何基于True这样的条件进行循环,在循环中使用else子句,研究了几个循环的例子,在循环中使用not操作符,结合while循环处理用户输入,在for循环中访问索引,在for循环中使用range()函数,用break和continue语句控制循环执行。现在,让我们开始疯狂吧