Python 中的 for 和 while 循环_for和while循环的区别python

liftword3个月前 (02-18)技术文章16

Python 中的 for 和 while 循环

<> 6 分钟阅读

什么是循环,何时使用它们?

循环是所有编程语言中的基本构造。在循环结构中,程序首先检查条件。如果此条件为 true,则运行一段代码。除非条件无效,否则此代码将继续运行。

例如,查看以下伪代码块:

Bash
IF stomach_empty
  eat_food()
ENDIF
//check if stomach is empty again.
IF stomach_empty
  eat_food()
ENDIF 
//check if stomach is still empty, 
//....

在这里,我们正在检查变量是否为 .如果满足此条件,程序将执行该方法。此外,请注意,我们多次键入相同的代码,这意味着这违反了编程的 DRY 规则。stomach_emptytrueeat_food

为了缓解这个问题,我们可以使用这样的循环结构:

Bash
WHILE stomach_empty //this code will keep on running if stomach_empty is true
  eat_food()
ENDWHILE

在此代码中,我们使用语句。在这里,循环首先分析布尔值是否为 。如果满足此条件,程序将继续运行该函数,直到条件变为 false。我们将在本文后面了解循环。
whilestomach_emptytrueeat_foodwhile

总而言之,开发人员使用循环多次运行一段代码,直到满足某个条件。因此,这可以节省时间并提高代码的可读性。

循环的类型

在 Python 中,有两种循环结构:

  • for:迭代预定义的次数。这也称为确定迭代
  • while:继续迭代,直到条件为 。这称为无限迭代false

在本文中,您将学习以下概念:

  • 对于循环语法数字循环使用列表循环
  • 列表理解语法列表用法数字用法
  • 而循环语法数字循环使用列表循环
  • 循环控制语句break陈述continue陈述pass陈述该条款else

for循环

循环是一种运行预设次数的循环。它还能够循环访问任何序列的项,例如列表或字符串。for

语法

Bash
for i in : 
  

这里,是一个对象列表。循环变量 每次通过循环时都采用下一个元素的值。其中的代码会一直运行,直到到达集合的末尾。collectionicollectionloop bodyi

数字循环

为了演示循环,让我们使用数字范围循环:for

Bash
for i in range(10):  # collection of numbers from 0 to 9
    print(i)

在这一段代码中,我们使用该函数创建了一个从 0 到 9 的数字集合。后来,我们使用该函数记录了循环变量的值。因此,这将输出范围从 0 到 9 的数字列表。rangeprinti

该方法返回一个可迭代对象,该可迭代对象返回从 0 开始的整数,最多但不包括 。range()

我们甚至可以在循环中使用条件语句,如下所示:

Bash
for i in range(10):  # numbers from 0-9
    if i % 2 == 0:  # is divsible by 2? (even number)
        print(i) # then print.

此代码块将输出从 0 到 9 的所有偶数。

使用列表循环

我们甚至可以使用循环来遍历列表:for

Bash
names = ["Bill Gates", "Steve Jobs", "Mark Zuckerberg"] # create our list
for name in names:  # load our list of names and iterate through them
    print(name)

在上面的代码片段中,我们创建了一个名为 .稍后,我们使用命令遍历数组,然后注销此列表的内容。namesfornames

下面的代码段使用语句返回所有包含字母“B”的名称:if

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg"]  # create our list
for name in names:  # load our list of names and iterate through them
    if "B" in name:  # does the name include 'B'?
        print(name)

列表理解

在某些情况下,您可能希望基于现有列表的数据创建新列表。
例如,查看以下代码:

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]
namesWithB = []
for name in names:
    if "B" in name: 
        namesWithB.append(name) # add this element to this array.
print(namesWithB)

在此代码中,我们使用命令遍历数组,然后检查是否有任何元素包含字母 .如果为 true,程序会将此相应的元素追加到列表中。fornamesBnamesWithB


了解更多→


利用列表理解的力量,我们可以在很大程度上缩小这个代码块。

语法

Bash
newlist = [ for  in  (if condition)]

在这里,可以是一段返回值的代码,例如方法。的元素将附加到数组中,如果满足 .expressionlistnewlistloop variablecondition

列表用法

让我们重写之前使用列表推导编写的代码:

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]
namesWithB = [name for name in names if "B" in name]
print(namesWithB)

在此代码中,我们遍历了数组。根据我们的条件,所有包含字母的元素都将添加到列表中。namesBnamesWithB

数字用法

我们可以在列表理解中使用该方法,如下所示:range

Bash
numbers = [i for i in range(10)]
print(numbers)

请注意,在本例中,我们没有条件语句。这意味着条件是可选的。

此代码片段将使用条件来获取 0 到 9 之间的偶数列表:

while循环

通过循环,我们可以执行一个代码块,只要 是 .whileconditiontrue

语法

Bash
while :
  

在循环中,首先检查 。如果是,则执行 中的代码。此过程将重复,直到变为 。whileconditiontrueloop bodyconditionfalse

数字循环

这段代码打印出 和 之间的整数。09

Bash
n = 0
while n < 10: # while n is less than 10,
    print(n) # print out the value of n 
    n += 1 # 

下面是此示例中发生的情况:

  • 的初始值为 。程序首先检查是否大于 。由于这是,循环体运行n0n10true
  • 在循环中,我们首先打印出 的值。稍后,我们将按 递增它。n1
  • 当循环主体完成后,程序执行将再次计算条件。因为它仍然是真的,所以身体再次执行。
  • 这将持续到超过 。此时,当测试表达式时,它是 ,并且循环停止。n10false

