简体   繁体   中英

python: input validation return

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()

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM