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()
使用这些输入:
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
应显示/显示:
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
答案 0 :(得分:1)
您只需要一个无限for
循环,本质上就是while True
。
这个答案有:Infinite for loops possible in Python?
#int will never get to 1
for _ in iter(int, 1):
pass
因此,只需将以上内容替换为while循环并添加一个中断条件即可。
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":
break
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()