Menu Close

Python While循环语句和While循环语句范例

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

1.什么是 Python 中的while循环?

只要测试表达式(条件)为真,Python 中的while循环就可以迭代代码块。

当我们不知道事先进行迭代的次数时,通常使用此循环。

1)Python 中while循环的语法

while test_expression: 
      Body of while

while循环中,首先检查测试表达式。 仅当test_expression求值为True时,才进入循环的主体。 一次迭代后,再次检查测试表达式。 该过程一直持续到test_expression求值为False为止。

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

主体以缩进开始,第一条未缩进的线标记结束。

Python 将任何非零值解释为True(真)。None和0解释为False(假)。

2)While循环流程图

While循环流程图
While循环流程图

例1.1while循环计算整数的和

# 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)

结果

The sum is 55

例1.2 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

在上述程序中,只要我们的计数器变量i小于或等于n(在我们的程序中为 10),则测试表达式为True

我们需要在循环体内增加计数器变量的值。 这是非常重要的(并且几乎被遗忘了)。 否则,将导致无限循环(永无止境的循环)。

最后,显示结果。

例1.3

count = 0;
while count < 10:
     print("My name is Vidyut")
     count += 1

结果

My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut
My name is Vidyut

3) while循环与else

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

如果while循环中的条件求值为False,则执行else部分。

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

这是一个例子来说明这一点。

例1.3 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")

结果:

在这里,我们使用计数器变量将字符串内部循环打印三遍。

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

 

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in Python教程

Related Posts