2015-12-09 234 views
0

我正在学习python中for循环和while循环之间的区别。 如果我有一个while循环是这样的:将While循环更改为For循环

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循环?

回答

0

严格地说不是真的,因为当你的while循环可以很容易地运行下去,一个for循环具有数到东西

但如果你使用一个迭代器,如提及here,那么就可以实现。

1

非常笨拙。显然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")