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 = "-"whileTrue:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if x == "":
breakelif negative notin x:
jnr += 1sum = 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:
deffloat_input(s):
whileTrue:
try:
x = input(s)
except ValueError:
print('Invalid input. Try again.')
else:
breakreturn 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 = 0whileTrue:
x = int(input())
if x>1:
jnr += 1elif x<1:
passif x == 0:
breaksum += float(x)
print(sum)
print("Aritmethmetical mean for these numbers is: {}".format(sum/jnr))
output:
I'm going to find the arithmetical mean! 999990
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 ininput().split()]
print(sum(inp)/len(inp))
output:
I'm going to find the arithmetical mean! 999999.0
Post a Comment for "Converting An Empty String Input To Float"