如何将此while循环转换为for循环

时间:2020-11-05 09:09:47

标签: python

  • 您好,我是python的新手,想知道如何将while循环转换为for循环。我不确定如何继续循环输入,因此一直询问输入一行直到GO,然后说下一步直到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

1 个答案:

答案 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()