我有2个输入要输入,如果用户输入错误的输入,我想循环遍历它们。我做的是我设置为True然后尝试除了然后继续。但是,如果输入错误,则在第二次输入的情况下,从开始重复整个循环 - 即从第一个输入开始。我想从第二个输入重复它。我唯一能想到的是在第一次正确输入后将代码放入代码中,然后在第二次输入时为True设置另一个。有什么更好的方法可以做到这一点?
while True:
try:
a = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if a <= 0:
print("Input can't be 0 or negative!")
continue
else:
try:
b = int(input("Type second positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if b <= 0:
print("Input can't be 0 or negative!")
continue
else:
break
答案 0 :(得分:0)
由于每个循环的条件相同,您可以尝试将try-except部分存储为返回值的函数(或者使用值的参数指示成功或失败的bool),运行lambda in a为您需要的每个输入循环,将结果存储在列表中,然后将您需要的内容作为元组。
E.g。
def try_get_number_input():
try:
value = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
return False, 0
if value <= 0:
print("Input can't be 0 or negative!")
return False, 0
return True, value
# We require 2 inputs from the user
required_inputs = 2
received_inputs = []
for num in range(0, required_inputs):
values = try_get_number_input()
while not values[0]:
values = try_get_number_input()
received_inputs.append(values[1])
这可以确保代码是DRY(不会自行重复)并且可以轻松更改(如果您需要3个输入,您可以轻松更改它而不必添加while循环的另一个分支)
答案 1 :(得分:0)
def getNumber(second=False):
while True:
try:
if second:
number = int(input("Type second positive integer: "))
else:
number = int(input("Type positive integer: "))
except ValueError:
print(" Enter a positive NUMBER!")
continue
if number <= 0:
print("Input can't be 0 or negative!")
continue
return number
a, b = getNumber(second=False), getNumber(second=True)
print(a,b)
答案 2 :(得分:0)
你问for
循环是什么样的,这是一个例子:
vals = []
for msg in ['', 'second ']:
while True:
try:
n = int(input(f"Type {msg}positive integer: ")) # PY3.6
# n = int(input("Type {}positive integer: ").format(msg))) # <=PY3.5
except ValueError:
print(" Enter a positive NUMBER!")
continue
if n <= 0:
print("Input can't be 0 or negative!")
continue
vals.append(n)
break
a, b = vals
答案 3 :(得分:0)
你可以使用装饰器重试逻辑和单个函数来读取int值
def retry(func):
def wrapper(msg):
while True:
try:
return func(msg)
except Exception as e:
print(e)
return wrapper
@retry
def read_int(msg):
try:
a = int(input(msg))
except:
raise ValueError('Invalid Number')
else:
if a < 0:
raise ValueError('Number should be positive')
return a
a = read_int('type valid positive number: ')
b = read_int('type other valid positive number: ')
print(a, b)