簡體   English   中英

值錯誤:無法將str轉換為浮點PYTHON

[英]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'從文件輸出floatstr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM