Reputation: 55
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
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