将While循环更改为For循环

时间:2015-12-09 00:00:10

标签: python

我正在学习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循环?

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:0)

严格来说并非如此,因为虽然while循环可以轻松永久运行,但for循环必须计入某些内容

虽然如果使用迭代器,例如提到的here,那么就可以实现。