python-3.x - Python - 如何使用多变量重新输入异常?
问题描述
对python来说很新,我想知道如果用户输入负数,我如何让用户重新输入他们的多个变量而不让他们经历整个循环?这就是我到目前为止所拥有的。
while True:
try:
length = float(input("Length of the room in feet?\n").strip())
if length < 0: raise Exception
width = float(input("Width of the room in feet?\n").strip())
if width < 0: raise Exception
height = float(input("Height of the room in feet?\n").strip())
if height < 0: raise Exception
break
except Exception:
print("The number must be at least 0ft! Please try again.")
except ValueError:
print("Please print numerical values only! (grater than 0)")
因此,例如,如果他们正确输入了高度,但为宽度输入了负值,他们将不得不再次重新输入高度变量。通过为每个变量使用一个while循环来解决这个问题的唯一方法是什么?
解决方案
也许您可以检查代码末尾的值并引发异常,如下所示
while True:
try:
length = float(input("Length of the room in feet?\n").strip())
width = float(input("Width of the room in feet?\n").strip())
height = float(input("Height of the room in feet?\n").strip())
if (length < 0 or height < 0 or width < 0):
raise Exception
else:
break
except Exception:
print("The number must be at least 0ft! Please try again.")
except ValueError:
print("Please print numerical values only! (grater than 0)")
这段代码的作用是,它检查任何小于 0 的值,否则它再次要求所有三个变量值,这是你想要的吗?
推荐阅读
- python - 用pyserial实时绘制2系列数据
- javascript - webpack + shelljs 会抛出“错误:找不到模块'/exec-child.js'”
- git - 将 git 子目录拆分为子模块保留历史记录
- flutter - 如何在 Flutter Web 中导入依赖项?
- mysql - 从两个日期列之间的 mysql 表中获取行时出现问题
- machine-learning - 如何收集和过滤图像以进行图像识别?
- php - 在服务器上将大型文件上传到 Amazon S3 失败
- flutter - 在flutter中从资产中读取文件后逐行读取字符串
- python - 检索数据返回无
- ios - I want email address from 2nd ViewController to be used for mail.setToRecipients([myTextField.text ?? ""])