首页 > 解决方案 > Python - 根据整个代码中的用户输入分配和计算最终成本?

问题描述

我目前正在尝试创建一个人们可以“购买”书籍的购物程序。问题是我必须计算购买的最终成本,这是我坚持的。我是否为每个项目创建变量并分配价格?感谢您的帮助!我当前的代码如下。

def showOptions():
    print('''Item Number: 1000
Title: Science: A Visual Encyclopedia
Author: Chris Woodford
Genre: Science
Price: $23.99
==============================
Item Number: 1001
Title: My First Human Body Book
Author: Patricia J. Wynne and Donald M. Silver
Genre: Science
Price: $3.99
==============================
Item Number: 1002
Title: The Runaway Children
Author: Sandy Taylor
Genre: Fiction
Price: $3.99
==============================
Item Number: 1003
Title: The Tuscan Child
Author: Rhys Bowen
Genre: Fiction
Price: $9.99
==============================
Item Number: 1004
Title: Learning Python
Author: Mark Lutz
Genre: Programming
Price: $61.99
''')
    
def displayCart():
    shopping_list = open('bookcart.txt')
    contents = shopping_list.read()  
    print('Here is your cart:')
    print(contents) 
    print()
    shopping_list.close()

def addItem(item):
    shopping = open('bookcart.txt', 'a')
    whichbook = input("Please input the item number")
        if whichbook == '1000':
            shopping.write('''Item Number: 1000
Title: Science: A Visual Encyclopedia
Author: Chris Woodford
Genre: Science
Price: $23.99''')
            shopping.close()
            print('Item has been added') 
            print()
        elif whichbook == '1001':
            shopping.write('''Item Number: 1001
Title: My First Human Body Book
Author: Patricia J. Wynne and Donald M. Silver
Genre: Science
Price: $3.99''')
            shopping.close()
            print('Item has been added') 
            print()
        elif whichbook == '1002':
            shopping.write('''Item Number: 1003
Title: The Tuscan Child
Author: Rhys Bowen
Genre: Fiction
Price: $9.99''')
            shopping.close()
            print('Item has been added') 
            print()
        elif whichbook == '1003':
            shopping.write('''Item Number: 1003
Title: The Tuscan Child
Author: Rhys Bowen
Genre: Fiction
Price: $9.99''')
            shopping.close()
            print('Item has been added') 
            print()
        elif whichbook == '1004':
            shopping.write('''Item Number: 1004
Title: Learning Python
Author: Mark Lutz
Genre: Programming
Price: $61.99''')
            shopping.close()
            print('Item has been added') 
            print()
        else:
            print("Did not understand.")


def checkItem(item):
    shopping_list = open('bookcart.txt')
    contents = shopping_list.readlines() #puts all the items into a list
    shopping_list.close()
    item = item + '\n'
    if item in contents: #If the specific item is in the list, the function returns true. Otherwise, it returns false.
        return True
    else:
        return False

while True:
    menu = int(input('''1. Display Books
2. Add item to cart
3. Show Cart
4. Checkout
5. Quit
Select an option:
'''))
    print()
    
    if menu == 1:
        showOptions()

    elif menu == 2:
        addItem()

    elif menu == 3:
        displayCart()

    elif menu == 4:
        pass

    elif menu == 5:
        print("Thank you for shopping!")
        break

任何其他代码提示也将不胜感激!我的目标是无论有多少物品添加到购物车中,都能够计算成本,并且不确定如何跟踪它。

标签: pythoncalculation

解决方案


您没有任何类型的数据结构(复制+粘贴字符串除外)中每本书的信息这一事实使得很难跟踪价格。解释将事物存储在有用数据结构中的概念的最简单方法是通过示例,因此我快速“修复”此代码以将每本书存储为NamedTuple

from typing import NamedTuple


class Book(NamedTuple):
    item_number: int
    title: str
    author: str
    genre: str
    price: float

    def __str__(self):
        return f"""Item Number: {self.item_number}
Title: {self.title}
Author: {self.author}
Genre: {self.genre}
Price: ${self.price}
"""


all_books = [
    Book(1000, "Science: A Visual Encyclopedia", 
         "Chris Woodford", "Science", 23.99),
    Book(1001, "My First Human Body Book",
         "Patricia J. Wynne and Donald M. Silver", "Science", 3.99),
    Book(1002, "The Runaway Children",
         "Sandy Taylor", "Fiction", 3.99),
    Book(1003, "The Tuscan Child",
         "Rhys Bowen", "Fiction", 9.99),
    Book(1004, "Learning Python",
         "Mark Lutz", "Programming", 61.99),
]
books_by_item_no = {book.item_number: book for book in all_books}


def showOptions():
    print("==============================\n".join(
        str(b) for b in all_books
    ))


def displayCart():
    shopping_list = open('bookcart.txt')
    contents = shopping_list.read()
    print('Here is your cart:')
    print(contents)
    print()
    shopping_list.close()


def addItem() -> float:
    """Returns the price of the item added, or 0 if no item."""
    shopping = open('bookcart.txt', 'a')
    whichbook = input("Please input the item number")
    try:
        book = books_by_item_no[int(whichbook)]
        shopping.write(str(book))  
        # XXX: rather than writing the entire description 
        # into your file, you probably want to just write 
        # the item number!
        shopping.close()
        print('Item has been added\n')
        return book.price
    except (KeyError, ValueError):
        print("Did not understand.")
        return 0


def checkItem(item):
    shopping_list = open('bookcart.txt')
    contents = shopping_list.readlines()
    shopping_list.close()
    item = item + '\n'
    return item in contents


total = 0
while True:
    menu = int(input('''1. Display Books
2. Add item to cart
3. Show Cart
4. Checkout
5. Quit
Select an option:
'''))
    print()
    if menu == 1:
        showOptions()
    elif menu == 2:
        total += addItem()
    elif menu == 3:
        displayCart()
    elif menu == 4:
        pass
    elif menu == 5:
        print("Thank you for shopping!")
        print(f"Your total: {total}")
        break

特别注意showOptions现在是如何迭代的几行代码all_books,以及如何addItem简单地使用输入的项目编号来查找书籍books_by_item_no;这两个函数都不需要复制和粘贴每本书的完整描述,因为Book.__str__知道如何生成它。

跟踪总数是通过addItemreturn的微小变化来完成的book.price,并且让主while循环将该值添加到 a total


推荐阅读