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")
運行的測試結果如下:
[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 ~]#