Skip to content Skip to sidebar Skip to footer

How Can I Limit The Amount Of Digits In An Input?

I'm a student doing a computer science course and for part of the assessment we have to write a program that will take 10 digits from the user and used them to calculate an 11th nu

Solution 1:

You have to convert the int to a string because int does not have a length property. Also You were checking if the digit was longer than 1 for a twice so I switched the SECOND NUMBER check to b

print('Please enter your 10 digit number')
a = raw_input("FIRST NUMBER: ")
iflen(a) > 1:
    print ("Error. Only 1 digit allowed!")
a = int(a)
aa = (a*10)

b = raw_input("SECOND NUMBER: ")
iflen(b) > 1:
    print ("Error. Only 1 digit allowed!")
b = int(b)
bb = (b*10)

Or more simply:

You could ask for the number and keep asking until the length is 10 and the input is a number

num = raw_input('Please enter your 10 digit number:')
whilelen(num) != 10or (not num.isdigit()):
    print'Not a 10 digit number'
    num = raw_input('Please enter your 10 digit number:')
num = int(num)
print'The final number is: ', num

Solution 2:

I suggest creating a function to handle of of the prompting, then call it in your code. Here is a simplfied example:

defsingle_num(prompt):
    num = ""whileTrue:
        num = raw_input(prompt)

        iflen(num) == 1:
            try:
                returnint(num)
            except ValueError:
                print"Error, you must enter a number"else:
            print"Try again, now with a single number"

This will take a prompt, and ask it over and over again until it recieves a 1 length string. To make this more user friendly, you can add in protections with try...except for non-numerical input and whatnot

Solution 3:

You never stated if you're on Windows or Linux, the code listed below is for Windows (as I'm on a Windows machine right now and can't test the equivalent on Linux).

# For windowsimport msvcrt
print('Please enter your 10 digit number')
print('First number: ')
a = int(msvcrt.getch())
print(a)

The .getch() call with msvcrt just gets a single character from the terminal input. You should also wrap the call to int() in a try/except block to stop your application from crashing when getting non-integer input.

Solution 4:

Firstly, I'm assuming you are using 3.x. Secondly, if you are using 2.x, you can't use len on numbers.

This is what I would suggest:

print('Please enter your 10 digit number')

number = ''for x inrange(1,11):
    digit = input('Please enter digit ' + str(x) + ': ')
    whilelen(digit) != 1:
        # digit is either empty or not a single digit so keep asking
        digit = input('That was not 1 digit. Please enter digit ' + str(x) + ': ')        
    number += digit # digit is a single digit so add to number# do the rest

It makes more sense to keep all the numbers in a str as you can then split them out later as you need them e.g. number[0] will be the first digit, number[1] will be the second.

If you can adapt your program to not have to explicitly use a, b, c ,d etc. and instead use slicing, it will be quite simple to construct.

Obviously if you can use a whole 10 digit number than the best method would be:

number = input('Please enter your 10 digit number: ')

whilelen(number) != 10:
    number = input('That was not a 10 digit number. Please enter your 10 digit number ')

As a last resort, if you absolutely have to have individual variable names per digit, you can use exec and eval:

var_names = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # add more as neededforvar, num in var_names:
    exec(var + ' = input("Please enter digit " + str(num) + ": ")')
    whileeval('len(' + var + ')') != 1:
        exec(var + ' = input("That was not a single digit. Please enter digit " + str(num) + ": ")')

That would give you vars a,b,c and d equalling the digits given.

Solution 5:

This is probably cleanest to do with a validation wrapper.

defvalidator(testfunc):
    defwrap(func):
        defwrapped(*args, **kwargs):
            result = func(*args, **kwargs)
            pass, *failfunc = testfunc(result)
            it pass:
                return result
            elif failfunc:
                failfunc[0]()
        return wrapped
    return wrap

deften_digits(num):
    pass = Falseiflen(num) != 10:
        msg = "{} is not of length 10".format(num)
    elifnot num.isdigit():
        msg = "{} is not a number".format(num)
    else:
        pass = Truedeffailfunc():
        raise ValueError(msg)
    response = (pass, Noneifpasselse failfunc)
    return response

valid_input = validator(ten_digits)(input) # or raw_input in Python2
response = valid_input("Enter your 10 digit number: ")

This is probably a bit overengineered, but it's incredibly reusable (have a different set of tests you need validated? Write a new ten_digits analogy!) and very configurable (want different behavior out of your fail function? Write it in!) Which means you could do things like:

ISBN = validator(ten_digits)(input)("ISBN# = ")
title = validator(max_50_chars)(input)("Title = ")
author = validator(no_digits)(input)("Author = ")
price = decimal.Decimal(validator(float_between_1_and_50)(input)(
        "Price = ")).quantize(decimal.Decimal('1.00'))

Post a Comment for "How Can I Limit The Amount Of Digits In An Input?"