将空字符串输入转换为float

时间:2017-12-12 19:36:36

标签: python python-3.x

我创建了这样的代码来查找用户输入的数字的算术平均值,但由于某种原因,程序最终无法将字符串转换为浮点数。我应该改变什么?

print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
negative = "-"
while True:
    x = input(f"Type in {jnr}. nr. (To end press Enter): ")
    if negative not in x:
        jnr += 1
    elif negative in x:
        pass
    elif x == "": break
    sum = sum + float(x)

print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))

我得到了他的错误:

  

Traceback(最近一次调用最后一次):文件   “C:\ Users \ siims \ Desktop \Koolitööd\ individuaalne proge.py”,第11行,in    sum = sum + float(x)ValueError:无法将字符串转换为   浮

3 个答案:

答案 0 :(得分:2)

正如我在评论中所说,错误来自于当用户使用float(x)时调用Enter导致错误的事实。修改代码而不更改所有内容的最简单方法是首先检查输入是否为""。这样你就不会尝试将空字符串转换为float。

print("I'm going to find the arithmetical mean! \n")
jnr = 0; 
sum = 0
negative = "-"
while True:
    x = input(f"Type in {jnr}. nr. (To end press Enter): ")

    if x == "":
        break
    elif negative not in x:
        jnr += 1
        sum = sum + float(x)


print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))

答案 1 :(得分:0)

您正在尝试将字符串转换为float,但如果您为此目的使用字符串,则它是无效字符串。我会继续询问,直到用户输入正确的输入,如下所示:

def float_input(s):
    while True:
        try:
            x = input(s)
        except ValueError:
            print('Invalid input. Try again.')
        else:
            break
    return x

然后,代替input,在代码中使用float_input

答案 2 :(得分:0)

您的代码的更新版本:

print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
while True:
    x = int(input())
    if x>1:
        jnr += 1
    elif x<1:
        pass

    if x == 0:
        break
    sum += float(x)
    print(sum)



print("Aritmethmetical mean for these numbers is: {}".format(sum/jnr))

输出:

I'm going to find the arithmetical mean! 

9
9
9
9
9
0
Aritmethmetical mean for these numbers is: 9.0

Pythonic方式:

您可以通过以下方式找到意思:

print("I'm going to find the arithmetical mean! \n")
inp=[int(i) for i in input().split()]
print(sum(inp)/len(inp))

输出:

I'm going to find the arithmetical mean! 

9 9 9 9 9
9.0