【问题标题】:How to convert this while loop to for loop如何将此while循环转换为for循环
【发布时间】: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


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2023-01-22
    • 2018-03-19
    • 2017-02-14
    相关资源
    最近更新 更多