[英]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. 您的代码有一些问题。
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
input
, then you'd have to catch NameError
and SyntaxError
(and maybe some more) instead of ValueError
input
,那么您必须捕获NameError
和SyntaxError
(可能还有更多)而不是ValueError
if
condition would allow a 7-digit number (1000000) to be entered; if
条件将允许输入7位数字(1000000); also, you can simplify the condition using comparison chaining break
or return
from the loop break
或从循环return
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.