for 循环主要去对列表、字符串、文件的行数等有次数的循环上。
    while 循环在有条件的控制上。
    while循环,直到表达式变为假(或者有一个break),才退会出while循环,表达式是一个逻辑表达式,必须返回一个True或False
 
语法:
while
expression:   statement(s)
#注意:避免写成死循环
 

练习

    直到输入是q,退出循环
#!/usr/bin/env python
x = '' ————站位,否则while会报x未定义
while x != 'q': ————条件式循环
  print 'hello'
  x = raw_input("Please input something:")
  if x == 'quit':
    continue
    print 'next'
  else:
    print 'END'
    判断输入的时候是空字符,是的话,就退出循环
#!/usr/bin/env python
x = ''
while x != 'q':
  print 'hello'
  x = raw_input("Please input something:")
  if x == 'quit':
    continue
    print 'next'
  if not x:
    break
  else:
    print 'END'

 在Python中空表示false,所以not x,就表示True,所以if not x表达式成立就直接break了。

相关文章:

  • 2021-12-05
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-12-23
猜你喜欢
  • 2021-12-18
  • 2019-09-01
  • 2022-02-04
  • 2022-02-18
  • 2021-06-04
  • 2021-07-11
  • 2021-06-08
相关资源
相似解决方案