2

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()
2
  • 1
    What do you mean by invalid input ? Commented Mar 9, 2021 at 15:07
  • 1
    @MarioKhoury That (like happens in the list of my script) the input should be an integer, but if the user inputs a string, that's the invalid input. The console returns that error. Commented Mar 9, 2021 at 15:20

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

That didn't work. I edited the question and added part of the code in my script. Maybe that helps.
@Manu1Volta First of all, I would suggest reducing the amount of code in the try clause. With essentially the entire code snippet inside the try clause, it is extremely difficult to pinpoint exactly where the ValueError would be raised. Second of all, what do you mean by "That didn't work"? Unless you give an expected output, I cannot write code which "works".
Yes, you are totally right... I'm just starting, so thank you! The expected output would be that the invalid input is stored in the list guessedNumbers, so that when I print the output with all the numbers inputted and a detail about each one, for the ones that are invalid, print that "Definitely is not [input text]". Following the code might be easier to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.