Home > Software engineering >  Python input validation: is there a way to ensure the user only inputs numbers (i.e. floats) that ar
Python input validation: is there a way to ensure the user only inputs numbers (i.e. floats) that ar

Time:10-07

Beginner here, looking for info on input validation.

I need the user to input a set of times that is occurring "during a race" (i.e. we assume that as the user keeps inputting times, the values keep getting bigger and bigger) which will then be stored into a list.

For example: times = [3.2, 3.45, 3.98, 4.32] and so on.

I need to make a way to error-proof this so it tells the user that it had made an "invalid input" by putting down a time that is lower than the previous time user had inputted.

Here is how my code looks thus far which isn't "error-proofed":

cont = "Y"
runners = []
times = []
while(cont != "N"):
    if cont == "Y":
        #get the name and time of the next runner
        runner_name = input("Please enter name of next runner: ")
        runner_time = float(input("Please enter runner time: "))
        #add the name and time to their respective lists
        runners.append(runner_name)
        times.append(runner_time)
        cont = input("Any more runners to add? (Y/N) ")
        #ask if the user is done
    if cont != "Y":
        if cont == "N":
            break        
        print("Invalid input. Please try again...")
        cont = input("Any more runners to add? (Y/N) ")

CodePudding user response:

times[-1] will retrieve the last runner's time. You can compare that to the next input time and throw an error if it breaks your condition. You'll need to create a special case for the first runner, as they do not have a previous runner to compare to so you can't access times[-1].

CodePudding user response:

...
runner_name = input("Please enter name of next runner: ")
while True:
    runner_time = float(input("Please enter runner time: "))
    if len(times) == 0 or runner_time > times[-1]:
        break
    else:
        print("New time must be greater than last!")
...

This will do the job. The while loop will ask for a valid number over and over again, and since your values in times are increasing, you can compare to the last added element which is given by times[-1]. Note that len(times) deals with the special case of the first runner, where your times list is empty.

  • Related