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 ~]#