使用列表循环

我们可以使用一个块来迭代列表,如下所示:while

Bash
numbers = [0, 5, 10, 6, 3]
length = len(numbers) # get length of array. 
n = 0
while n < length: # loop condition
    print(numbers[n])
    n += 1

Here’s a breakdown of this program:

  • The function returns the number of elements present in the arraylennumbers
  • Our statement first checks whether is less than the variable. Since this is true, the program will print out the items in the list. In the end, we are incrementing the variablewhilenlengthnumbersn
  • When exceeds , the loop haltsnlength

Loop control statements

有三个循环控制语句:

  • break:如果满足特定条件,则终止循环
  • continue:如果满足指定条件,则跳过循环的一次迭代,然后继续下一次迭代。和之间的区别在于关键字将“跳出”循环,但会“跳过”循环的一个循环continuebreakbreakcontinue
  • pass:当您不希望执行任何命令或代码时。

我们可以在和循环中使用所有这些。whilefor

1.break

当您想要退出循环(如果某些条件为 )。
以下是实际操作中的关键字:breaktruebreak

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]
for name in names:
    if name == "Mark Zuckerberg":  
        print("loop exit here.")
        break  # end this loop if condition is true.
    print(name)
print("Out of the loop")

从这段代码中得出一些推论:

  • 程序首先遍历数组names
  • 在每个周期中,Python 会检查 的当前值是否为nameMark Zuckerberg
  • 如果满足上述条件,程序将告诉用户它已经停止了循环
  • 但是,如果条件为 ,程序将打印falsename

2.continue

该语句告诉 Python 跳过当前迭代并继续下一个迭代。
下面是一个示例:continue

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]  
for name in names:
    if name == "Mark Zuckerberg":
        print("Skipping this iteration.")
        continue  # Skip iteration if true.
    print(name)
print("Out of the loop")

以下是此脚本的细分:

  • 遍历阵列names
  • 如果应用遇到具有值的元素,请使用语句跳过此迭代Mark Zuckerbergcontinue
  • 否则,打印出我们的循环计数器的值,name

3.pass

如果不希望运行任何命令,请使用该语句。换句话说,允许您执行“空”操作。这在代码将要去但尚未编写的地方可能至关重要。passpass

下面是关键字的简单示例:pass

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]
for name in names:
    if name == "Mark Zuckerberg":
        print("Just passing by...")
        pass  # Move on with this iteration
    print(name)
print("Out of the loop")

这将是输出:

4. 条款else

Python 也允许我们将语句附加到我们的循环中。块中的代码在循环终止时执行。
语法如下:elseelse

Bash
# for 'for' loops
for i in : 
  
else: 
   # will run when loop halts.
# for 'while' loops
while :
  
else:
   # will run when loop halts

在这里,人们可能会想,“为什么不在循环后立即将代码放入?它不会完成同样的事情吗?codeblock

有一个细微的区别。如果没有 ,无论如何,都将在循环终止后运行。elsecode block

但是,对于语句,如果循环通过关键字终止,则不会运行。elsecode blockbreak

下面是正确理解其目的的示例:

Bash
names = ["Bill Gates", "Billie Eilish", "Mark Zuckerberg", "Hussain"]
print("Else won't run here.")
for name in names:
    if name == "Mark Zuckerberg":
        print("Loop halted due to break")
        break  # Halt this loop
    print(name)
else: # this won't work because 'break' was used. 
    print("Loop has finished")

print(" \n Else statement will run here:")
for name in names: 
    print(name)
else: # will work because of no 'break' statement
    print("second Loop has finished")

这将是输出:

结论

在本文中,您学习了如何在 Python 编程中使用 and 循环。此外,您还学习了列表理解和循环更改语句的基础知识。这些是帮助你提高Python技能的关键概念。forwhile

相关文章

简单学Python——关键字17——while

while是Python中的关键字,用作循环。while循环是一种在满足特定条件的情况下重复执行一段代码的控制结构。语法:while 条件:(缩进)要执行的代码下面用while循环从1打印到10:a=...

收藏 | Python小技巧之while循环_python3 while循环语句

CDA数据分析师 出品作者:CDA明星讲师 曹鑫编辑:MikaPython 之 while 循环大家好,今天我们来讲讲 while 循环。while 循环真的很有用,我这里写了一个方法叫while T...

python学习——002for与while的区别

for 与 while的区别,简炼概述,用例子区别概述for 循环:适用于已知循环次数的场景,结构紧凑,将循环变量的初始化、条件判断和更新集中在一个语句中。while 循环:更适合循环次数未知(次数已...

Python小案例27-while循环的使用和语法

在Python中,while是一个循环控制结构,用于重复执行一段代码,直到指定的条件不再满足为止。while循环的语法如下:while 条件: # 循环体 在每次循环开始之前,首先会判断条件是...

Python教程:第15篇 while 循环语句

上一篇介绍了for 有限循环语句,本文介绍while无限循环语句。while的使用格式while语句可以执行无限循环。虽然while语句是判断与循环的结合体,但相对于for语句,while的用法看起来...

Python(for和while)循环嵌套及用法

Python 不仅支持 if 语句相互嵌套,while 和 for 循环结构也支持嵌套。所谓嵌套(Nest),就是一条语句里面还有另一条语句,例如 for 里面还有 for,while 里面还有 wh...