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` loop
In 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
try
clause (the statement(s) between thetry
andexcept
keywords) is executed. - If no exception occurs, the
except
clause is skipped and execution of thetry
statement is finished. - If an exception occurs during execution of the
try
clause, 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
except
clause, it is passed on to outertry
statements; 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 numberscontinue
Another 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?"