""" Converts a decimal number to a binary number. February 18th, 2019. Sébastien Lavoie """ def dec_to_bin(number): """Algorithm that converts a decimal number to a binary number. Receives an integer and returns a string.""" if number == 0: # if number is 'zero', the answer is 'zero' return 0 remainders = [] # list that stores the remainders # iterate over the initial given decimal and divide it by two # until it gets to 'zero'. At each step, add the remainder in # the above list while number > 0: remainders.append(number % 2) number = number // 2 # reverse the list of remainders, as the first remainder is the # right most digit in the answer remainders.reverse() # concatenate all the digits from the list of remainders from left # to right to display the final binary number answer = '' for digit in remainders: answer += str(digit) # give the answer back to the script return answer if __name__ == '__main__': # retrieve decimal number from input as integer DEC_NUM = int(input()) # pass decimal number to algorithm and store the result RESULT = dec_to_bin(DEC_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