简体   繁体   中英

How to find error in code while user input validation in python?

I just started to dig myself into python. As always when try to learn a new language, I start with a little game. But this time, I can't see what is gone wrong. The game is simple. Guess a number between 1 and 100. But before I come to the actual game logic, I want to make sure that the user guessed a number. (instead of an float or string). And the number must be in range between 1 and 100.

For some reason, my approach always tells me that my number is not in the range. And I can't figure out why. So any help is appreciated. Thank you.

from random import randint as rInt

game = {"winNumber": rInt(1,100), "guessedNumber": 0, "tries": 8, "triesLeft": 8}

def checkInput(uInput):
    """Checks user Inputs if they are valid numbers. Then a second check if the number is in between 1 and 100. Returns TRUE if successfull"""
    try:
        int(uInput)
    except ValueError:
        print("This is not a number!")
    else:
        if uInput not in range(1, 100):
            print("With this number you will definitly loose the game, because it is not between 1 and 100")
        else:
            game["guessedNumber"] = uInput
            return True


while game["triesLeft"] > 0:
    riskyInput = input("Please enter a number between 1 and 100: ")
    if checkInput(riskyInput) == True:
        print (f'The Validator worked. The Player guessed number is: {game["guessedNumber"]}')
    else:
        print ("Something has gone wrong with the validation. We try again")
        continue

The try block converts uInput to int but throws it away. In the else block uInput is still a string.

int(uInput) should be uInput = int(uInput)

uInput is still a string when you check if it's in the range.

Just convert it to int: if int(uInput) not in range(1, 100):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM