ITPub博客

首页 > IT职业 > IT生活 > Python的流程控制 - while

Python的流程控制 - while

IT生活 作者:wh7577 时间:2021-09-09 09:21:36 0 删除 编辑

while与for相比

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

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

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

while expression:    statement(s)

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

#!/usr/local/python3/bin/pythonx=''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.pyhelloPlease input something like q for quit :ePlease continue.helloPlease input something like q for quit :rePlease continue.helloPlease input something like q for quit :quithelloPlease input something like q for quit :qPlease continue.world[root@izj6cdhdoq5a5z7lfkmaeaz ~]#

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2480/viewspace-2802613/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-23

  • 博文量
    105
  • 访问量
    15384