Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典中选择项目时,原始虚拟商店项目失败_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 从字典中选择项目时,原始虚拟商店项目失败

Python 从字典中选择项目时,原始虚拟商店项目失败,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,作为一个小项目(我两天前开始编写代码),我正在用Python3.x脚本制作一个粗糙的商店,当我的程序试图从用户开始使用的初始金额中减去用户选择的项目的值时,程序崩溃 注意:balance():函数旨在显示尚未完成的剩余金额 我如何修复我的代码,还有其他方法可以改进/优化它吗?另外,如果你给出一个解决方案,请假设我不知道你将使用什么方法,所以请给出上下文并解释你正在使用什么以及它可以用于的其他应用程序 import time import sys # Dictionary: # Shop Cat

作为一个小项目(我两天前开始编写代码),我正在用Python3.x脚本制作一个粗糙的商店,当我的程序试图从用户开始使用的初始金额中减去用户选择的项目的值时,程序崩溃

注意:balance():函数旨在显示尚未完成的剩余金额

我如何修复我的代码,还有其他方法可以改进/优化它吗?另外,如果你给出一个解决方案,请假设我不知道你将使用什么方法,所以请给出上下文并解释你正在使用什么以及它可以用于的其他应用程序

import time
import sys

# Dictionary:
# Shop Catalog, with numbers for prices.
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }

# Money Values/Variables:
# Initial Money
initialMoney = 3000

# Functions:
# Catalog browsing:
# This is where you are presented the different items on sale, and choose which you will order

def browse():
    print("Welcome to the Virtual Shop Catalog")
    time.sleep(1)
    print("Here is what is currently on sale (item:price): ")
    time.sleep(1)
    print(shopCatalog)
    time.sleep(1)
    print("Enter '4' to quit")
    time.sleep(1)

# This loop is where you choose to either return to the main menu, or order items.
    while True:
        try:
                shopChoice = int(input("Enter item of choice: "))
                if shopChoice == 4:
                    print("Returning back to main menu...")
                    time.sleep(0.5)
                    mainMenu()
                    break

                # This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance
                elif shopChoice == 1 or  2 or 3 or 4 or 5 or 6:
                    print(" Purchased 1 " + shopCatalog[shopChoice] + " .")
                    initialMoney = initialMoney - shopCatalog[shopChoice]
                    break
                elif shopChoice == 3:
                    print("You want to leave already...? Ok, have a good day!")
                    time.sleep(1)
                    break
                else:
                    print("Invalid option. Please pick a choice from 1-6")
                    browse()
        except ValueError:
                print("Invalid option. Please input an integer.")
    exit            

# Balance and money in account:
# This loop allows you to check the money in your account:

def balance():
    print("hi")

# Menu selection function:
# It gives the user a number of three options, and will only accept the three integers provided.

def mainMenu ():
    time.sleep(0.5)
    print("1. Browse shop catalog")
    time.sleep(0.5)
    print("2. Check remaining balance")
    time.sleep(0.5)
    print("3. Quit program")

    while True:
        try:
            choice = int(input("Enter number of choice: "))
            if choice == 1:
                browse()
                break
            elif choice  == 2:
                balance()
                break
            elif choice == 3:
                print("You want to leave already...? Ok, have a good day!")
                time.sleep(1)
                break
            else:
                print("Invalid option. Please pick a choice from 1-3")
                mainMenu()
        except ValueError:
            print("Invalid option. Please input an integer.")
    exit     

# On startup:
# This is the startup code and messages

print("Welcome to my virtual shop!")
time.sleep(0.5)
print("What would you like to do?")
time.sleep(0.5)
mainMenu()

车间目录定义为:

shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }
但是,您正在尝试按数字访问密钥。比如

