Python 对dictionary对象使用if/then条件

Python 对dictionary对象使用if/then条件,python,dictionary,Python,Dictionary,我是python新手,一直在从事一些活动。目前,我的工作条件。我创建了一个月的字典,并使用if/then条件检查字典中是否有用户输入。如果用户输入不在字典中,则输出应为“坏月”。我的代码如下: months = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July'

我是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()
进行比较,并打印该
键的相应

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')
演示:


你可以走几条路。如果要保留代码大纲,请尝试

if int(choice) in months:
    print('months')

else:
    print('Bad month')
正如一些评论所建议的,更好的方法可能是使用
get
语法()


将检查
输入
,如果找不到,则返回坏月。只需打印
get
函数返回的内容,它就可以完成您需要的操作

你想打印什么?月份键?您可能希望执行
print(months[int(choice)])
。摆脱该条件并执行:
print(months.Get(int(choice),“Bad month”)
可能重复的月份键,最好将其强制转换一次,并保留强制转换的
choice
。为什么在months.keys()中使用
而不是像问题中那样在几个月内
if int(choice) in months:
    print('months')

else:
    print('Bad month')
months.get(input, "Bad Month")