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
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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With