shopCatalog[2]
它不作为有效密钥存在。一个有效的密钥是
shopCatalog['2.Gucci腰带]

相反,尝试一个元组列表。列表更好,因为顺序是有保证的。在dict中,即使您对项目进行了编号,它也可能会打印出错误的顺序

shopCatalog = [ ('MCM Backpack', 790), ('Gucci Belt' : 450) , ...]
如果您想要第一项,您可以通过索引访问它。如果您想对它们进行编号,同样,只需使用索引(尽管对于两者,请记住它是零索引的,因此您可能需要添加以打印编号,然后减去一以获得正确的项目)

此外,您的逻辑中存在一个缺陷:
shopChoice==1或2或3或4或5或6:

当人们这样说话时,编码不是这样工作的。相反,你必须做:
shopChoice==1或shopChoice==2,依此类推。但跳过所有这些,只需说:

elif 1试试下面的代码,现在我认为它可以工作了:

import time
import sys

# Dictionary:
# Shop Catalog, with numbers for prices.
shopCatalog = { '1. MCM Backpack' : 790 , '2. Gucci Belt' : 450 , '3. Supreme Box Logo Tee' : 100 , '4. Louis Vuitton Trenchcoat' : 1600 , '5. OFF-WHITE windbreaker' : 1200 , '6. Balenciaga Sneakers' : 850 }

# Money Values/Variables:
# Initial Money
initialMoney = 3000

# Functions:
# Catalog browsing:
# This is where you are presented the different items on sale, and choose which you will order

def browse():
    global initialMoney
    print("Welcome to the Virtual Shop Catalog")
    time.sleep(1)
    print("Here is what is currently on sale (item:price): ")
    time.sleep(1)
    print(shopCatalog)
    time.sleep(1)
    print("Enter '4' to quit")
    time.sleep(1)

# This loop is where you choose to either return to the main menu, or order items.
    while True:
        try:
                shopChoice = input("Enter item of choice: ")
                if shopChoice == 4:
                    print("Returning back to main menu...")
                    time.sleep(0.5)
                    mainMenu()
                    break

                # This is supposed to reduce the value/price of the item from your inital amount of money (initalmoney) or balance
                elif shopChoice in ('1','2','3','4','5','6'):
                    print(" Purchased 1 " + str(shopCatalog[[i for i in shopCatalog.keys() if str(shopChoice) in i][0]]) + " .")
                    initialMoney = initialMoney - shopCatalog[[i for i in shopCatalog.keys() if str(shopChoice) in i][0]]
                    break
                elif shopChoice == 3:
                    print("You want to leave already...? Ok, have a good day!")
                    time.sleep(1)
                    break
                else:
                    print("Invalid option. Please pick a choice from 1-6")
                    browse()
        except ValueError:
                print("Invalid option. Please input an integer.")
    exit            

# Balance and money in account:
# This loop allows you to check the money in your account:

def balance():
    print("hi")

# Menu selection function:
# It gives the user a number of three options, and will only accept the three integers provided.

def mainMenu ():
    time.sleep(0.5)
    print("1. Browse shop catalog")
    time.sleep(0.5)
    print("2. Check remaining balance")
    time.sleep(0.5)
    print("3. Quit program")

    while True:
        try:
            choice = int(input("Enter number of choice: "))
            if choice == 1:
                browse()
                break
            elif choice  == 2:
                balance()
                break
            elif choice == 3:
                print("You want to leave already...? Ok, have a good day!")
                time.sleep(1)
                break
            else:
                print("Invalid option. Please pick a choice from 1-3")
                mainMenu()
        except ValueError:
            print("Invalid option. Please input an integer.")
    exit     

# On startup:
# This is the startup code and messages

print("Welcome to my virtual shop!")
time.sleep(0.5)
print("What would you like to do?")
time.sleep(0.5)
mainMenu()
您的代码不起作用,因为没有这样一个键,即
1
2
等,所以我只需检查每个键,如果
shopChoice
在其中,则获取其值,如果不在,则检查下一个。

错误是:

Traceback (most recent call last):
  File "C:/Users/s4394487/Downloads/crap.py", line 96, in <module>
    mainMenu()
  File "C:/Users/s4394487/Downloads/crap.py", line 73, in mainMenu
    browse()
  File "C:/Users/s4394487/Downloads/crap.py", line 38, in browse
    print(" Purchased 1 " + shopCatalog[shopChoice] + " .")
KeyError: 1
回溯(最近一次呼叫最后一次):
文件“C:/Users/s4394487/Downloads/crap.py”,第96行,在
主菜单()
主菜单第73行的文件“C:/Users/s4394487/Downloads/crap.py”
浏览()
文件“C:/Users/s4394487/Downloads/crap.py”,第38行,浏览
打印(“购买1”+商店目录[shopChoice]+”)
关键错误:1
shopCatalog是一本字典,因此您可以使用键访问其值。键是“1.MCM背包”、“2.Gucci腰带”等,而不是数字


如果要访问字典中的第一个、第二个等值,可以使用Python中的OrderedDictionary:

Python产生的错误是什么?回溯(最近一次调用):mainMenu browse()第73行文件“C:/Users/s4394487/Downloads/crap.py”中的第96行文件“C:/Users/s4394487/Downloads/crap.py”文件“C:/Users/s4394487/Downloads/crap.py”,第38行,在浏览打印中(“购买1”+商店目录[shopChoice]+”)键错误:1OP“另外,如果你给出一个解决方案,请假设我不知道你将使用什么方法,所以请给出上下文并解释你正在使用的内容以及它可以用于的其他应用程序。提前谢谢你。”你应该这样做。@Zev好的,我会的。你也可以使用
the_dict[the_dict.keys()[1]]
没有,因为dict不一定记得按键的顺序,你是对的。要想让dict正常工作,就必须订购dict。谢谢你选择我的答案。如果有什么我可以澄清的,请告诉我。