[英]Not wanting to use if else but try except block in python
I am trying to write a program that does the following in python:我正在尝试编写一个在 python 中执行以下操作的程序:
accept three arguments: a prompt, a low acceptable limit, and a high acceptable limit;接受三个arguments:一个提示,一个可接受的下限,一个可接受的上限; if the user enters a string that is not an integer value, the function should emit the message Error: wrong input, and ask the user to input the value again;如果用户输入的字符串不是 integer 值,则 function 应发出消息错误:输入错误,并要求用户再次输入该值; if the user enters a number which falls outside the specified range, the function should emit the message Error: the value is not within permitted range (min..max) and ask the user to input the value again;如果用户输入的数字超出指定范围,function 应发出错误消息:该值不在允许的范围内 (min..max) 并要求用户再次输入该值; if the input value is valid, return it as a result.如果输入值有效,则将其作为结果返回。
I don't want to use if-else.我不想使用 if-else。 I am learning catching exceptions in python.我正在学习在 python 中捕获异常。 i want to use try-except我想使用 try-except
I have written the following code我写了以下代码
def readint(prompt, min, max):
try:
theNum = int(input(prompt))
if theNum in range(min, max+1):
return theNum
except ValueError:
return "Error: wrong input. The value is not within the permitted range (-10..10)"
readint(prompt, min, max)
v = readint("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
The output prints out any number in the mentioned range but when a number not within the range is entered, the output says "The number is: None" and it does not re-prompt me to enter another number output 打印出上述范围内的任何数字,但是当输入不在该范围内的数字时,output 会显示“数字为:无”并且它不会重新提示我输入另一个数字
Here's a typical retry loop that uses try/except:这是一个使用 try/except 的典型重试循环:
def thing_to_retry():
while True:
try:
return thing()
except SomeError as e:
print("Whoopsie! Error: {}".format(e))
Since the try/except is within the loop, any exception you catch will cause another loop iteration.由于 try/except 在循环内,您捕获的任何异常都将导致另一个循环迭代。 Success will cause the function to return from the loop.成功将导致函数从循环中返回。
def readint(prompt, min, max):
doIt = True
while doIt:
try:
userInput = int(input(prompt))
if userInput in range(min, max+1):
return userInput
doIt = False
else:
raise AssertionError
except ValueError:
print("Error: wrong input.")
except AssertionError:
print("The value is not within the permitted range (-10..10)")
except:
doIt = True
v = readint("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
min
and max
are keywords in python. min
和max
是 python 中的关键字。 I would avoid using them as variable names.我会避免将它们用作变量名。
def readint(prompt, minimum, maximum):
while True:
try:
value = int(input(prompt))
assert minimum <= value <= maximum
prompt = "Try again: "
except ValueError:
print("Error: Not an integer")
except AssertionError:
print("Error: Value not within range")
else:
break
return value
minimum = -10
maximum = 10
value = readint(f"Enter a number between {minimum} and {maximum}: ", minimum, maximum)
2 questions regarding the accepted answer.关于已接受答案的 2 个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.