Python while循环
时间:2020-02-23 14:43:40 来源:igfitidea点击:
在本教程中,我们将介绍python while循环的基础知识。
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循环。
假设您需要打印这样的图案
1
1 2
1 2 3
1 2 3 4
1 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/hyman/Desktop/infinite.py ================= Enter something:10 You entered : 10 Enter something:20 You entered : 20 Enter something: Traceback (most recent call last): File "/Users/hyman/Desktop/infinite.py", line 3, in <module> data = input("Enter something:") KeyboardInterrupt >>>