Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if input is a natural number in Python?

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?

like image 989
Owlythesova Avatar asked Jan 01 '15 01:01

Owlythesova


5 Answers

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.

like image 149
Elle Avatar answered Nov 02 '22 12:11

Elle


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
like image 27
falsetru Avatar answered Nov 02 '22 10:11

falsetru


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.

like image 38
jamylak Avatar answered Nov 02 '22 12:11

jamylak


Following on console could help :

>>> x=1
>>> x>0 and isinstance(x,int)
True
like image 2
user6402562 Avatar answered Nov 02 '22 10:11

user6402562


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.

like image 1
TheFaultInOurStars Avatar answered Nov 02 '22 10:11

TheFaultInOurStars