【问题标题】:cs50: pset6: Why both of these while loops don't work as expected? [duplicate]cs50: pset6: 为什么这两个 while 循环都不能按预期工作? [复制]
【发布时间】:2020-12-11 12:41:17
【问题描述】:

无法弄清楚为什么这些循环不能按预期工作。我希望用户输入一个字符串(高度),如果它包含字符,请再次请求高度,直到输入某些整数。

第一个循环:这里。我期待如果我输入一个从 1 到 8 的数字,循环会中断,但事实并非如此!它一直在请求高度。

height = input("What's the height?\n")
while type(height) != int or (height < 1 or height >= 9):
    height = input("What's the height?\n")

第二个循环:期望相同。循环没有中断,一直在询问高度。

while True:
    height = input("What's the height?\n")
    if type(height) == int and (height >= 1 and height <= 8):
        break 

刚接触 Python,但这似乎不是 Python 问题,更像是我在 while 循环中缺少的东西。

编辑

终于成功了。这就像一个魅力。

while True:
height = input("What's the height?\n")
if not(height.isalpha()):
    if not(height.isspace()):
        if height != "":
            height = int(height)
            if height >= 1 and height <= 8:
                break 

【问题讨论】:

  • height的类型在这里始终是字符串

标签: python-3.x while-loop cs50


【解决方案1】:

这将解决您的问题:

height = input("What's the height?\n")
while not(height.isnumeric()) or (int(height) < 1 or int(height) >= 9):
    height = input("What's the height?\n")

【讨论】:

  • 如果用户输入字符,我希望我的循环再次询问高度。如果我将代码修改为仅采用整数,则会出现错误。
  • 好的,我现在已经编辑了您查询的代码
  • 不幸的是它没有工作。我又得到一个字符串到 int 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 2013-07-25
  • 2016-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
相关资源
最近更新 更多