while与for相比
for循环用在有次数的循环上。
while循环用在有条件的控制上,和 if 比较相似。
while循环,直到表达式变为假(或者有一个break),才退出while循环,表达式是一个逻辑表达式,必须返回一个True或False。语法如下:
while expression: statement(s)
现在我们写一个while循环,让用户输入指定字符退出,如下所示:
#!/usr/local/python3/bin/pythonx=''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")
运行的测试结果如下:
[root@izj6cdhdoq5a5z7lfkmaeaz ~]# python whileE.pyhelloPlease input something like q for quit :ePlease continue.helloPlease input something like q for quit :rePlease continue.helloPlease input something like q for quit :quithelloPlease input something like q for quit :qPlease continue.world[root@izj6cdhdoq5a5z7lfkmaeaz ~]#