免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2083 | 回复: 2
打印 上一主题 下一主题

python学习之while语句 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-10-27 15:48 |只看该作者 |倒序浏览
while语句在一个条件为真的情况下,while语句允许你重复执行一块语句。直接看例子:
  1. #!/usr/bin/python
  2. # Filename: while.py

  3. number = 23
  4. running = True

  5. while running:
  6.     guess = int(raw_input('Enter an integer : '))

  7.     if guess == number:
  8.         print 'Congratulations, you guessed it.'
  9.         running = False # this causes the while loop to stop
  10.     elif guess < number:
  11.         print 'No, it is a little higher than that'
  12.     else:
  13.         print 'No, it is a little lower than that'
  14. else:
  15.     print 'The while loop is over.'
  16.     # Do anything else you want to do here

  17. print 'Done'
复制代码
当输入23时,程序执行done,结束,否则一直在循环(当然输入非整数时语法错误,程序会跳出的)。

运行结果:
  1. $ python while.py
  2. Enter an integer : 50
  3. No, it is a little lower than that.
  4. Enter an integer : 22
  5. No, it is a little higher than that.
  6. Enter an integer : 23
  7. Congratulations, you guessed it.
  8. The while loop is over.
  9. Done
复制代码
//这里要说明的是python语言对空格要求的很严格,必须是对应的,否则语法是不正确的。

论坛徽章:
0
2 [报告]
发表于 2010-10-27 16:34 |只看该作者
好吧,我承认你在教没接触过编程的同学...

论坛徽章:
0
3 [报告]
发表于 2010-10-28 12:24 |只看该作者
本帖最后由 a515200 于 2010-10-28 17:23 编辑

                                                              
                                               
                                       
                                 
                                 
                    














































































                                                                                                                                                                                                
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP