【发布时间】:2021-02-17 23:30:39
【问题描述】:
- 您好,我对 python 还很陌生,想知道如何将此 while 循环转换为 for 循环。我不知道如何继续循环输入,所以它会一直询问 Enter a line until GO 然后说 Next 直到 STOP 然后显示行数。
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
【问题讨论】:
-
如果您(或更好的代码)不知道 while 循环的总行数是最好的方法。为什么要改成for循环呢?
-
我只是想更好地理解代码,并能够从 while 切换到 for 和 for to while
-
@Finn 做到了。所以在这种情况下,切换到
for循环是没有意义的。
标签: python