Way to loop from the middle of the while loop
我有2个输入键入,如果用户输入错误的输入,我想循环它们。 我做的是我设置为True然后尝试除了然后继续。 但是,如果输入错误,则在第二次输入的情况下,从开始重复整个循环 - 即从第一个输入开始。 我想从第二个输入重复它。 我唯一能想到的是在第一次正确输入后将代码放入代码中,然后在第二次输入时为True设置另一个。 有什么更好的方法呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 |
你可以使用decorator重试逻辑和单个函数来读取int值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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) |
你问过
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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) |
由于每个循环的条件相同,您可以尝试将try-except部分存储为返回值的函数(或者使用值的参数指示成功或失败的bool),在for循环中运行lambda 您需要的每个输入,将结果存储在列表中,然后将您需要的内容作为元组获取。
例如。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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循环的另一个分支)