亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python while 循环

Python while 循环

循环在编程中用于重复特定的代码块。在本文中,您将学习在 Python 中创建 while 循环。

视频:Python while 循环

Python 中的 while 循环是什么?

Python中的while循环用于迭代一段代码,只要测试表达式(条件)为真。

我们一般在事先不知道迭代次数的情况下使用这个循环。

Python中while循环的语法

while test_expression:
    Body of while

在 while 循环中,首先检查测试表达式。只有当 test_expression 计算结果为 True .一次迭代后,再次检查测试表达式。这个过程一直持续到 test_expression 计算结果为 False .

在 Python 中,while 循环的主体是通过缩进确定的。

正文以缩进开始,第一条未缩进的行标记结束。

Python 将任何非零值解释为 True . None0 被解释为 False .

while循环的流程图

<图>

示例:Python while 循环

# Program to add natural
# numbers up to 
# sum = 1+2+3+...+n

# To take input from the user,
# n = int(input("Enter n: "))

n = 10

# initialize sum and counter
sum = 0
i = 1

while i <= n:
    sum = sum + i
    i = i+1    # update counter

# print the sum
print("The sum is", sum)

当你运行程序时,输出将是:

Enter n: 10
The sum is 55

在上面的程序中,测试表达式将是 True 只要我们的计数器变量 i 小于或等于 n (我们的程序中有 10 个)。

我们需要增加循环体​​中计数器变量的值。这非常重要(而且大多被遗忘)。否则将导致无限循环(永无止境的循环)。

最后显示结果。


While 与 else 循环

与 for 循环相同,while 循环也可以有一个可选的 else 块。

else 如果 while 循环中的条件计算结果为 False,则执行部分 .

while 循环可以用 break 语句终止。在这种情况下,else 部分被忽略。因此,while 循环的 else 如果没有发生中断并且条件为假,则部分运行。

这里有一个例子来说明这一点。

'''Example to illustrate
the use of else statement
with the while loop'''

counter = 0

while counter < 3:
    print("Inside loop")
    counter = counter + 1
else:
    print("Inside else")

输出

Inside loop
Inside loop
Inside loop
Inside else

在这里,我们使用一个计数器变量来打印字符串 Inside loop 三遍。

在第四次迭代中,while 中的条件 变成 False .因此,else 部分被执行。


Python

  1. C# while 和 do...while 循环
  2. C# foreach 循环
  3. C++ while 和 do...while 循环
  4. Python 数据类型
  5. Python 运算符
  6. Python pass 语句
  7. Python 函数参数
  8. Python字典
  9. Python 迭代器
  10. Python For &While 循环:枚举、中断、继续语句
  11. Python 中的 Enumerate() 函数:循环、元组、字符串(示例)
  12. SINUMERIK 840D 编程 WHILE 循环使用