Store invalid input in a Python list

Viewed 270

I know I can handle invalid inputs using the try: except ValueError:, but how can I store that input in a list or variable or whatever?

I want that when the user inputs text, the code tells "It is definitely not [text]" in some part of the code (as it is seen in the code below). But it is not working the way it is.

while True:
        try:
            while guessedNumber != realNumber:
                tries = tries + 1
                checkTries()
                guessedNumbers.append(guessedNumber)
                os.system("clear")
                print(pyfiglet.figlet_format("Try again!", font = "big"))
                print("The number is:")
                for x in guessedNumbers:
                    if x < realNumber:
                        print("Higher than " + str(x))
                    elif x > realNumber:
                        print("Lower than " + str(x))
                    elif type(guessedNumber) is not int:
                        print("Definitely not " + str(x)) # to solve this, maybe use another Try: except:.
                guessedNumber = int(input("The number is... "))
            if tries == 1:
                os.system("clear")
                print(pyfiglet.figlet_format("You won!", font = "big"))
                print("You got it in the first try! What a lucky person!")
            else:
                os.system("clear")
                print(pyfiglet.figlet_format("You won!", font = "big"))
                print("Way to go! You got it in " + str(tries) + " tries!")
                break
        except ValueError:
            guessedNumbers.append(guessedNumber)
    playAgain()
1 Answers

Whether the user input comes as command lines arguments, passed function/method values, or input returned by the input() function, you can just create a list and add the invalid input inside the except clause.

Command Line Arguments

try:
    ...
except ValueError:
    invalid_input.append(sys.argv)

Function Calls

def my_func(argument):
    try:
        ...
    except ValueError:
        invalid_input.append(argument)

Input() Function

user_input = input()
try:
    ...
except ValueError:
    invalid_input.append(user_input)

Note the scope which you define invalid_input in would be up to your choosing.

Edit 1

Since the variable in question is only 'valid' if it is an integer, then checking for that property is the only statement needed in the try clause.

guesses = []
while True:
    guess = input("Guess a number")
    try:
        guess = int(guess)
    except ValueError:
        print(f"Definitely not {guess}")
        guesses.append(guess)
        continue
Related