Python 3.x 如何使try函数只打印我的邮件一次
我尝试过使用try()函数,但当我尝试:然后键入print()时,它只会不间断地打印消息。如何使它只打印一次Python 3.x 如何使try函数只打印我的邮件一次,python-3.x,Python 3.x,我尝试过使用try()函数,但当我尝试:然后键入print()时,它只会不间断地打印消息。如何使它只打印一次 def inputInt(minv, maxv, message): res = int(input(message)) while (res > minv) and (res < maxv): try: print("Good job.") except: print("Inva
def inputInt(minv, maxv, message):
res = int(input(message))
while (res > minv) and (res < maxv):
try:
print("Good job.")
except:
print("Invalid input")
def输入(最小值、最大值、消息):
res=int(输入(消息))
而(res>minv)和(res
您是否尝试过使用中断
查看并获得更多说明,但如果您希望在尝试跳转到Exception的某个时间进行此操作,它应该只打印一次,break
我必须说,这个循环将永远持续下去,因为你不会改变
res
。即使它出现在try
或except
中,可能引发异常的代码也应该出现在try
中。输入应在中,而中。在发生意外异常时捕获预期异常。除了
之外的裸露的是不好的做法,可以隐藏错误
下面是一个建议的实现:
def inputInt(minv, maxv, message):
while True: # Loop until break
try:
res = int(input(message)) # Could raise ValueError if input is not an integer.
if minv <= res <= maxv: # if res is valid,
break # exit while loop
except ValueError: # Ignore ValueError exceptions
pass
print("Invalid input") # if didn't break, input or res was invalid.
return res # Once while exits, res is good
x = inputInt(5,10,"enter number between 5 and 10: ")
def输入(最小值、最大值、消息):
为True时:#循环直到中断
尝试:
res=int(输入(消息))#如果输入不是整数,则可能引发ValueError。
如果是minv,为什么需要在这里尝试/捕获?它之所以不停止打印是因为while循环。由于这两个条件在循环内没有更新,因此这些条件始终为真。这就是为什么它一直在打印res=int(输入(消息))
while
循环时不也在中?否则,res
将永远无法更新。实际上是“安迪克”s的评论非常相关!