首页 > 解决方案 > 强制出错时无法打印除语句

问题描述

强制出错时,我似乎无法打印我的 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()

标签: pythonpython-3.xerror-handling

解决方案


以下行;

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))

推荐阅读