【问题标题】:Python - Assign and Calculate a final cost based on user input throughout code?Python - 根据整个代码中的用户输入分配和计算最终成本?
【发布时间】:2021-07-26 15:16:37
【问题描述】:

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

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

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

【问题讨论】:

  • 我建议使用 SQLite 表而不是纯文本文件来存储“购物车”。那么代价就是一个简单的SUM()函数
  • 我将如何使用这张桌子?我从来没有听说过它,它似乎更容易使用。
  • 如果我正确理解您的问题,您可以在开头声明一个变量来存储总数并将其设置为 0。并且每次在 @ 中的一个 if 块中添加一个特定价格到该变量987654324@函数执行
  • 谢谢!我只是快速浏览了网页并想问,我将如何实现每个项目的信息?还是我只是指定价格并打印其余部分?

标签: python calculation


【解决方案1】:

在任何类型的数据结构(除了复制+粘贴的字符串)中,您都没有每本书的信息,这一事实使得跟踪价格变得很困难。解释将事物存储在有用数据结构中的概念的最简单方法是通过示例,因此我快速“修复”此代码以将每本书存储为 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__ 知道如何生成它。

通过让addItem 返回book.price 并让while 主循环将该值添加到total 的微小变化来跟踪总数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-04
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多