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)
ValueError
ValueError
for i in value:
if not (i in "1234567890"):
value
int
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)