为什么这不能在字典中打印出一个值?

2024-09-21 09:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让它从用户输入的键中打印出字典中的一个值,但是什么也没有出来。有什么想法吗

u_items=input("Enter 'list' to see a list of items, or 'Book', 'Apple', 'Toy', 'Pumpkin', 'Bowl' or 'Purse' to see the item's price: ")
u_items=u_items.title()

inventory={'Book':'18', 'Apple':'3', 'Toy':'7', 'Pumpkin':'9', 'Bowl':'5', 'Purse':'30'}

if u_items in inventory[u_items] == True:
    print("A " + u_items + "costs $" + inventory[u_items])

elif u_items == 'List':
    print(items(inventory))

Tags: orto用户apple字典itemslistinventory
1条回答
网友
1楼 · 发布于 2024-09-21 09:47:52

你的if语句构造错误。应该是这样的:

if u_items in inventory:

测试字典中是否存在u_items(用户输入的键)

您之前所做的是查看通过使用u_items索引inventory返回的值中是否存在u_items。因此,如果用户输入'apple',代码的解释如下:

if 'Apple' in '3' == True:

相关问题 更多 >

    热门问题