while与for相比python
for循环用在有次数的循环上。express
while循环用在有条件的控制上,和 if 比较类似。ide
while循环,直到表达式变为假(或者有一个break),才退出while循环,表达式是一个逻辑表达式,必须返回一个True或False。语法以下:测试
while expression: statement(s)
如今咱们写一个while循环,让用户输入指定字符退出,以下所示:ui
#!/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")
运行的测试结果以下:code
[root@izj6cdhdoq5a5z7lfkmaeaz ~]# 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 [root@izj6cdhdoq5a5z7lfkmaeaz ~]#