首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试让您可以从列表中选择书籍,然后在最后使用python给出详细的收据

尝试让您可以从列表中选择书籍,然后在最后使用python给出详细的收据
EN

Stack Overflow用户
提问于 2018-12-11 22:02:09
回答 1查看 75关注 0票数 -1

使用python,我试图让它显示在文本文件中的书,用户可以选择一本书和一个数量,并在循环中执行此操作。当他们这样做的时候,它应该将它作为收据保存到文本文件中,并在用户完成选择时打印出来。这就是我到目前为止所能做到的。

代码语言:javascript
复制
cusName = input("What is your name?")

def main():
    def menu():
       print("Here is a list of items that we have:")

books_file= open("Books.txt","r")
lines = books_file.readlines()

aryBooks = []

for line in lines:
    print(line)

bookChoice = input("Which book would you like?")

bookQty = input("You chose",  bookChoice , "How many would you like?")

print ("Qty:", bookQty)
print ("Item:", bookChoice)

price = print ("Price:", book[2])
print ("SubTotal:", price * bookQty)

repeat = input("Would you like another item? Y or N")

 receipt_file= open("receipt.txt","w")
 lines = receipt_file.writelines()


for i in range(0,len(aryBooks)):
    print(i + 1, aryBooks[i])
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-11 23:51:39

尝试下面的代码:

代码语言:javascript
复制
def menu():
    # Main loop for shopping
    cart = {}

    # Read books here
    books = read_books()

    while True:
        # Loop until user does not want to shop any longer
        print("Here is a list of items that we have:\n")

        for book_num, (book_name, book_price) in books.items():
            print(f'#{book_num}: {book_name} -- ${book_price}')

        bookChoice = input("Which book would you like? (Please enter a number)\n")

        # Make sure user enters the right number
        try:
            price = books[bookChoice][1]
        except:
            print('Sorry you chose the wrong number')
            print()
            continue

        bookQty = int(input(f"You chose {books[bookChoice][0]}. How many would you like?\n"))

        subtotal = price * bookQty
        cart[books[bookChoice][0]] = (bookQty, subtotal)

        print (f"Qty: {bookQty}")
        print (f"Item: {books[bookChoice][0]}")
        print (f"Price: {price}")
        print (f"SubTotal: {subtotal}")

        repeat = input("Would you like another item? Y or N\n")

        # End loop if answer was No
        if repeat.lower() == 'n' or repeat.lower == "no":
            print(f'Your total was: {sum([y for x, y in cart.values()])}')
            generate_receipt('receipt.txt', books, cart)
            print('Have a good day!\n')
            break
        else:
            print('Here is what you have thus far:')
            for name, (qty, sub) in cart.items():
                print(f'Name: {name} ; Qty: {qty} ; Subtotal: {sub}')
            print()

def generate_receipt(path_to_receipt, books, cart):
    # Generate receipt based on shopping cart
    with open(path_to_receipt, 'a') as receipt_file:
        for name, (qty, subtotal) in cart.items():
            receipt_file.write(f'Qty: {qty} ; Item: {name}; Total: {sum([y for x, y in cart.values()])}; Subtotal: {subtotal}\n')

def main():
    # Main loop that starts the shopping
    cusName = input("What is your name?\n")

    print(f'Hi {cusName}. Welcome to the bookstore!')
    menu()

def read_books(path_to_books="Books.txt"):
    # Read in the books from the file
    with open(path_to_books, 'r') as f:
        books = f.readlines()
        books = [book.strip().split(',') for book in books]
        books = {book_num: (book_name, int(book_price)) for book_num, book_name, book_price in books}

    return books

if __name__ == '__main__':
    main()

输出文件可能不是您想要的,但这可以很容易地修复。

我的Books.txt如下:

代码语言:javascript
复制
 15,Harry Potter,20
 2,LOTR,25
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53725753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档