个性化阅读
专注于IT技术分析

Python While循环语句用法示例介绍

点击下载

本文概述

在Python中, While循环用于重复执行语句块, 直到满足给定条件。并且当条件变为假时, 将立即执行程序中循环之后的行。虽然循环属于以下类别不定迭代。无限迭代意味着没有预先明确指定执行循环的次数。

语法如下:

while expression:
    statement(s)

语句表示在将编程构造视为单个代码块的一部分之后, 所有缩进相同数量字符空间的语句。 Python使用缩进作为其对语句进行分组的方法。当执行while循环时, expr首先在布尔上下文如果为true, 则执行循环体。然后expr再次检查, 如果仍然为true, 则再次执行主体, 并且继续执行直到表达式变为false。

例子:

# Python program to illustrate 
# while loop 
count = 0
while (count <3 ):     
     count = count + 1
     print ( "Hello Geek" ) 
  
print ()
  
# checks if list still
# contains any element 
a = [ 1 , 2 , 3 , 4 ]
while a:
     print (a.pop())

输出如下:

Hello Geek
Hello Geek
Hello Geek

4
3
2
1

While循环的工作方式:

python while循环

单条语句而块

就像if阻止, 如果而块包含一个语句, 我们可以在一行中声明整个循环。如果在构成循环体的块中有多个语句, 则可以用分号分隔它们(;).

# Python program to illustrate 
# Single statement while block 
count = 0
while (count <5 ): count + = 1 ; print ( "Hello Geek" )

输出如下:

Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek

循环控制语句

循环控制语句从其正常顺序更改执行。当执行离开作用域时, 在该作用域中创建的所有自动对象都将被销毁。 Python支持以下控制语句。

继续声明:

它将控件返回到循环的开头。

# Prints all letters except 'e' and 's' 
i = 0
a = 'srcmini'
  
while i <len (a): 
     if a[i] = = 'e' or a[i] = = 's' : 
         i + = 1
         continue
     print ( 'Current Letter :' , a[i])
     i + = 1

输出如下:

Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

中断声明:

它使控制脱离了循环。

# break the loop as soon it sees 'e'  
# or 's'
i = 0
a = 'srcmini'
  
while i <len (a): 
     if a[i] = = 'e' or a[i] = = 's' : 
         i + = 1
         break
     print ( 'Current Letter :' , a[i])
     i + = 1

输出如下:

Current Letter : g

通过声明:

我们使用pass语句编写空循环。 Pass还用于空的控制语句, 函数和类。

# An empty loop 
a = 'srcmini'
i = 0
  
while i <len (a):
     i + = 1
     pass
print ( 'Value of i :' , i)

输出如下:

Value of i : 13

while-else循环

如上所述, while循环执行该块, 直到满足条件为止。当条件变为假时, 循环后立即执行该语句。

else子句仅在while条件变为false时执行。如果你跳出循环或者引发了异常, 则不会执行该异常。

注意:仅当循环未由break语句终止时, 才在for/while之后执行else块。

# Python program to demonstrate
# while-else loop
i = 0 
while i <4 :
     i + = 1
     print (i) 
else : # Executed because no break in for 
     print ( "No Break\n" ) 
  
i = 0 
while i <4 : 
     i + = 1
     print (i) 
     break
else : # Not executed as there is a break 
     print ( "No Break" )

输出如下:

1
2
3
4
No Break

1

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python While循环语句用法示例介绍

评论 抢沙发

评论前必须登录!