0

I am trying to return the number if it is an INT and between numbers, an error occurs when you enter a letter . also you have to input the correct value twice to get an input:

  def get_number():

b = False

while b == False:
    try:
        n = (input('Please enter a 6 digit number'))
    except ValueError:
        continue
    if n >= 100000 and n <= 1000000:
        b = True
        break
return n

if __name__ == '__main__':
    get_number()
    print get_number()

`

Changed input to raw_input , it now work if someone enters a letter. however when i enter the correct input ,it will keep on looping:

def get_number():

b = False

while b == False:
    try:
        n = (raw_input('Please enter a 6 digit number'))
    except ValueError:
        continue
    if n >= 100000 and n <= 1000000:
        b = True
        break
return n

if __name__ == '__main__':
    get_number()
    print get_number()
bbaayy
  • 5
  • 2

1 Answers1

1

There are a few problems with your code.

  • you could just use input to evaluate whatever the unser entered, but that's dangerous; better use raw_input to get a string and try to cast that string to int explicitly
  • also, if you are using input, then you'd have to catch NameError and SyntaxError (and maybe some more) instead of ValueError
  • currently, your if condition would allow a 7-digit number (1000000) to be entered; also, you can simplify the condition using comparison chaining
  • no need for the boolean variable; just break or return from the loop
  • you call your function twice, and print only the result of the second call

You could try something like this:

def get_number():
    while True:
        try:
            n = int(raw_input('Please enter a 6 digit number '))
            if 100000 <= n < 1000000:
                return n
        except ValueError:
            continue

if __name__ == '__main__':
    print get_number()
tobias_k
  • 81,265
  • 12
  • 120
  • 179