python - 他们是如何摆脱这个 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.
解决方案
在这个场景中,突破使用的是回报。因此,当满足条件时,封闭函数返回。如果无法读取用户响应,则返回 None。pass 只是一种忽略错误并继续提示用户输入的方法。
推荐阅读
- python - 如何从 iterator.combinations() 创建部分列表?
- python - 我应该在图像数据生成器中进行哪些更改来解决错误?
- pandas - 查找没有无的 groupby/transform 的唯一值
- xamarin.forms - 如果我的 Xamarin Forms Android 只有一个图标,是否需要创建启动画面?
- json - 我怎样才能把这个“\/\/cdn.apixu.com\/weather\/64x64\/day\/116.png”放在一个字符串里面,我对“\/\/”有问题
- android - 下载管理器:状态 HTTP 数据错误:无法从移动设备 IP 地址 android 连接到 Web 服务器
- python - 合并/加入 Pandas 数据框
- javascript - 具有嵌套表连接的 Knex 查询
- c - 用字符串复制到链表不起作用
- excel - 火花驱动器意外停止并正在重新启动。您的笔记本将自动重新附加