前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >While 循环语句

While 循环语句

作者头像
老七Linux
发布2018-05-09 17:17:12
1.6K0
发布2018-05-09 17:17:12
举报

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。当然也可以遍历所有的字符串,列表,元祖等。

其基本形式为:

代码语言:javascript
复制
while 判断条件:
    执行语句……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。

当判断条件假false时,循环结束。

for 循环一般是用在一个有次数的循环上。

while 循环用在有条件的控制上。

来个容易上手的例子:

代码语言:javascript
复制
n = 0   ## 给n赋值初始值 0
while True:     ## True为表达式成立
    if n == 10:     ## 当 n==10的时候
        break       ## 跳出循环
    print n, 'hello'   ## 打印 ‘hello’
    n += 1      ## n=n+1

## 整体的程序是:使用while循环打印hello,当n==10 的时候就会停止。

执行结果:

代码语言:javascript
复制
0 hello
1 hello
2 hello
3 hello
4 hello
5 hello
6 hello
7 hello
8 hello
9 hello

手动选择停止 while 循环:

代码语言:javascript
复制
while True:
    aa = raw_input("pls input anything you want, use 'quit' to stop: ")
    if aa == 'quit':
        break

输出的结果是:

代码语言:javascript
复制
pls input anything you want, use 'quit' for stop: qawe
pls input anything you want, use 'quit' for stop: 123
pls input anything you want, use 'quit' for stop: q12
pls input anything you want, use 'quit' for stop: quit

Process finished with exit code 0
循环使用 else 语句

在 python 中,while … else 在循环条件为 false 时执行 else 语句块:

代码语言:javascript
复制
#!/usr/bin/python
 
count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

以上实例输出结果为:

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017/06/28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 循环使用 else 语句
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档