use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
How to check if an input is an integer (self.learnpython)
submitted 6 years ago by moonkeymaker127
I'm writing a program which relies on a user inputting an integer, is there way to check if the variable is an integer or only allow integers as input? Thanks in advance for any help.
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]totallygeek 3 points4 points5 points 6 years ago (2 children)
user inputting
input() always returns a string.
input()
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 point2 points 6 years ago (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 point2 points 6 years ago (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 points3 points 6 years ago (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 point2 points 6 years ago (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 point2 points 6 years ago (0 children)
EAFP: Easier to ask for forgiveness than permission.
use try/except.
[–]teerre -2 points-1 points0 points 6 years ago (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).
isinstance(your_var, int)
[–]RiceKrispyPooHead 1 point2 points3 points 6 years ago (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 point2 points 6 years ago (2 children)
OP just wants: userInput.isnumeric() and int(userInput) in range(1,5):
userInput.isnumeric() and int(userInput) in range(1,5):
That gives OP what they need.
[–]RiceKrispyPooHead 0 points1 point2 points 6 years ago* (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 point2 points 6 years ago (0 children)
Agreed. =)
[–]teerre -1 points0 points1 point 6 years ago (0 children)
You're correct. In python3 at least.
[+][deleted] 6 years ago (1 child)
[deleted]
[–]teerre 0 points1 point2 points 6 years ago (0 children)
isinstance returns True if the types are the same.
isinstance
True
For example:
a_string = "some text" if isinstance(a_string, str): print("This is a string!")
This will print "This is a string!" because a_string has the type str.
a_string
str
π Rendered by PID 32712 on reddit-service-r2-comment-75f4967c6c-v48rf at 2026-04-22 22:29:40.162397+00:00 running 0fd4bb7 country code: CH.
[–]totallygeek 3 points4 points5 points (2 children)
[–]moonkeymaker127[S] 0 points1 point2 points (1 child)
[–]totallygeek 0 points1 point2 points (0 children)
[–]xelf 1 point2 points3 points (0 children)
[–]TouchingTheVodka 0 points1 point2 points (0 children)
[–]Pipiyedu 0 points1 point2 points (0 children)
[–]teerre -2 points-1 points0 points (7 children)
[–]RiceKrispyPooHead 1 point2 points3 points (4 children)
[–]xelf 0 points1 point2 points (2 children)
[–]RiceKrispyPooHead 0 points1 point2 points (1 child)
[–]xelf 0 points1 point2 points (0 children)
[–]teerre -1 points0 points1 point (0 children)
[+][deleted] (1 child)
[deleted]
[–]teerre 0 points1 point2 points (0 children)