[英]Python/Sklearn - Value Error: could not convert string to float
[英]Value error: could not convert str to float PYTHON
這是我的代碼。 我不明白為什么我得到這個錯誤以及如何糾正它。 錯誤顯示在: totals = entrant + float(tot)
這是我的完整代碼:
def total():
File = open("argent.txt","r")
File = File.read()
tot = File
print("You have",tot,"£ in your account")
def add():
entrant = float(input("How many do you want to add to your account? "))
with open("argent.txt", 'r') as f:
tot = f.read().rstrip('\n')
print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)
with open("argent.txt", 'w') as f:
output = str(totals)
f.write(output)
add()
提前致謝。
在您的情況下,函數read()
不僅讀取字符20
,還讀取附加到其上的新行字符。
因此變量tot
包含不可轉換為數字的值。
嘗試
tot = tot.strip()
在使用它之前。
將來,請嘗試避免將File
用於file type
變量。
entrant = float(input("How many do you want to add to your account? "))
with open("argent.txt", 'r') as f:
tot = f.read().rstrip('\n')
print("You have ",tot,"£ in your account")
totals = entrant + float(tot)
print(totals)
with open("argent.txt", 'w') as f:
output = str(totals)
f.write(output)
通過使用with open
文件,在以下代碼后關閉。
編輯:修正了'w'
從文件輸出float
到str
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.