當我運行程式時,它一直彈出。無法將字串轉換為浮點數。我試圖查找它,但我找不到任何東西。
這是代碼:
f = open("ticket.txt",'r')
s=f.read()
lines=s.split("\n")
priceMax=0
priceMin=9999
total=0
for line in lines:
cols=line.split(" ")
price=(float)(cols[1])
total=total price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
f.close()
f=open("output.txt",'w')
f.write("*******************************************\n")
f.write(" TICKET REPORT\n")
f.write("*******************************************\n\n")
f.write("There are " str(len(lines)) " tickets in the database.\n\n")
f.write("Maximum Ticket price is $" str(priceMax) "\n")
f.write("Minimum Ticket price is $" str(priceMin) "\n")
f.write("Average Ticket price is $" str(total / len(lines)) "\n\n")
f.write("Thank you for using our ticket system!\n\n")
f.write("*******************************************\n")
f.close()
print("File Created sucessfully")
uj5u.com熱心網友回復:
是的,縮進在 Python 中很重要。你必須保持一致。
這個“強制轉換”(float)基本上是對float()函式求值,然后你呼叫它,所以這不是問題。更規范的是f = float("123.45"). 現在,ValueError如果傳遞了無效數字,這將引發例外,因此,您可能想要捕獲它,以便找出問題所在。沿著以下路線:
s = "123.baboom"
try:
f = float(s)
except ValueError as e:
print("Oh, no, got an exception:", e)
print("The offending string was: ", s)
uj5u.com熱心網友回復:
顯示的錯誤是什么?
我認為問題在于您已使用cols[1]而不是cols[0].
這里的縮進也是錯誤的。
for line in lines:
cols=line.split(" ")
price=(float)(cols[0])
total=total price
if(price>priceMax):
priceMax=price
if(price<priceMin):
priceMin=price
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/349005.html
標籤:Python
