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
Answer from Maroun on Stack OverflowUse 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
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")
Beginner Python question
Using regular expressions and filter why does isdigit return false on a number?
.isdigit() .isnumeric() .isdecimal()
Handling negative number inputs from the user
Here is the code:
import re s = " -42" s = re.split(r'\s+', s) s = list(filter(None,s)) print(s[0].isdigit())
This prints out False. I don't understand why because if I go to simply print it without the isdigit it gives back 42.
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
The method tests for digits only, and - is not a digit. You need to test with int() and catch the ValueError exception instead if you wanted to detect integers:
for i, value in enumerate(mylist):
try:
mylist[i] = int(value)
except ValueError:
pass # not an integer
In other words, there is no need to test explicitly; just convert and catch the exception. Ask forgiveness rather than ask for permission.
The way to convert to integers is to try the conversion and be prepared for it to fail:
for i in range(len(mylist)):
try:
mylist[i] = int(mylist[i])
except ValueError:
pass
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
Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails:
choice = raw_input("> ")
try:
y = int(choice)
x += y
except ValueError:
print "Invalid input."