在本教程中,我们将介绍python while循环的基础知识。在上一个教程中,我们了解到Python for循环.
Python while循环
Python while循环用于重复执行某些语句,直到条件为真。所以python while循环的基本结构是:
While condition :
#Start of the statements
Statement
. . . . . . .
Statement
#End of the Statements
else :
#this scope is optional
#This statements will be executed if the condition
#written to execute while loop is false
例如,下面的代码将为您提供有关while循环的一些想法。在这个例子中,我们在循环内部打印1到4个数字,在循环外部打印5个数字
cnt=1 #this is the initial variable
while cnt < 5 :
#inside of while loop
print (cnt,"This is inside of while loop")
cnt+=1
else :
#this statement will be printed if cnt is equals to 5
print (cnt, "This is outside of while loop")
输出
在for循环教程的示例中,我们打印单词中的每个字母。我们可以实现代码使用while循环。下面的代码将向您展示这一点。
word="anaconda"
pos=0 #initial position is zero
while pos < len(word) :
print (word[pos])
#increment the position after printing the letter of that position
pos+=1
输出
关于循环的一个有趣的事实是,如果您使用for循环实现某些东西,您也可以在while循环中实现它。尝试在while循环中实现for循环教程中显示的示例。
Python嵌套while循环
可以在另一个while循环中编写while循环。假设您需要打印这样的图案
- 112个1 2 3个1 2 3 41 2 3 4 5
下面的代码将说明如何使用嵌套while循环来实现它。
line=1 #this is the initial variable
while line <= 5 :
pos = 1
while pos < line:
#This print will add space after printing the value
print pos,
#increment the value of pos by one
pos += 1
else:
#This print will add newline after printing the value
print pos
#increment the value of line by one
line += 1
Python while循环无限问题
因为while循环将继续运行,直到条件变为false,所以您应该确保它继续运行,否则程序将永远不会结束。有时,当你想让你的程序等待一些输入并持续检查时,它会很方便。
var = 100
while var == 100 : # an infinite loop
data = input("Enter something:")
print ("You entered : ", data)
print ("Good Bye Friend!")
如果您运行上述程序,它将永远不会结束,您将不得不使用Ctrl+C键盘命令终止它。
>>>
================= RESTART: /Users/pankaj/Desktop/infinite.py =================
Enter something:10
You entered : 10
Enter something:20
You entered : 20
Enter something:
Traceback (most recent call last):
File "/Users/pankaj/Desktop/infinite.py", line 3, in <module>
data = input("Enter something:")
KeyboardInterrupt
>>>
以上是python while循环示例教程。如有任何疑问,请在下面发表意见。