簡體   English   中英

無法將字符串轉換為 int 或 float

[英]Can't convert strings to int or float

所以我能夠在你們的幫助下解決第一個問題,但是現在程序運行沒有任何錯誤,它沒有正確計算平均值,我不知道為什么。 這是它的樣子:

def calcAverage():
with open('numbers.dat', 'r') as numbers_file:
    numbers = 0
    amount = 0

    for line in numbers_file:
        amount = amount + float(line)
        numbers += 1


average = amount / numbers
print("The average of the numbers in the file is:",average)

檢查while中的line是否為空后,您正在重新分配line while測試正在測試文件中的前一行。

所以當你讀到最后時,你讀到一個空行並嘗試將它添加到amount ,但得到一個錯誤。

您也永遠不會添加第一行,因為您在循環之前閱讀了它並且永遠不會將其添加到amount

使用for循環而不是while ,它會在到達結束時自動停止。

def calcAverage():
    with open('numbers.dat', 'r') as numbers_file:
        numbers = 0
        amount = 0
    
        for line in numbers_file:
            amount = amount + float(line)
            numbers += 1
    
    average = amount / numbers
    print("The average of the numbers in the file is:",average)

如果您確實想使用while循環,請這樣做:

while True:
    line = numbers_file.readline()
    if not line:
        break

    # rest of loop

錯誤顯示您在line有空字符串。

你可以用float('')得到同樣的錯誤

您以錯誤的順序運行代碼 - 在轉換前一行之前讀取新行。
你應該剝離線,因為它仍然有\\n

你需要

line = numbers_file.readline()
line = line.strip()  # remove `\n` (and `\t` and spaces)

while line != '':

    # convert current line
    amount = amount + float(line)  

    numbers += 1

    # read next line
    line = numbers_file.readline()
    line = line.strip()  # remove `\n` (and `\t` and spaces)

您也可以為此使用for -loop

numbers = []

for line in numbers_file:
    line = line.strip()  # remove `\n` (and `\t` and spaces)
    if line:
       numbers.append( float(line) )
    #else:
    #   break

average = sum(numbers) / len(numbers)

這可以減少到

numbers = [float(line) for line in numbers_file if line.strip() != '']

average = sum(numbers) / len(numbers)

其他答案說明了如何逐行讀取文件。 其中一些處理諸如到達文件結尾 (EOF) 和用於轉換為浮點數的無效輸入等問題。

由於任何 I/O 和 UI 都可能會提供無效輸入,因此我想在按預期處理輸入之前強調驗證。

驗證

對於從輸入控制台或類似文件讀取的每一行,您應該考慮進行驗證。

  • 如果字符串為會發生什么? 將空字符串輸入轉換為浮點數
  • 如果字符串包含特殊字符會發生什么? 喜歡Mat 的評論
  • 如果數字不符合您的預期float怎樣? (取值范圍,小數精度)
  • 如果沒有讀取或到達文件尾會發生什么 (空文件或 EOF)

建議:為了使其健壯,預期輸入錯誤並捕獲它們。

(a) 在 Python 中使用try-except構造進行錯誤處理:

for line in numbers_file:
    try:
        amount = amount + float(line)
        numbers += 1
    except ValueError:
        print "Read line was not a float, but: '{}'".format(line)

(b) 提前測試輸入:以更簡單的方式,您還可以使用基本的if語句手動測試,例如:

if line == "":  # on empty string received
    print("WARNING: read an empty line! This won't be used for calculating average.")  # show problem and consequences
    continue  # stop here and continue with next for-iteration (jump to next line)

暫無
暫無

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

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