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


run_timing()

Could you tell me why i am getting Value Error.

Regards,
Suresh

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':
        try:
            run_time = input("Enter 10k run time (type 'Done' to exit): ")
            total_time += float(run_time)
            total_runs += 1
        except:
            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

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.