0

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?

Bob Smith
  • 55
  • 1
  • 6

2 Answers2

1

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")
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

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.

101
  • 8,514
  • 6
  • 43
  • 69