首页 > 编程语言 > 详细

Python的流程控制 - while

时间:2018-01-11 11:19:25      阅读:209      评论:0      收藏:0      [点我收藏+]
while与for相比

for循环用在有次数的循环上。

while循环用在有条件的控制上,和 if 比较相似。

while循环,直到表达式变为假(或者有一个break),才退出while循环,表达式是一个逻辑表达式,必须返回一个True或False。语法如下:

while expression:
    statement(s)

现在我们写一个while循环,让用户输入指定字符退出,如下所示:

#!/usr/local/python3/bin/python

x=‘‘
while x != ‘q‘:
    print(‘hello‘)
    x=input("Please input something like q for quit :")
    if not x:
        break
    if x==‘quit‘:
        continue
    print("Please continue.")

else:
    print("world")

运行的测试结果如下:

[root@izj6cdhdoq5a5z7lfkmaeaz ~]# python whileE.py
hello
Please input something like q for quit :e
Please continue.
hello
Please input something like q for quit :re
Please continue.
hello
Please input something like q for quit :quit
hello
Please input something like q for quit :q
Please continue.
world
[root@izj6cdhdoq5a5z7lfkmaeaz ~]#

Python的流程控制 - while

原文:http://blog.51cto.com/shaoniana/2059742

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!