我怎样才能使这个循环继续下去,直到输入正确的输入?



这是我写的代码,我现在正在学习python但告诉我如何让这个循环继续下去,直到我们达到正确的条件,即x和y都是整数,y>0,这样它就不会抛出异常。

def problem_2():
while True:
try:
x = int(input("Enter the value of X"))
y = int(input("Enter the value of Y"))
print(x/y)
except ZeroDivisionError:
print("You have divided the number by zero")
except TypeError:
print("Please Enter Integer in both the cases")
problem_2()

您可以简单地创建一个无限while循环,以x和y作为输入并检查您的条件。

  1. 如果满足条件,则执行您想要执行的处理并中断循环。
  2. 如果你的条件没有满足,那么就继续循环,同样的事情会重复,直到你的条件满足。
while true:
#take your input
#check your condition 
#if condition not met 
continue
#if condition met
#do your stuff
break

检查y>在你的异常捕获块之后:

def problem_2():
while True:
try:
x = int(input("Enter the value of X"))
y = int(input("Enter the value of Y"))
print(x/y)
except ZeroDivisionError:
print("You have divided the number by zero")
except TypeError:
print("Please Enter Integer in both the cases")
# No exception was raised, check y
if y > 0:
break
problem_2()

或者,为了完全避免使用异常处理,您可以这样做:

def problem_2():
while True:
x = input("Enter the value of X")
y = input("Enter the value of Y")
if not x.isdigit() or not y.isdigit():
print("Please enter Integer in both the cases")
continue
x, y = int(x), int(y)
if x == 0 or y == 0:
print("Cannot divide by zero")
continue
# If we reached here, the input is valid
print(x/y)
break
problem_2()

试试这个,我希望它能完美地满足你的需要。由于

def problem_2():
while True:
x = input("Enter the value of x: ")
y = input("Enter the value of y: ")
if x.isdigit() and y.isdigit():
if int(y)>0:
print(int(x)/int(y))
else:
pass 
else:
continue
problem_2()

最新更新