- Hello, I am fairly new to python and wondering how to convert this while loop to a for loop. I am not sure how to keep looping the inputs so it keeps asking Enter a line until GO and then say Next until STOP then display the count of lines.
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
while(line[:4] != "STOP"):
if (line[:2] == "GO"):
flag = True
if flag:
line = input("Next: ")
count += 1
else:
line = input("Enter a line: ")
print(f"Counted {count-1} lines")
keyboard()
With these inputs:
ignore me
and me
GO GO GO!
I'm an important line
So am I
Me too!
STOP now please
I shouldn't even be read let alone printed
Nor me
Should display/result in:
Enter a line: ignore me
Enter a line: and me
Enter a line: GO GO GO!
Next: I'm an important line
Next: So am I
Next: Me too!
Next: STOP now please
Counted 3 lines