Siim Salmi
Siim Salmi

Reputation: 41

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

Upvotes: 3

Views: 25077

Answers (3)

scharette
scharette

Reputation: 9977

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

Upvotes: 3

Aaditya Ura
Aaditya Ura

Reputation: 12669

An updated version of your code :

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

output:

I'm going to find the arithmetical mean! 

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

Pythonic way:

You can find mean by:

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

output:

I'm going to find the arithmetical mean! 

9 9 9 9 9
9.0

Upvotes: 0

user1781434
user1781434

Reputation:

You're trying to convert a string to a float but it is an invalid string if you are using the string for that purpose. I would just continue asking until the user gives the right input, like this:

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

Then, instead of input, use float_input in your code.

Upvotes: 0

Related Questions