python的while语句用while无限循环语句1+1/3+1/3*2/5+1/3*2/5*3/7

Python编程语言中的 while 循环语句只要给定条件为真,则会重复执行的目标声明或语句。
Python编程语言的&while循环的语法&-
while expression:
statement(s)&
在这里,语句(statement(s))可以是单个语句或均匀缩进语句块。条件(condition)可以是表达式,以及任何非零值时为真。当条件为真时循环迭代。
当条件为false,则程序控制流会进到紧接在循环之后的行。
在Python中,所有编程结构后相同数量的字符空格的缩进语句被认为是一个单一代码块的一部分。Python使用缩进作为分组语句的方法。
在这里,while循环的关键点是循环可能永远不会运行。当条件测试,结果是false,将跳过循环体并执行while循环之后的第一个语句。
#!/usr/bin/python3
while (count & 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
当执行上面的代码,它产生以下结果&-
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!&
块在这里,其中包括打印和增量语句,重复执行直到计数(count)不再小于9。每次迭代,将显示索引计数(count)的当前值和然后count&加1。
如果条件永远不会变为FALSE,一个循环就会变成无限循环。使用while循环时,有可能永远不会解析为FALSE值时而导致无限循环,所以必须谨慎使用。导致无法结束一个循环。这种循环被称为一个无限循环。
服务器需要连续运行,以便客户端程序可以在有需要通信时与服务器端通信,所以无限循环在客户机/服务器编程有用。
#!/usr/bin/python3
while var == 1 :
# This constructs an infinite loop
num = int(input("Enter a number
print ("You entered: ", num)
print ("Good bye!")
当执行上面的代码,它产生以下结果&-
Enter a number
You entered:
Enter a number
You entered:
Enter a number
You entered:
Enter a number
You entered:
Enter a number
You entered:
Enter a number
:Traceback (most recent call last):
File "examples\test.py", line 5, in
num = int(input("Enter a number
KeyboardInterrupt
上面的例子中执行进入了一个无限循环,你需要使用CTRL+C才能退出程序。
循环使用else语句
Python支持循环语句相关的else语句。
如果else语句在一个for循环中使用,当循环已经完成(用尽时)迭代列表执行else语句。
如果else语句用在while循环中,当条件变为&false,则执行 else 语句。
下面的例子说明了,只要它小于5,while语句打印这些数值,否则else语句被执行。
#!/usr/bin/python3
while count & 5:
print (count, " is
less than 5")
count = count + 1
print (count, " is not less than 5")
当执行上面的代码,它产生以下结果&-
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
单套件声明
类似于if语句的语法,如果while子句仅由单个语句组成,&它可以被放置在与while&同行整个标题。
这里是一个单行的&while&子句的语法和例子&-
#!/usr/bin/python3
while (flag): print ('Given flag is really true!')
print ("Good bye!")
上面的例子中进入无限循环,需要按 Ctrl+C 键才能退出。
本站代码下载:

我要回帖

更多关于 python while无限循环 的文章

 

随机推荐