-1

I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.

I have tried to use just 'int' in an if statement to address all integers, but that is not working. I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.

import random
play = True

while play:
    count = 1

    hidden = random.randrange(1,5)


    guess = int(input("Guess a number between 1 and 5:"))

    if guess != int
        guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))


    while guess != hidden:
        count+=1
        if guess > hidden + 10:
            print("your guess is to high!")
        elif guess < hidden -10:
            print("your too low!")
        elif guess > hidden:
            print("your really warm, but still to high!")
        elif guess < hidden:
            print("your really warm, but still to low")

        print("You have guessed incorrectly, Try again!. \n")
        #reset the guess variable and make another guess
        guess = int(input("Guess a number between 1 and 5:"))

    print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")

    count = 1


    playagain = str(input("Do you want to play again?\nType yes or no: "))
    if playagain == "no" or "n" or "N" or "no thank you":
        play = False

    elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
        play = True

    else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
    playagain = str(input("Invalid Entry. Please Type yes or no: "))

This is the error that I'm getting. There may be some other mistakes in my code as well.

File "comrandomguess.py", line 18
    if guess != int
                  ^
SyntaxError: invalid syntax
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
YHapticY
  • 177
  • 11
  • 1
    Possible duplicate of [How do I parse a string to a float or int in Python?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int-in-python) – Devesh Kumar Singh May 25 '19 at 05:13
  • You forgot to add colon `:` after if condition, therefore a syntax error arises – Vasu Deo.S May 25 '19 at 05:18
  • alright, I fixed the missing `:` after the `if` statement. Now I'm getting an the message ``` Invalid Entry. Please enter an Integer between 1 and 5: ``` even after entering any number at all. – YHapticY May 25 '19 at 05:20
  • Possible duplicate of [How do you set a conditional in python based on datatypes?](https://stackoverflow.com/questions/14113187/how-do-you-set-a-conditional-in-python-based-on-datatypes) – MisterMiyagi May 25 '19 at 06:46
  • You would be better off using the routine `sanitised_input` given [in this answer](https://stackoverflow.com/a/23294659/6246044). In particular, call `sanitised_input('Guess a number between 1 and 5:', type_=int, min_=1, max_=5)`. Or perhaps `sanitised_input('Guess a number between 1 and 5:', range_=[1,2,3,4,5])`. – Rory Daulton May 25 '19 at 20:01

4 Answers4

2

If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):

def testForInt(s):
    if s:
        try:
            _ = s.encode('ascii')
        except UnicodeEncodeError:
            return False
        test = ''.join([x for x in s if x.isdigit()])
        return (test == s)
    else:
        return False

If you want to sandbox the user entirely, wrap it in a loop like this:

acceptable = False
while not acceptable:
    entry = input("Enter an int: ")
    if testForInt(entry):
        entry = int(entry)
        acceptable = True
    else:
        print("Invalid Entry")

If you want a simpler version with no function call(see Jack Taylor comment), this works too:

acceptable = False
while not acceptable:
    entry = input("Enter an int: ")
    try:
        entry = int(entry)
        acceptable = True
    except ValueError as e:
        print(f"Failed due to {str(e)}")

Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11
  • This approach suffers the same drawback as @Deepankar's. If you input a string like "①", then it will pass the testForInt function, but the program will raise an exception when you actually try to convert it to an int. – Jack Taylor May 25 '19 at 13:41
  • @JackTaylor thanks, I tried a string encode('ascii') method inside a try/except block which seems to work... – neutrino_logic May 25 '19 at 20:01
  • Why not use int(entry) inside a try/except block? That seems a lot simpler to me. – Jack Taylor May 26 '19 at 04:56
  • Perfect This is what I needed thanks @neureino_logic – YHapticY May 26 '19 at 05:08
  • Yes that's simpler... coming from C++ to Python, I think makes me more reluctant to use exceptions than is the 'pythonic' standard. Thanks for the suggestion. – neutrino_logic May 27 '19 at 19:34
0

I always use this method to check if something is not an integer:

Python 3

if not round(guess) == guess: print("Do Stuff")

Python 2

if not round(guess) == guess: print "Do Stuff"
SimpleBinary
  • 1,968
  • 1
  • 7
  • 13
  • That is not exactly what I'm looking for. I just need a conditional statement catching everything that is not an integer and outputting a message "Invalid Entry" and they return to prompt for another try. – YHapticY May 25 '19 at 06:12
0

You need to do something like this:

play = True

while play:
    guess = input("Guess a number between 1 and 5: ")

    try:
        number = int(guess)
    except ValueError:
        print("You need to input an integer.")
        continue

    if number < 1 or number > 5:
        print("You need to input an integer between 1 and 5.")
        continue

    # ...

    print("Your number was: " + guess)
    play = False

When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.

>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'

To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.

The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.

Jack Taylor
  • 5,588
  • 19
  • 35
  • I was able to get it to now work for values below 1 and above 5 But when I enter strings it's still spitting out error messages. is there a way for this to print out the "Invalid Entry" message when strings are entered like just a letter or a word? – YHapticY May 25 '19 at 07:07
  • Did you copy and paste my example code with no alterations? It should print "You need to input an integer" if you input a string. – Jack Taylor May 25 '19 at 09:51
0

Parse the user input as string to avoid ValueError.

guess = input("Guess a number between 1 and 5: ")

while not guess.isdigit() or int(guess) > 5 or int(guess) < 1: 
    guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")

guess = int(guess)

Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.

Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:

a = 2
isinstance(a, int)

Output:
>>> True
MrSeeker
  • 130
  • 11
  • 1
    This breaks for Unicode characters that are classified as digits but can't be converted to an int in Python. For instance, `"①".isdigit()` is True, but `int("①")` raises a ValueError. – Jack Taylor May 25 '19 at 10:03
  • @JackTaylor, Thanks! I was not aware of that. However, a typical user won't input Unicode characters like this unless they are adamant on breaking the program. – MrSeeker May 25 '19 at 15:38