首页 > 解决方案 > ValueError:无法将字符串转换为浮点数:'F' python

问题描述

我正在尝试编写一个小的 python 代码来打印出用户提供的数据总和。更具体地说,当事先不知道数据数量时,我需要代码能够计算它。为了实现这一点,我需要代码来识别用户没有指示列表的大小,并通过键入“F”来知道要包含的最后一个条目是什么。我的代码遇到的问题(见下文)是,当我使用“F”而不是“-1”时,代码崩溃并显示以下消息“ValueError:无法将字符串转换为浮点数:'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)

标签: python

解决方案


我将只解决代码中存在问题的部分,即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)

推荐阅读