Python - 根据整个代码中的用户输入分配和计算最终成本?

Python - Assign and Calculate a final cost based on user input throughout code?

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

def showOptions():
    print('''Item Number: 1000
Title: Science: A Visual Encyclopedia
Author: Chris Woodford
Genre: Science
Price: .99
==============================
Item Number: 1001
Title: My First Human Body Book
Author: Patricia J. Wynne and Donald M. Silver
Genre: Science
Price: .99
==============================
Item Number: 1002
Title: The Runaway Children
Author: Sandy Taylor
Genre: Fiction
Price: .99
==============================
Item Number: 1003
Title: The Tuscan Child
Author: Rhys Bowen
Genre: Fiction
Price: .99
==============================
Item Number: 1004
Title: Learning Python
Author: Mark Lutz
Genre: Programming
Price: .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: .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: .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: .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: .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: .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

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

事实上,您没有任何类型的数据结构(复制+粘贴字符串除外)中每本书的信息,因此很难跟踪价格。解释在有用的数据结构中存储事物的概念的最简单方法是通过示例,所以我快速“修复”这段代码以将每本书存储为 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_booksaddItem如何简单地使用输入的条目号来查找这本书在 books_by_item_no 中;这两个函数都不需要复制和粘贴每本书的完整描述,因为 Book.__str__ 知道如何生成它。

跟踪总数是通过 addItem return book.price 和主 while 循环将该值添加到 total.