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?

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.