How to convert this while loop to for loop

You just need an infinity for loop which is what while True essentially is. This answer has it: Infinite for loops possible in Python?

#int will never get to 1
for _ in iter(int, 1):

So just replace your while loop with the above and add a break condition.

def keyboard():
    """Repeatedly reads lines from standard input until a line is read that 
    begins with the 2 characters "GO". Then a prompt Next: , until a line is 
    read that begins with the 4 characters "STOP". The program then prints a 
    count of the number of lines between the GO line and the STOP line (but 
    not including them in the count) and exits."""
    line = input("Enter a line: ")
    flag = False
    count = 0
    for _ in iter(int, 1):
        if line[:4] == "STOP":
        if (line[:2] == "GO"):
            flag = True
        if flag:
            line = input("Next: ")
            count += 1
            line = input("Enter a line: ")
    print(f"Counted {count-1} lines")

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top