""" Converts a binary number to a decimal number. February 18th, 2019. Sébastien Lavoie """ def bin_to_dec(number): """Algorithm that converts a binary number to a decimal number. Receives and returns a string.""" # get the index of power of first digit # e.g. 1001 → first index power is 3 (2^3) first_power = len(number) - 1 total = 0 # initialize variable to store final result for index, char in enumerate(number): if char == '1': total += 2 ** (first_power - index) return total if __name__ == '__main__': # retrieve binary number from input as string to parse BIN_NUM = input() # pass binary number to algorithm and store the result RESULT = bin_to_dec(BIN_NUM) # print the solution to the console print(RESULT)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question