Python limiting digits as an int in a input

367 Views Asked by At

So as the title suggests I am trying to limit integers in a input to 11, has anyone got a simple solution to this?

Edit. Sorry should be a little more precise, I'm not trying to limit the actual input to 11. I'm trying to limit the amount of digits inputted to 11 such as,

input 123 = okay input 123456789123 = invaid

4

There are 4 best solutions below

0
CDJB On

Assuming you mean to only accept integers in the range 0 <= x <= 11, you could use:

while True:
    try:
        inpt = int(input('Enter number less than 12: '))
        if inpt in range(12):
            break
    except:
       pass 
    print('Invalid input.')
0
peki On

Try:

while True:
    a = input ("Input: ")
    if len(a) < 11: #excepted as string
        a = int(a)          
        break
0
N Chauhan On

If you want to only accept a maximum of 11-digit numbers, just compare it to a twelve digit number:

def up_to_digits(n):
    while True:
       try:
           r = int(input('Enter number: '))
           if r >= 10 ** n or r <= -(10 ** n):
               print('Maximum {} digits'.format(n))
               raise ValueError
           return r 
       except ValueError:
           pass
2
Andrex On
def f(x):
  if x >= 1E+11:
     raise SomeError

  "Do something"

Something like this u mean?