使用字典,练习编码

2024-10-02 18:16:31 发布

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

我为我之前的问题道歉,因为它们含糊不清,难以回答。我对编程还是相当陌生的,而且还在学习它的来龙去脉。所以请容忍我。现在是背景资料。我使用的是python3.3.0。我把它加载到eclipseide上,这就是我用来编写代码和测试代码的地方。在

现在来问一个问题:我正在努力学习如何创建和使用词典。因此,我的任务是创建一个价格匹配代码,通过用户界面,不仅能够在字典中搜索项目(这些项目是关键字以及与关键字相关联的位置和价格)。到目前为止,我已经创建了一个用户界面,它可以很好地运行而不会出现任何错误(至少在IDE中)当我遍历并输入所有的提示时,空字典不会被更新,因此我无法调用字典以获得先前的输入。在

我有我已经写了下面的代码,如果有人可以告诉我,如果我做的事情是正确的。如果有更好的方法来解决这个问题。我仍在学习,因此更详细的代码术语解释将是有用的。在

print("let's Price match") 
decition = input("Are you adding to the price match list?") 
if decition == "yes": 
    pricematchlist = {"Snapple":["Tops",99]} 
    location = input("Now tell me where you shopped") 
    item = input("Now what  was the item") 
    price = input("Now how much was the item") 
    int(price) 
    pricematchlist[item]=location,price 
    print(pricematchlist) 
else:  
    pricematchlist = {"Snapple":["Tops",99]}  
    reply = input("Ok so you want to search up a previous price?") 
    if reply == "yes": 
        search = input("What was the item?")
        pricematchlist.item(search)

Tags: the项目代码youinputsearch字典价格
1条回答
网友
1楼 · 发布于 2024-10-02 18:16:31

这是一些小的改变。对于字典:您正确地使用了它们。在

print("let's Price match") 
pricemathlist = {"Snapple":["Tops", 99]} # assign it here
decition = input("Are you adding to the price match list?").lower() #"Yes" >"yes"
if decition == "yes": 
    # pricematchlist = {"Snapple":["Tops",99]}
    # If this whole code block is called repeatedly, you don't want to reassign it
    location = input("Now tell me where you shopped") 
    item = input("Now what  was the item") 
    price = int(input("Now how much was the item"))
    # int(price) does nothing with reassigning price
    pricematchlist[item]=location,price 
    print(pricematchlist) 
else:    
    reply = input("Ok so you want to search up a previous price?").lower()
    if reply == "yes": 
        search = input("What was the item?")
        print pricematchlist[search] # easier way of accessing a value

相关问题 更多 >