I have written some code but gives me Value Error

Hi Team,

I wanted to take inputs from the user in both ‘int’ and ‘float’ and then calculate the average of no. of inputs.

"""This is a function to take inputs as 'Times' from user and calculate the average of the 10k run"""

def run_timing():
    run_time = float(input('Enter 10 KM run time:'))
    no_of_runs = 0
    total_time = 0.0
    while run_time:
        total_time += run_time
        no_of_runs += 1
        run_time = float(input('Enter 10KM run time:'))
    print(f'Average Run time is {total_time / no_of_runs}, over {no_of_runs} runs')


Could you tell me why i am getting Value Error.


What exactly error says?

ValueError: could not convert string to float:

Error didn’t include which string cannot be converted?

Your run_time = float(input(‘Enter 10 KM run time:’)) is going to throw a ValueError is you put anything other than an integer or float into it. So if you put a letter in there, you will get a ValueError because the float function cannot convert a letter into a float. Similarly, if a user just hits enter without putting anything in, you will have an empty string that the float function will try to convert to a float, but will be unable to since it cannot convert an empty string into a float value. Since the float function cannot convert an empty string into a float, you will get a ValueError.

You probably need to use a try-except block in the while loop to handle any errors. And then move the float function off the input and put it on the total_time update, like this total_time = float(run_time). And I might consider using a more explicit end condition for your while loop. Something like:

def run_timing():
    run_time = 0.0
    total_runs = 0
    total_time = 0.0

    while run_time != 'Done':
            run_time = input("Enter 10k run time (type 'Done' to exit): ")
            total_time += float(run_time)
            total_runs += 1
            print("Please enter a number or type 'Done' to exit")
    print(f'Average runtime is {total_time / total_runs} over {total_runs} runs.')

I hope that helps.

Super, thank you very much

If you do not enter anything and just hit Enter, then the input is just an empty string. You can not convert an empty string to a number which is why you get this error.

It would be the same as you writing run_time = float('')