Printing Message Rather Than Valuerror In An Integer User Input?
Solution 1:
You need to handle the ValueError exception using try/except block. Your code should be like:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print('Please enter a valid integer value')
continue# To skip the execution of further code within the `while` loopIn case user enters any value which can not be converted to int, it will raise ValueError exception, which will be handled by the except Block and will print the message you mentioned.
Read Python: Errors and Exceptions for detailed information. As per the doc, the try statement works as follows:
- First, the
tryclause (the statement(s) between thetryandexceptkeywords) is executed. - If no exception occurs, the
exceptclause is skipped and execution of thetrystatement is finished. - If an exception occurs during execution of the
tryclause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement. - If an exception occurs which does not match the exception named in the
exceptclause, it is passed on to outertrystatements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
Solution 2:
What I believe is considered the most Pythonic way in these cases is wrap the line where you might get the exception in a try/catch (or try/except) and show a proper message if you get a ValueError exception:
print ("Welcome to August's decimal to binary converter.")
whileTrue:
try:
value = int(input("Please enter enter a positive integer to be converted to binary."))
except ValueError:
print("Please, enter a valid number")
# Now here, you could do a sys.exit(1), or return... The way this code currently# works is that it will continue asking the user for numberscontinueAnother option you have (but is much slower than handling the exception) is, instead of converting to int immediatly, checking whether the input string is a number using the str.isdigit() method of the strings and skip the loop (using the continue statement) if it's not.
whileTrue:
value = input("Please enter enter a positive integer to be converted to binary.")
ifnot value.isdigit():
print("Please, enter a valid number")
continue
value = int(value)
Post a Comment for "Printing Message Rather Than Valuerror In An Integer User Input?"