Not wanting to use if else but try except block in python
Question:
I am trying to write a program that does the following in python:
accept three arguments: a prompt, a low acceptable limit, and a high acceptable limit;
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;
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;
if the input value is valid, return it as a result.
I don’t want to use if-else. I am learning catching exceptions in python. i want to use 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
Answers:
Here’s a typical retry loop that uses 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. Success will cause the function to return from the loop.
min
and max
are keywords in 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)
def readint(prompt, min, max):
doIt = True
while doIt:
try:
userInput = int(input(prompt))
if userInput in range(min, max+1):
doIt = False
return userInput
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)
def read_int(prompt, min, max):
#
while True:
try:
value = int(input(prompt))
assert min <= value <= max
return value
except AssertionError:
print("Error: the value is not within permitted range (-10..10)")
except ValueError:
print("Error: wrong input")
else:
break
#
v = read_int("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
- The problem with None is that you do not write: return readint(prompt, min, max)
You just write readint(prompt, min, max)
- If you like recursion ( I don’t) instead of a loop then you may try this:
def readint(prompt, mini, maxi):
try:
theNum = int(input(prompt))
assert theNum in range(mini, maxi + 1)
return theNum
except AssertionError:
print("Error: wrong input. The value is not within the permitted range (-10..10)")
except ValueError:
print("This is not a number")
return readint(prompt, mini, maxi)
I am trying to write a program that does the following in python:
accept three arguments: a prompt, a low acceptable limit, and a high acceptable limit;
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;
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;
if the input value is valid, return it as a result.
I don’t want to use if-else. I am learning catching exceptions in python. i want to use 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
Here’s a typical retry loop that uses 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. Success will cause the function to return from the loop.
min
and max
are keywords in 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)
def readint(prompt, min, max):
doIt = True
while doIt:
try:
userInput = int(input(prompt))
if userInput in range(min, max+1):
doIt = False
return userInput
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)
def read_int(prompt, min, max):
#
while True:
try:
value = int(input(prompt))
assert min <= value <= max
return value
except AssertionError:
print("Error: the value is not within permitted range (-10..10)")
except ValueError:
print("Error: wrong input")
else:
break
#
v = read_int("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)
- The problem with None is that you do not write: return readint(prompt, min, max)
You just write readint(prompt, min, max) - If you like recursion ( I don’t) instead of a loop then you may try this:
def readint(prompt, mini, maxi): try: theNum = int(input(prompt)) assert theNum in range(mini, maxi + 1) return theNum except AssertionError: print("Error: wrong input. The value is not within the permitted range (-10..10)") except ValueError: print("This is not a number") return readint(prompt, mini, maxi)