使用python,我试图让它显示在文本文件中的书,用户可以选择一本书和一个数量,并在循环中执行此操作。当他们这样做的时候,它应该将它作为收据保存到文本文件中,并在用户完成选择时打印出来。这就是我到目前为止所能做到的。
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])
发布于 2018-12-11 23:51:39
尝试下面的代码:
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
如下:
15,Harry Potter,20
2,LOTR,25
https://stackoverflow.com/questions/53725753
复制相似问题