[英]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.