简体   繁体   English

python:输入验证返回

[英]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 . 我试图返回一个数字,如果它是一个INT,并且在数字之间,则在输入字母时出现错误。 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. 将输入更改为raw_input,如果有人输入字母,现在可以使用。 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; 可以只使用input来评估unser输入的内容,但这很危险; better use raw_input to get a string and try to cast that string to int explicitly 最好使用raw_input获取一个字符串,然后尝试将该字符串显式转换为int
  • also, if you are using input , then you'd have to catch NameError and SyntaxError (and maybe some more) instead of ValueError 另外, 如果您使用input ,那么您必须捕获NameErrorSyntaxError (可能还有更多)而不是ValueError
  • currently, your if condition would allow a 7-digit number (1000000) to be entered; 当前,您的if条件将允许输入7位数字(1000000); also, you can simplify the condition using comparison chaining 另外,您可以使用比较链接简化条件
  • no need for the boolean variable; 不需要布尔变量; just break or return from the loop 只是break或从循环return
  • 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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