-1

How to narrow input of a integer to a certain length like "7" (per example) from a user raw_input:

def number():
number=int(input("Number:"))
print(number)

number=1234567

It has to have an while condition where it says if len(number) < 7 or len(number) > 7:

print("Error")
phone=int(input("Number:"))` 

Thank you & Merry Xmas

Phyti
  • 131
  • 9

1 Answers1

2

check the length before you try casting to int:

def number():
    while True:
        i = input("Number:") 
        if len(i) > 7:
            print("Number can only contain at most 7 digits!")
            continue
        try:
            return int(i)
        except ValueError:
            print("Invalid input")

If you want exactly 7 use if len(i) != 7 and adjust the error message accordingly. I also used a try/except as because the length is seven does not mean it is a valid string of digits. If you want to allow the minus son you could if len(i.lstrip("-")) > 7:

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • I have to say if len(number)<7 or len(number)>7: print("Input Invalid") and to print again raw_input(int("Number")). – Phyti Dec 24 '15 at 19:10
  • 1
    You don't use number at all, you check the length if i and only try casting to int if it is an acceptable length, if you want at most a 7 digit number then `if len(i) > 7:` will work as you want as any length > 7 will not be ignored – Padraic Cunningham Dec 24 '15 at 19:13
  • 2
    just run the code @Phyti .. the `while True` keeps reprompting until correct input is recieved ... – Joran Beasley Dec 24 '15 at 19:13
  • Ok I will @JoranBeasley – Phyti Dec 24 '15 at 19:16