将 if/then 条件与字典对象一起使用



我是python的新手,并且一直在做一些活动。目前我正在使用条件。我创建了一个月份的字典,我正在使用 if/then 条件来检查用户输入是否在字典中。如果用户输入不在字典中,则输出应显示"糟糕的月份" 我的代码如下:

months = {1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'}
choice = input
choice = input('Enter an integer value for a month:')
result = choice
if int(choice) in months:
print('months')
else:
print('Bad month')

当输入任何大于 12 的整数时,输出是"坏月份",但当我输入 1-12 的数字时,输出只是几个月?我已经尝试了许多打印语句,但没有一个我尝试过有效。我被卡住了。

您需要将用户输入从input()作为string的内容转换为可以与字典keys()进行比较的integer,并打印该key的相应value

months = {1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12: 'December'}
choice = int(input('Enter an integer value for a month: ')) # cast user input to integer
if choice in months:        # check if user input exists in the dictionary keys
print(months[choice])   # print corresponding key value
else:
print('Bad month')

演示:

Enter an integer value for a month: 4
April

你可以在这里走几条路线。如果要保持代码大纲,请尝试

if int(choice) in months:
print('months')
else:
print('Bad month')

正如一些评论所建议的那样,更好的方法可能是使用get语法(教程(。

months.get(input, "Bad Month") 

将检查input,如果找不到,则返回"坏月"。 只需printget函数返回的内容,它就会完成您正在寻找的内容。

最新更新