0

Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:

while True:
    try:
        number = int(input("Please enter a (3 digit) number: "))
    except:
        print('try again')
    else:
        break

any help is appreciated! :)

Kody
  • 17
  • 1
  • 3
  • 2
    Does `012`count as 3 digits, or 2? You could always cast the number back to a string and look at the length: `len(str(number))`. Plus you would have to perform additional validation for cases like `12.3`, etc. (`isdigit` would be handy here). – Bahrom Jun 29 '16 at 04:47

5 Answers5

1

You could try something like this in your try/except clause. Modify as necessary.

number_string = input("Please enter a (3 digit) number: ")
number_int = int(number_string)
number_length = len(number_string)
if number_length == 3:
    break

You could also use an assert to raise an exception if the length of the number is not 3.

try:
    assert number_length == 3
except AssertionError:
    print("Number Length not exactly 3")
sytech
  • 29,298
  • 3
  • 45
  • 86
0

input() returns you a string. So you can first check the length of that number, and length is not 3 then you can ask the user again. If the length is 3 then you can use that string as a number by int(). len() gives you the length of the string.

while True:
    num = input('Enter a 3 digit number.')
    if len(num) != 3:
        print('Try again')
    else:
        num = int(num)
        break
GadaaDhaariGeek
  • 971
  • 1
  • 14
  • 33
  • Also, if you want to use the same thing in python 2.x you should use 'raw_input()' instead of 'input()'. Because python is not backward compatible, issues often comes. Also you can up vote the answer if it helped. – GadaaDhaariGeek Jun 29 '16 at 05:55
0

Keep the input in a variable before casting it into an int to check its length:

my_input = input("Please enter a (3 digit) number: ")
if len(my_input) != 3:
    raise ValueError()
number = int(my_input)

Note that except: alone is a bad practice. You should target your exceptions.

Community
  • 1
  • 1
Simon
  • 774
  • 4
  • 21
0
while True:
    inp = raw_input("Enter : ")
    length = len(inp)
    if(length!=3):
        raise ValueError
    num = int(inp)   

In case you are using Python 2.x refrain from using input. Always use raw_input.

If you are using Python 3.x it is fine.

Read Here

Community
  • 1
  • 1
formatkaka
  • 1,278
  • 3
  • 13
  • 27
0

This should do it:

while True:
    try:
        string = input("Please enter a (3 digit) number: ")
        number = int(string)
        if len(string) != 3 or any(not c.isdigit() for c in string):
            raise ValueError()
    except ValueError:
        print('try again')
    else:
        break
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172