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, ie
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
Following on console could help :
>>> x=1
>>> x>0 and isinstance(x,int)
True
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.
I don't know why are people pushing this to next level. Simply for natural number you can write,
int(x) > 0
And for the range issue:
0 < int(x) <= 9
Obviously numbers lying within the range are natural numbers.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.