Validated user input (ensure correct/expected data entry)

MOST OF THE TIMES THAT YOU CREATE A PROGRAM YOU EXPECT IT TO INTERACT WITH THE USER, AND BY DOING SO THEY MAY BE DOING THINGS THAT THEY AREN’T SUPPOSED TO, LIKE WRITING WORD WHERE THEY SHOULD WRITE NUMBERS OR USE SPECIAL CHARACTERS IN STRINGS, IN THIS CASES THE COMPUTER WILL DROP AN ERROR AND WILL STOP THE PROGRAM BUT HOW TO PREVENT IT FROM STOPING AND JUST LET THE USER KNOW HE IS DOING SOMETHING WRONG? THAT IS EXACTLY WHAT THIS TOPIC IS ABOUT.

As in many things in programing how you do it depends on the programer and there are plenty of ways to do so, so I will be explaining just the basic concept and to do so I will use an example.

def get_int(prompt):
    try:
        value = int(input(prompt))
    except ValueError:
        print("Sorry, I didn't understand that.")
        return get_int(prompt)

    if value < 0:
        print("Sorry, your response must not be negative.")
        return get_int(prompt)
    else:
        return value

Deja un comentario