You can easily remove the characters from the left first, like so:

choice.lstrip('-+').isdigit()

However it would probably be better to handle exceptions from invalid input instead:

print x
while True:
    choice = raw_input("> ")
    try:
        y = int(choice)
        break
    except ValueError:
        print "Invalid input."
x += y
Answer from Alex Hall on Stack Overflow
🌐
Quora
quora.com › What-method-checks-that-the-string-is-a-number-and-includes-negative-in-the-Python-language
What method checks that the string is a number and includes negative in the Python language? - Quora
Answer (1 of 8): The simplest way - use the inbuilt ‘int(..)’ function and capture the exception that int(..) raises when it finds something that isn’t an int (it raises a ValueError exception). Use try/except to capture whether a call to int() raises a ValueError.
Discussions

python - How to type negative number with .isdigit? - Stack Overflow
when I try this if question.isdigit() is True: I can type in numbers fine, and this would filter out alpha/alphanumeric strings when I try 's1' and 's' for example, it would go to (else). Proble... More on stackoverflow.com
🌐 stackoverflow.com
Handling negative number inputs from the user
I would recommend you use a try instead. answer = input(f"What is {a} + {b}") try: answer = int(answer) except ValueError: print("That's not a number") More on reddit.com
🌐 r/learnpython
19
4
January 29, 2025
.isdigit() .isnumeric() .isdecimal()
which of the following will work for a negative number to? .isnumaric() .isdigit() .isdecimal() thanks a lot! More on discuss.codecademy.com
🌐 discuss.codecademy.com
0
0
December 3, 2019
Can someone help me with this problem?
You have to remove: if top_of_range.isdigit(): top_of_range = int(top_of_range) And write: top_of_range = int(input("Type a number: ")) Edit: You take the first input number as a string, then the code checks if it is an integer, if it is an integer, it will then cast the integer into an integer - which doesn't make much sense. You could change it to check if it is a string instead though, if you want to keep those lines. The code have a bunch of other oddities, like the quit statements after every if-else, why are those there? More on reddit.com
🌐 r/learnpython
8
1
December 26, 2022
🌐
Nextjournal
nextjournal.com › avidrucker › detecting-valid-number-strings-in-python
Detecting Valid Number Strings in Python - Nextjournal
It appears that Python's isnumeric() function performs no better than Python's isdigit() function, though I may be missing something here 🤷 · How about we try to determine (using our own custom code) whether or not a given string an actual ...
Top answer
1 of 7
88

Use lstrip:

question.lstrip("-").isdigit()

Example:

>>>'-6'.lstrip('-')
'6'
>>>'-6'.lstrip('-').isdigit()
True

You can lstrip('+-') if you want to consider +6 a valid digit.

But I wouldn't use isdigit, you can try int(question), it'll throw an exception if the value cannot be represented as int:

try:
    int(question)
except ValueError:
    # not int
2 of 7
28

Use a try/except, if we cannot cast to an int it will set is_dig to False:

try:
    int(question)
    is_dig = True
except ValueError:
    is_dig = False
if is_dig:
  ......

Or make a function:

def is_digit(n):
    try:
        int(n)
        return True
    except ValueError:
        return  False

if is_digit(question):
   ....

Looking at your edit cast to int at the start,checking if the input is a digit and then casting is pointless, do it in one step:

while a < 10: 
     try:
        question = int(input("What is {} {} {} ?".format(n1,op,n2)))
     except ValueError:
        print("Invalid input")
        continue # if we are here we ask user for input again

    ans = opsop
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")
    a += 1

Not sure what Z is doing at all but Z = Z + 0 is the same as not doing anything to Z at all 1 + 0 == 1

Using a function to take the input we can just use range:

def is_digit(n1,op,n2):
    while True:
        try:
            n = int(input("What is {} {} {} ?".format(n1,op,n2)))
            return n
        except ValueError:
            print("Invalid input")


for _ in range(a):
    question = is_digit(n1,op,n2) # will only return a value when we get legal input
    ans = opsop
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")
🌐
YouTube
youtube.com › watch
Python: Check if a string is a positive or negative integer - YouTube
In this video we go over a simple function to see if a string is an integer - handling both positive and negative cases.Original blog post with all code and ...
Published   December 11, 2024
🌐
Reddit
reddit.com › r/learnpython › handling negative number inputs from the user
r/learnpython on Reddit: Handling negative number inputs from the user
January 29, 2025 -

This is a solution post. I had a problem and none of the solutions I found online were right for me. I eventually figured it out, and so I'm putting my solution here for future learners. Also if my solution is bad, I'll get some feedback. If you think it's obvious, then you're very clever, but no need to go to the trouble of letting me know!

I'm making an arithmetic game for my little one. So it had a line:

answer = int(input(f"What is {a} + {b}?"))

but of course he accidentally typed a letter and crashed the program. I wanted to handle this eventuality so I changed it to:

answer = input(f"What is {a} + {b}")
if answer.isnumeric():
    answer = int(answer)
else:
    print("That's not a number")
    continue

the trouble is I also have subtraction questions and negative numbers! But "-1".isnumeric()==False !!

