[英]Changing While loop to a For loop
我正在學習python中for循環和while循環之間的區別。 如果我有一個while循環,像這樣:
num = str(input("Please enter the number one: "))
while num != "1":
print("This is not the number one")
num = str(input("Please enter the number one: "))
是否可以將其寫為for循環?
很笨拙 顯然, for
循環在這里不合適
from itertools import repeat
for i in repeat(None):
num = str(input("Please enter the number one: "))
if num == "1":
break
print("This is not the number one")
如果您只是想限制嘗試次數,那是另一回事了
for attempt in range(3):
num = str(input("Please enter the number one: "))
if num == "1":
break
print("This is not the number one")
else:
print("Sorry, too many attempts")
嚴格說來不是真的,因為雖然while
循環可以很容易地永遠運行,但是for
循環必須算是什么 。
但如果你使用一個迭代器,如提到這里 ,那么就可以實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.