This is my sample code for converting a binary number to a decimal number with steps
def binaryToDecimal(b2d):
i = len(b2d) - 1
total = 0
for x in b2d:
print("%d x 2^%d = %d" % (x, j, (x * 2 ** j)))
total += (x * 2 ** j)
j -= 1
print("The decimal conversion would be", total)
binaryToDecimal([int(n) for n in input('Enter value: ')]) # this converts user input into a list
I would like it to show an error message if the user had inputted numbers other than 1's and 0's.
This is my take on it:
def binaryToDecimal(b2d):
if 1 and 0 in b2d:
*<proceed with program>*
else:
print("ERROR")
As for the problem with the top example, it works fine in some cases but in order for the program to proceed, both numbers 1's and 0's has to be inputted. Therefore, inputting '11' gives an error. And for some numbers like '0222' it would still proceed with the program even when there's a 2 in the list.