August Williams August Williams - 1 month ago 8
Python Question

Printing message rather than valuerror in an integer user input?

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?

Answer

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)