问题
I have a decimal to binary converter as seen below:
print ("Welcome to August's decimal to binary converter.")
while True:
value = int(input("Please enter enter a positive integer to be converted to binary."))
invertedbinary = []
initialvalue = value
while value >= 1:
value = (value/2)
invertedbinary.append(value)
value = int(value)
for n,i in enumerate(invertedbinary):
if (round(i) == i):
invertedbinary[n]=0
else:
invertedbinary[n]=1
invertedbinary.reverse()
result = ''.join(str(e) for e in invertedbinary)
print ("Decimal Value:\t" , initialvalue)
print ("Binary Value:\t", result)
The user input is immediately declared as an integer so anything other than numbers entered terminates the program and returns a ValueError
. How can I make it so a message is printed instead of the program terminating with a ValueError
?
I tried taking the method I used from my binary to decimal converter:
for i in value:
if not (i in "1234567890"):
Which I soon realised won't work as value
is an integer rather than a string. I was thinking that I could leave the user input at the default string and then later convert it to int
but I feel like this is the lazy and crude way.
However, am I right in thinking that anything I try to add after the user input line will not work because the program will terminate before it gets to that line?
Any other suggestions?
回答1:
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.")
while True:
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 numbers
continue
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.
while True:
value = input("Please enter enter a positive integer to be converted to binary.")
if not value.isdigit():
print("Please, enter a valid number")
continue
value = int(value)
回答2:
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.
来源:https://stackoverflow.com/questions/40224243/printing-message-rather-than-valuerror-in-an-integer-user-input