Anonymous
Anonymous

Reputation: 19

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

I'm currently trying to create a shopping program where people can "purchase" books. The problem is I have to calculate the final cost of the purchase, which I am stuck on. Do I create variables for each item and assign the price? Thank you for the help! My current code is below.

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

Any other code tips will also be greatly appreciated! I am aiming to be able to calculate the cost no matter how many items are added to the cart and am unsure of how to keep track of that.

Upvotes: 0

Views: 982

Answers (1)

Samwise
Samwise

Reputation: 71454

The fact that you don't have the information for each book in any kind of data structure (other than copy+pasted strings) makes it hard to track prices. The easiest way to explain the concept of storing things in a useful data structure is by example, so I took a quick whack at "fixing" this code to store each book as a 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

Pay special attention to how showOptions now is just a few lines of code that iterate over all_books, and how addItem simply uses the inputted item number to look up the book in books_by_item_no; neither function needs to copy and paste the entire description of each book, because Book.__str__ knows how to generate it.

Tracking the total is accomplished by the small change of having addItem return book.price, and having the main while loop add that value to a total.

Upvotes: 1

Related Questions