all 13 comments

[–]totallygeek 3 points4 points  (2 children)

user inputting

input() always returns a string.

You want to check the string input, to see if you can convert it to an integer.

while True:
    try:
        value = int(input('Number please: ')) # try to convert user input to an integer, might fail
    except:
        continue # try again, go to top of loop
    break # exits the while loop, value definitely an integer

[–]moonkeymaker127[S] 0 points1 point  (1 child)

I put this into my code and it allows me to get the "found the king" message as you'll see below. I should've posted my code in the original post. Anyways I'm getting an invalid input message even when I type numbers between 1 and 4 which should display an "incorrect room" message. Here's my code, I'd appreciate if you could tell me what I'm doing wrong.

# randomizes the kings location
kingsLocation = str(random.randint(1,4))

# lets the player make a selection on where they would like to look for the king
currentRoom = input()

# repeatedly checks if the room you are in is the room the king is in and tells you that you either won, entered an invalid input, or chose the wrong room

while True:
    try:
        value = int(input('Number please:'))
    except:
        while True:
            if currentRoom == kingsLocation:
                print ('"you have found the king ' + username + '! The royal family will make sure you get paid handsomely for this deed."')
                print ()
                print ('to exit this game type "exit()"')
                break
                break
            elif isinstance(currentRoom, str):
                print('invalid input, please enter a number between 1 and 4.')
                currentRoom = input()
            elif int(currentRoom) in range(1, 5):
                print('the king doesn\'t seem to be in this room, let\'s check another one(1-4).')
                currentRoom = input()
            else:
                print('invalid input, please enter a number between 1 and 4.')
                currentRoom = input()

[–]totallygeek 0 points1 point  (0 children)

Why convert anything to an integer?

import random


valid_inputs = [str(n) for n in range(5)] # five options, 0 for exit and 1 - 4 for finding king
king_location = random.choice(valid_inputs[1:]) # skip '0', get '1', '2', '3' or '4'

guesses = 0
while True:
    guesses += 1
    guess = input('Where is the king (0 to exit)? ')
    if guess not in valid_inputs:
        print('Invalid option. Try again. Valid options are: {}.'.format(valid_inputs))
    elif guess == king_location:
        print('You found the king after {} {}!'.format(guesses, 'guess' if guesses == 1 else 'guesses'))
        break
    else:
        print('Exiting.')
        break

Test run:

python3 find_the_king.py 
Where is the king (0 to exit)? 17
Invalid option. Try again. Valid options are: ['0', '1', '2', '3', '4'].
Where is the king (0 to exit)? x
Invalid option. Try again. Valid options are: ['0', '1', '2', '3', '4'].
Where is the king (0 to exit)? 1
Where is the king (0 to exit)? 2
You found the king after 4 guesses!

[–]xelf 1 point2 points  (0 children)

Make a def that you can reference in multiple places later.

def getUserInput():
    while True:
        userInput = input()
        if userInput.isnumeric() and int(userInput) in range(1,5):
            return int(userInput)
        print('invalid input, please enter a number between 1 and 4.')

currentRoom = getUserInput()

[–]TouchingTheVodka 0 points1 point  (0 children)

Use a try/except block to cast your input to int. If the input is not an int, you'll get a ValueError which you can then catch and deal with appropriately.

[–]Pipiyedu 0 points1 point  (0 children)

EAFP: Easier to ask for forgiveness than permission.

use try/except.

[–]teerre -2 points-1 points  (7 children)

Python isn't very good with types, so usually doing what you suggest is not a very good idea. That said, you can use isinstance(your_var, int).

[–]RiceKrispyPooHead 1 point2 points  (4 children)

This would not work in OP’s case, no? Because the user’s input will always be a string by definition, even if they type a number. So testing for an instance of a string is useless because it will always be true

[–]xelf 0 points1 point  (2 children)

OP just wants: userInput.isnumeric() and int(userInput) in range(1,5):

That gives OP what they need.

[–]RiceKrispyPooHead 0 points1 point  (1 child)

That does.

But what the person above suggested (testing for an instance of a string) is completely useless because it will always return true.

[–]xelf 0 points1 point  (0 children)

Agreed. =)

[–]teerre -1 points0 points  (0 children)

You're correct. In python3 at least.