Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an empty string input to float

I made a code like this to find the arithmetical mean for numbers the user has typed in but for some reason the program couldn't convert string to float in the end. What should I change?

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)))

I got his Error :

Traceback (most recent call last): File "C:\Users\siims\Desktop\Koolitööd\individuaalne proge.py", line 11, in sum = sum + float(x) ValueError: could not convert string to float

like image 482
Siim Salmi Avatar asked Mar 26 '26 21:03

Siim Salmi


1 Answers

As I said in my comment the error comes from the fact that calling float(x) when the user uses Enter result in the error. The easiest way to fix your code without changing everything is by checking first if the input is "". That way you will not be trying to convert an empty string to 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)))
like image 107
scharette Avatar answered Mar 29 '26 09:03

scharette