我要做的是询问用户两个输入,如果其中一个输入小于零,或者输入是某个字符串,则再次询问输入。唯一有效的输入是数字> = 0。因此,您不能使用-1或cat作为输入。
尝试1:
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
while int(number_of_books) < 0 or int(number_of_chairs) < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
但是由此我意识到输入总是字符串,因此它会再次请求输入。
尝试2:
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
while number_of_books < 0 or number_of_chairs < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
但是有了这个,我意识到你不能做int('some string')
所以我想知道是否有办法做到这一点,或者这是不可能的事情?
答案 0 :(得分:4)
您应该为每个输入使用while
循环,因此只会再次询问无效循环。通过使用while True
,您需要输入一次,并在它有效时中断。尝试转换为int
,如果无法完成,则会ValueError
。异常导致打印自定义错误,并重新启动循环。
while True:
books_input = input("What is the number of books in the game?: ")
try:
number_of_books = int(books_input)
if number_of_books < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
你需要为每个输入执行此操作(可能有两个以上?),因此创建一个函数来完成繁重工作是有意义的。
def non_negative_input(message):
while True:
input_string = input(message)
try:
input_int = int(books_input)
if input_int < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
return input_int
致电:
non_negative_input("What is the number of books in the game?: ")
答案 1 :(得分:0)
解决方案是强制解决int()并捕获任何异常,例如:
while True:
try:
number_of_books = int(raw_input('Enter number of books:'))
if number_of_books < 0:
raise ValueError('must be greater than zero')
except ValueError, exc:
print("ERROR: %s" % str(exc))
continue
break
可能你应该将它放在一个函数中,并将提示符设为变量(以允许重复使用)。
答案 2 :(得分:0)
使用try except方法
while stringval = input("What is the number you want to enter"):
try:
intval = int(stringval)
if intval > -1:
break
except ValueError:
print 'Invalid answer, try again'
# Process intval now