So I started googling: "isnumeric negative numbers" and "parsing negative numbers" and so on. The solutions I found were quite convoluted, mostly they seemed to be worrying about SQL injection and used concepts I hadn't learned yet. I wanted a solution that only used the beginner stuff I already knew. I realised that I only had to check if the first symbol is "-" and the rest is numeric. So:

if answer.isnumeric() or answer[0]=="-" and answer[1:].isnumeric():

is the solution!

EDIT: There was a typo in my solution, I meant to check if everything after the initial "-" is numeric. Otherwise an answer like "-3e" gets through. Thanks to u/Rizzityrekt28 for the catch

Find elsewhere
🌐
Programiz
programiz.com › python-programming › examples › positive-negative-zero
Python Program to Check if a Number is Positive, Negative or 0
To understand this example, you should have the knowledge of the following Python programming topics: ... num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
🌐
Codecademy Forums
discuss.codecademy.com › get help › python
.isdigit() .isnumeric() .isdecimal() - Python - Codecademy Forums
December 3, 2019 - which of the following will work for a negative number to? .isnumaric() .isdigit() .isdecimal() thanks a lot!
🌐
Reddit
reddit.com › r/learnpython › can someone help me with this problem?
r/learnpython on Reddit: Can someone help me with this problem?
December 26, 2022 - But you still have to remove the last quit() after else, otherwise it doesn't matter what you do, the program will quit even if the number entered is legal. The second part is going to need some work too but I think you're right on path! ... This is a guess, as I’ve never used “isdigit” before, but could it be that it is not working because “-“ in your negative number is not a digit? Try “isnumeric” instead. ... This is giving you trouble because negative numbers as strings don't seem to work very well with .isdigit or .isnumeric.
🌐
Miguendes
miguendes.me › python-isdigit-isnumeric-isdecimal
How to Choose Between isdigit(), isdecimal() and isnumeric() in Python
November 7, 2021 - Checking numbers starting with minus sign depend on the target type. Since we're talking about digits here, it makes sense to assert if the string can be converted to int. This is very similar to the EAFP approach discussed for floats. However, just like the previous approach, it doesn't handle superscripts. def is_negative_number_digit(n: str) -> bool: try: int(n) return True except ValueError: return False >>> is_negative_number_digit('-2345') True >>> is_negative_number_digit('-2345⁵') False
🌐
OpenPython
openpython.org › home › articles › python: check if a string is a number
Python: Check if a String is a Number | OpenPython
April 4, 2026 - The most reliable way to check if a Python string contains a valid number is try: float(s) — it handles integers, decimals, negatives, scientific notation, and leading/trailing whitespace, exactly matching what Python itself considers a valid ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-check-whether-a-number-is-positive-or-negative-or-zero
Python Program to Check Whether a Number is Positive or Negative or zero - GeeksforGeeks
January 31, 2023 - Given a number. The task is to check whether the number is positive or negative or zero. ... We will use the if-elif statements in Python.
🌐
Flexiple
flexiple.com › python › check-if-int-python
How to Check if a String is an Integer in Python? - Flexiple
March 21, 2024 - Use the isdigit() method in Python to check if a string is a number. This method is straightforward and returns True when all characters in the string are digits, and the string is not empty.
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-109.php
Python: Check if a number is positive, negative or zero - w3resource
May 17, 2025 - print("It is a positive number") # Check if the number is equal to zero. elif num == 0: # If true, print that it is zero. print("It is zero") else: # If the above conditions are not met, print that it is a negative number.
🌐
Sling Academy
slingacademy.com › article › python-check-if-a-string-can-be-converted-to-a-number
Python: Check If a String Can Be Converted to a Number - Sling Academy
June 4, 2023 - You can use the string isnumeric() method to verify that all the characters in a string are numeric (0-9) or other numeric characters like exponents (², ¾). This method returns True if the string is a numeric value, otherwise False. ... s = "2024" print(s.isnumeric()) # True s = "2²2" ...
🌐
Hamy
hamy.xyz › blog › 2024-12_python-check-positive-or-negative-integer
Python: Check if a string is a positive or negative integer - HAMY
December 11, 2024 - Python has a lot of built-in helpers like isdigit to help you figure out what a value is. I recently ran into an issue where I needed to see if a value was a positive or negative integer but isdigit only handles positives. So here's a little workaround to check if a string is a positive or ...
🌐
Stack Abuse
stackabuse.com › check-if-string-contains-a-number-in-python
Check if String Contains a Number in Python
May 17, 2023 - Note: The isdigit() method only behaves in the same manner as isnumeric(), and if you pass a string containing a float or a negative number to it, False is returned due to the special characters not being numbers. On a character-level, though, if as long as one True value is enough to determine ...
🌐
PYnative
pynative.com › home › python › programs and examples › python program to check if a number is positive, negative, or 0
Python Program to Check if a Number is Positive, Negative, or 0
March 31, 2025 - A lambda function in Python is a small, anonymous function that is defined using the lambda keyword. It can have multiple arguments but only one expression, which is evaluated and returned. ... This is more concise way to perform the same check in a more functional programming style. It works similar to the ternary operator but wrapped inside a lambda. num = -10 check_sign = lambda num: "Positive" if num > 0 else "Negative" if num < 0 else "Zero" print(check_sign(num)) # Output: # NegativeCode language: Python (python) Run