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

2024-09-29 23:31:11 发布

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

作为一个小项目(我两天前开始编写代码),我在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()

Tags: orofthetoyoutimeissleep
3条回答

商店目录定义为:

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 Belt']

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

shopCatalog = [ ('MCM Backpack', 790), ('Gucci Belt' : 450) , ...]

如果您想要第一个项目,您可以通过索引访问它。如果你想给它们编号,同样地,只需使用索引(尽管对于两者,请记住它是零索引的,所以你可能需要添加以打印编号,然后减去一以得到正确的项目)

另外,你的逻辑也有缺陷: shopChoice == 1 or 2 or 3 or 4 or 5 or 6:

当人们这么说的时候,编码并不是这样工作的。相反,你必须: shopChoice ==1 or shopChoice ==2等等。但是跳过这些,直接说: elif 1 <= shopChoice <= 6:

试试下面的代码,现在我想它可以工作了:

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()

你的代码不起作用,因为没有这样的键,例如12等等,所以我只要检查每个键,如果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

shopCatalog是一个字典,因此您可以使用键访问它的值。钥匙是“1.MCM背包”、“2.Gucci腰带”等,不是数字

如果要访问字典中的第一个、第二个等值,可以使用Python中的OrderedDictionary:https://docs.python.org/3/library/collections.html#collections.OrderedDict

相关问题 更多 >

    热门问题