Skip to content Skip to sidebar Skip to footer

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 c

Solution 1:

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

Solution 2:

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.


Solution 3:

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

Post a Comment for "Converting An Empty String Input To Float"