簡體   English   中英

ValueError:無法將字符串轉換為浮點數:'F' python

[英]ValueError: could not convert string to float: 'F' python

我正在嘗試編寫一個小的 python 代碼來打印出用戶提供的數據總和。 更具體地說,當數據數量未知時,我需要代碼能夠計算它。 為了實現這一點,我需要代碼來識別用戶沒有指明列表的大小,並通過鍵入“F”知道要包含的最后一個條目是什么。 我在代碼中遇到的問題(見下文)是,當我使用“F”而不是“-1”時,代碼崩潰並顯示以下消息“ValueError: could not convert string to float: 'F' python”。 任何人都可以幫助我了解我做錯了什么,以便我可以解決它。

numberList = []
count = int(input("Enter the list size :"))
stopList = False
F = -1
mysum = 0
num = 0
if count >= 0:
    for i in range(0, count):
        item = int(input("Enter number :"))
        numberList.append(item)
        mysum = sum(numberList)
print("The sum is", mysum)
if count < 0:
    while stopList is False:
        nextnum = float(input("Enter number :"))
        if nextnum == F:
            stopList = True
        if stopList is False:
            num += 1
            mysum += nextnum
    print("The sum is", mysum)

我將只解決您代碼中存在問題的部分,即if count < 0:之后的所有內容。

您應該首先按原樣獲取輸入並檢查它是否為'F' ,然后僅在必要時將 if 轉換為浮點數:

while stopList is False:
    nextnum = input("Enter number :")
    if nextnum == 'F':
        stopList = True
    if stopList is False:
        num += 1
        mysum += float(nextnum)
print("The sum is", mysum)

作為旁注,不要在循環中使用這樣的條件,我會這樣使用它:

while True:
    nextnum = input("Enter number :")
    if nextnum == 'F':
        break

    num += 1
    mysum += float(nextnum)

print("The sum is", mysum)

暫無
暫無

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

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