所以,我的代码适用于想要从图书馆或某处借书的用户。他们输入了他们想要借书的书的代码,我在文本文件中有指定名称,价格等的代码。他们输入他们想贷款的书的数量,然后计算价格。如果他们想借更多书籍,代码会循环回来,他们可以重复这个过程。我想创建一个单独的收据文件,它存储用户在此收据文件中的循环内输入的所有内容,然后将所有内容添加到一起。我读了一些东西并尝试了这个,但是有一个错误,我不知道我做错了什么。这是我的代码:
task=input("Enter 'b' to borrow a book, press 'x' to exit. \n")
if task.lower()== "b":
myfile=open("books.txt", "r+")
details=myfile.readlines()
while True:
book=input("Enter the 8 digit book code. \n")
while len(book) !=8
print("Your code is not 8 digits long, please try again.\n")
f = open("books.txt", "r+")
for line in f.readlines():
quantity=input("How many copies of the book do you wish to purchase?\n")
t = line.split(" ")
price = float(t[3])
code = t[1]
NameOfBook = t[2]
total=(price)* int(quantity)
with open("receipt.txt", "w") as receiptFile:
receiptFile.write(str(code))
receiptFile.write(float(NameOfItem))
receiptFile.write(int(quantity))
receiptFile.write(str(price))
receiptFile.write(str(total))
break
answer = input("Do you want to loan another book? Enter 'yes' if you would like to. ")
if answer == "yes":
continue
else:
break
我试图进入的是:
with open("receipt.txt", "w") as receiptFile:
receiptFile.write(str(code))
receiptFile.write(float(NameOfBook))
receiptFile.write(int(quantity))
receiptFile.write(str(price))
receiptFile.write(str(total))
我认为它会打开我命名为receipt.txt的文件然后写入用户输入的每个东西,但是我没有成功。这反过来了:
Traceback (most recent call last):
File "F:\PYTHOn\New python edited for loop.py", line 19, in <module>
receiptFile.write(float(NameOfBook))
ValueError: could not convert string to float: 'Narnia,'
请尽可能帮助。谢谢:))