【发布时间】: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