有人可以帮我解决以下问题吗?我对编程还比较陌生,我似乎不明白我做错了什么。
我发现了太多的字典功能,我真的很挣扎。我的代码给了我一个又一个的按键错误,当我最终设法运行该程序时,它返回“无”或 0。
这是代码示例。
# Dictionary called choices.
choices = {
'1.': 'One',
'2.': 'Two',
'3.': 'Three',
}
# Display the choices to the user.
for k, v in choices.items():
print(f'{k} {v}')
# Ask the user to make a choice from the dictionary options.
my_choice = int(input('Choose a number 1, 2 or 3: '))
# Make the choice the same as the index[number] of the dictionary
my_choice -= 1
# From here I get stuck
print(f'You have chosen {choices.get(str(my_choice))}.') # This returns a 0 or None
# The desired output is
You have chosen Two.
我尝试了以下选项将字典项分配给 my_choice 变量:
for loops
dict.values()
dict .get()
dict.items()
new_choice = str(my_choice)
# The desired output is
You have chosen Two.
由于您的字典键以
.
结尾,因此您需要将其添加到用户的输入中,以便它能够匹配。 choices.get(f'{my_choice}.'))
print(f"You have chosen {choices.get(str(my_choice) + '.')}.")
或者,您可以只使用整数作为键。
choices = {
1: 'One',
2: 'Two',
3: 'Three',
}
然后
print(f"You have chosen {choices.get(my_choice)}.")