python - 强制出错时无法打印除语句
问题描述
强制出错时,我似乎无法打印我的 except 语句。
PLANT_DATA = { 'daisy': 'diasy.csv',
'rose': 'rose.csv',
'cucumber': 'cucumber.csv' }
def filters():
print('Let\'s explore some plant data')
while True:
plant = input("Would you like to see data for Cucumber, Daisy or Rose plants?").lower()
if plant in PLANT_DATA.keys():
try:
print("Looks like you want to hear about {} plants!".format(plant))
break
except ValueError:
print("That is not a valid plant! Please try again.")
filters()
解决方案
以下行;
if plant in PLANT_DATA.keys():
检查字典中是否存在提供的键。您永远不会到达您的 except 子句,因为您已经在代码的前面执行了检查。这就是为什么每当您输入错误的值时,它会再次提示您输入问题。
如果您需要打印错误,请尝试此操作。
if plant not in PLANT_DATA.keys():
print("That is not a valid plant! Please try again.")
else:
print("Looks like you want to hear about {} plants!".format(city))
推荐阅读
- r - 居中 rHandsontableOutput - Shiny
- angular - 提交时的角度材料验证
- powershell - 在不使用反引号的情况下运行 PowerShell 脚本文件,其路径包含来自 Jenkins Pipeline 的空格
- android - 覆盖 onNewToken 并从 firebase 错误中获取令牌
- returnn - Return中的预训练
- python - OpenCV - 从图像中删除文本
- php - 嵌套集仅适用于类别或终端元素?
- python - 安装 python 3.7.1 后终端输出“找不到命令”
- mysql - laravel 中的非法混合排序规则
- html - 屏幕调整大小时文本变小