In my other blog post ‘Binary to Decimal’, I realized what if I had put in a different number than 1 and 0. I tried putting a 2 and the code still worked. So I will be sharing an updated version, so that you can only put in either 1 or 0. Else there will be an error.
# make a new function
def bintodeci(num):
reverse = len(num) -1
exp = 0
total = 0
for index in range(reverse, -1, -1):
# if each number is either 0 or 1 else it'll print out an error.
if num[index] in '01':
total += int(num[index]) * (2**exp)
exp += 1
else:
print("Error: Invalid binary number")
return None
# return the value
return total
# In case I want to import it
if __name__ == '__main__':
print(f'The variable __name__ is {__name__}')
answer = bintodeci("111")
print(answer)