downmovies 发表于 2018-8-8 10:27:21

Python的流程控制 - while

  while与for相比
  for循环用在有次数的循环上。
  while循环用在有条件的控制上,和 if 比较相似。
  while循环,直到表达式变为假(或者有一个break),才退出while循环,表达式是一个逻辑表达式,必须返回一个True或False。语法如下:
  

while expression:  statement(s)
  

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

#!/usr/local/python3/bin/python  

  
x=''
  
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")
  

  运行的测试结果如下:
  

# python whileE.py  
hello
  
Please input something like q for quit :e
  
Please continue.
  
hello
  
Please input something like q for quit :re
  
Please continue.
  
hello
  
Please input something like q for quit :quit
  
hello
  
Please input something like q for quit :q
  
Please continue.
  
world
  
#
页: [1]
查看完整版本: Python的流程控制 - while