Right now I'm trying to make a simple tic-tac-toe game, and while user chooses the sector of the board for their next move I need to check if the input is a single-digit natural number. I don't think just making a ['1','2','3'...'9']
list and calling an in statement for it is the most optimal thing. Could you suggest anything?
You can check if a string, x
, is a single digit natural number by checking if the string contains digits and the integer equivalent of those digits is between 1 and 9, i.e.
x.isdigit() and 1 <= int(x) <= 9
Also, if x.isdigit()
returns false, int(x)
is never evaluated due to the expression using and
(it is unnecessary as the result is already known) so you won't get an error if the string is not a digit.
Using len
and str.isdigit
:
>>> x = '1'
>>> len(x) == 1 and x.isdigit() and x > '0'
True
>>> x = 'a'
>>> len(x) == 1 and x.isdigit() and x > '0'
False
>>> x = '12'
>>> len(x) == 1 and x.isdigit() and x > '0'
False
Alternative: using len
and chained comparisons:
>>> x = '1'
>>> len(x) == 1 and '1' <= x <= '9'
True
>>> x = 'a'
>>> len(x) == 1 and '1' <= x <= '9'
False
>>> x = '12'
>>> len(x) == 1 and '1' <= x <= '9'
False
Why not just use
>>> natural = tuple('123456789')
>>> '1' in natural
True
>>> 'a' in natural
False
>>> '12' in natural
False
Checking for membership in a small tuple you initialize once is very efficient, a tuple
in particular over a set
since it's optimized for small numbers of items. Using len
and isdigit
is overkill.
Following on console could help :
>>> x=1
>>> x>0 and isinstance(x,int)
True
Although there are many answers for your question , but , with all due respect, i believe there are some bugs that may happen through using them.
One of them is that using x.isdigit()
, this works! but just for strings!!. but what if we wanna check another types such as float? and another problem is that using this method will not work for some numbers such as 12.0. right!. it's a natural number but pyhton will find this as a float. so i think we can check natural numbers by using this function :
def checkNatNum(n):
if str(n).isdigit() and float(n) == int(n) and int(n) > 0:
return True
else:
return False
I ensure you this will do the process fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With