+ -
当前位置:首页 → 问答吧 → python学习之while语句

python学习之while语句

时间:2010-10-27

来源:互联网

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语言对空格要求的很严格,必须是对应的,否则语法是不正确的。

作者: c_u_c_u   发布时间: 2010-10-27

好吧,我承认你在教没接触过编程的同学...

作者: donotblock   发布时间: 2010-10-27