希望您在Python 平滑复习系列中过得不错。 让我快速提醒您,本系列文章的目的是以通俗易懂的方式教您需要掌握的主要概念,以便在您的Python学习之旅中前进。
您还记得那天必须浇10朵花的那一天吗? 还是当您必须加满20杯水时? 您对每朵花或一杯水都执行相同的任务。 这种重复称为编程中的循环 。
为了感觉到循环的重要性,假设您正在编写一个程序,该程序应打印相同的语句100,000次。 您敢于手动重复此语句100,000次吗? 我不会,我想你也不会。 我相信您还有很多重要的事情要做。 因此,出现了循环的美妙之处。
事不宜迟,让我们看看Python的循环方式。
While循环
在这种类型的迭代中,只要测试评估为true
,该语句或语句块就会继续执行。 因此,控制将继续循环回到语句(即测试)的开头,并且如果测试评估为false
,则将处理对下一个语句的控制。 如果测试始终评估为true,则在这种情况下,我们将陷入无限循环 。
while语句的一般语法非常简单,如下所示:
while test: # loop test
statements # loop body
还记得我刚才提到的无限循环术语吗? 也就是说,由于测试始终为真,永不停止的循环吗? 让我们看一个这样的循环的例子:
while 1:
print 'I\'m an infinite loop. Ctrl-C to stop me!'
值1
是布尔值true
另一种形式。 因此,如果您将while true
编写为while true
,那么它将等同于示例中的while语句。 您会注意到,您将不断获得无限显示的打印语句。
要终止循环,只需在键盘上单击Control-C 。 下图显示了程序如何无限运行并被键盘(即Control-C)打断。
现在让我们用Python浇灌10朵美丽的花。 可以按以下步骤完成:
flowers = 1
while flowers <= 10:
print 'Water the flower # ' + str(flowers)
flowers = flowers + 1
程序的结果如下图所示:
在继续之前,让我澄清一下上面的Python脚本中的一些要点。 您可能想知道str()
是什么,为什么我们在这里使用它。 根据文档:
返回一个字符串,其中包含对象的漂亮可打印表示形式。 对于字符串,这将返回字符串本身。 与repr(object)
的区别在于str(object)
并不总是尝试返回eval()
可接受的字符串; 它的目标是返回可打印的字符串。 如果未提供任何参数,则返回空字符串''
。
换句话说, str()
将返回对象的可打印字符串表示形式。 但为什么? 让我们看看如果不使用str()
,Python会抱怨什么:
Traceback (most recent call last):
File "test.py", line 3, in <module>
print 'Water the flower # ' + flowers
TypeError: cannot concatenate 'str' and 'int' objects
因此,问题是str
不能与int
串联。
我要提到的另一点是,使用flowers = flowers + 1
。 如果不使用这样的语句,则将有一个无限循环,其中flowers的值将保持为1
,因此始终小于10
(始终为true)。
对于循环
for-loop
是一个迭代,它逐步遍历有序序列的项,例如列表 , 字典键, 元组 ,字符串等。
Python for-loop
语法如下所示:
for var in sequence:
statement(s)
其中var
将保存for-loop
将要迭代通过的序列项(即列表,元组), for-loop
将为序列中的每个项执行for for-loop
主体。
时间到了for-loop
上的一些例子!
languages = ['Arabic', 'English', 'French', 'Spanish']
counter = 0
for lang in languages:
print 'This language is in the list: ' + languages[counter]
counter = counter + 1
如果初始化counter = 1
会发生什么? 在这种情况下,您将得到如下所示的错误,因为在循环中的某一时刻索引将超出列表范围:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print 'This language is in the list: ' + languages[counter]
IndexError: list index out of range
一个小测验。 以下循环的输出是什么? (提示:请记住,Python从0
开始计数):
for x in range(1,5):
print x
While和For循环中使用的语句
下面的小节将显示一些在循环中经常使用的语句。
打破
语句break
导致循环终止,并且在下一条语句上继续执行程序。
下面显示了使用break
的示例。 它显示了当if-statement
评估为true
时程序如何退出( break
)循环。
numbers = [1,2,3,4,5,6,7,8,9,10]
value = 1
while value in numbers:
if value == 5:
break
print 'I\'m # ' + str(value)
value = value + 1
print 'Sorry, I had to quit the loop when the value became 5'
继续
该语句将控制权返回到循环的开头,而忽略循环之后的所有语句。 让我们看下面的例子:
numbers = [1,2,3,4,5,6,7,8,9,10]
value = 1
while value in numbers:
if value < 5:
print 'I\'m # ' + str(value)
value = value + 1
continue
print 'I\'m in the if-condition, why are you ignoring me?!'
elif value == 5:
break
print ('I have reached the last statement in the program and need to exit')
您知道continue
工作原理了吗? 您认为此Python脚本的输出是什么? 继续尝试一下。
通过
这句话有点棘手。 pass
语句是一个null
语句,即它不执行任何操作。 但是,为什么要使用它呢? 假设您正在编写程序,并且在某个时候您不确定在for-statement
应该包含哪些内容,如下所示:
numbers = [1,2,3,4,5,6,7,8,9,10]
value = 1
for value in numbers:
# not sure what to do here yet
print ('I have reached the last statement in the program and need to exit')
如果尝试运行该程序,则会出现以下错误:
File "test.py", line 6
print ('I have reached the last statement in the program and need to exit')
^
IndentationError: expected an indented block
因此,Python抱怨for-loop
内应该有一些语句。 如果在for-loop
键入pass
,则程序的输出为:
I have reached the last statement in the program and need to exit
由此,我们可以得出结论,即使您尚未决定在代码的某些位置必须包含哪些必需的语句, pass
可以充当占位符以允许程序运行。
其他
else
语句是不言自明的,它将仅包含一个语句块,以便在循环以正常方式(而不是通过break
退出时运行。 其用法示例如下:
numbers = [1,2,3]
value = 1
while value in numbers:
print 'I\'m # ' + str(value)
value = value + 1
else:
print 'I\'m part of the else statement block'
print 'I\'m also part of the else statement block'
结论
总结本文并想像一下循环的重要性,我记得当我必须对图像的每个像素执行那些图像分析操作时。
在尺寸为256x256
的图像上执行此操作仅意味着我必须重复操作65,536次(这是像素数)! 循环救援!
翻译自: https://code.tutsplus.com/tutorials/a-smooth-refresher-on-pythons-loops--cms-25585