首页 > 解决方案 > 他们是如何摆脱这个 while true 循环的?

问题描述

在我的理解while True:中意味着永远循环,比如说 while True == True
还有一种机制可以使用break语句打破无限循环。我在cs50 模块
中遇到了一个函数,它使用 while 循环(不断提示输入 int),其中没有中断。 我试图了解,当我们输入一个 int 时,如何在循环中将“True statement”更改为 False(这就是我的理解)并且我们停止提示用户。

换句话说,什么可以将代码中的 while True 更改为 false?

功能如下:

def get_long(prompt=None):
    """
    Read a line of text from standard input and return the equivalent long;
    if text does not represent a long, user is prompted to retry. If line
    can't be read, return None.
    """
    while True:
        s = get_string(prompt)
        if s is None:
            return None
        if re.search(r"^[+-]?\d+$", s):
            try:
                return long(s, 10)
            except ValueError:
                pass

        # temporarily here for backwards compatibility
        if prompt is None:
            print("Retry: ", end="")

里面使用的get_string()函数如下:

def get_string(prompt=None):
"""
Read a line of text from standard input and return it as a string,
sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n)
as line endings. If user inputs only a line ending, returns "", not None.
Returns None upon error or no input whatsoever (i.e., just EOF). Exits
from Python altogether on SIGINT.
"""
try:
    if prompt is not None:
        print(prompt, end="")
    s = sys.stdin.readline()
    if not s:
        return None
    return re.sub(r"(?:\r|\r\n|\n)$", "", s)
except KeyboardInterrupt:
    sys.exit("")
except ValueError:
    return None

I am trying to figure how the while True statement is no more true when the s variable get a string and when the string is casted into an int ? Can someone please explain this to me, maybe I am missing something about the while True: statements.

标签: pythonwhile-loopbooleancs50

解决方案


在这个场景中,突破使用的是回报。因此,当满足条件时,封闭函数返回。如果无法读取用户响应,则返回 None。pass 只是一种忽略错误并继续提示用户输入的方法。


推荐阅读