[英]How to make the try function only print my message once
I've tried using the try() function, but when i try: and then type print() it just prints the message non-stop. 我已经尝试过使用try()函数,但是当我尝试:然后键入print()时,它只是不停地打印消息。 how do i make it only print once? 我如何使其仅打印一次?
def inputInt(minv, maxv, message):
res = int(input(message))
while (res > minv) and (res < maxv):
try:
print("Good job.")
except:
print("Invalid input")
Have you tried with break
? 您尝试过break
吗?
Take a look at this and this to get more clarification, but if you want that at the one time the try jumps to the except, it should print it once only, break
is the thing. 看看这个和这个 ,以获得更多的澄清,但如果你想,在一个时间尝试跳转到不同的,它应该打印出来只有一次, break
是事情。
I must say this loop will go on forever as you are not changing res
. 我必须说这个循环将永远持续下去,因为您没有更改res
。 Even if it goes in the try
or in the except
. 即使在try
还是在except
。
The code that could raise an exception should be in the try
. 可能引发异常的代码应该在try
。 The input should be inside the while
. 输入应在while
。 Catch expected exceptions in case an unexpected exception occurs. 如果发生意外异常,请捕获预期的异常。 A naked except
is bad practice and can hide errors. 裸except
是不好的做法,可以掩盖错误。
Here's a suggested implementation: 这是一个建议的实现:
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: ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.