Bob Smith
Bob Smith

Reputation: 55

Changing While loop to a For loop

I am learning about the differences between for loops and while loops in python. If I have a while loop like this:

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: "))

Is it possible to write this as a for loop?

Upvotes: 0

Views: 119

Answers (2)

John La Rooy
John La Rooy

Reputation: 304137

Very clumsy. Clearly a for loop is not appropriate here

    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")

If you just wanted to restrict the number of attempts, it's another story

    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")

Upvotes: 1

101
101

Reputation: 8989

Strictly speaking not really, because while your while loop can easily run forever, a for loop has to count to something.

Although if you use an iterator, such as mentioned here, then that can be achieved.

Upvotes: 0

Related Questions