import time def playAgain(): print('Do you want to convert another number?') return input().lower().startswith('y') def showInstructions(): print(''' Binary is amazing. It is a base 2 system. 2^0 = 1 2^1 = 2 2^2 = 4 2^3 = 8 2^4 = 16 2^5 = 32 2^6 = 64 2^7 = 128 76543210 Those are the 8 bits we are working with. Each will be replaced with a 1 or a 0 depending on whether we need its number to create the sum. 200 is our example. 200 = 128 + 64 + 8 1×2^7 + 1×2^6 + 0x2^5 + 0x2^4 + 1×2^3 + 0x2^2 + 0x2^1 + 0x2^0 So in binary, 200 is 11001000 Now you try another number and check your answer with this program.''') input() print() while True: print('Would you like to view the explanation?') if input().lower().startswith('y'): showInstructions() print('I can convert numbers to 8-bit binary code.') print('Enter a number less than or equal to 255.') theirNumber = input() if theirNumber.isdigit(): if int(theirNumber) > 255: print('Please, enter a number less than or equal to 255.') theirNumber = input() if int(theirNumber) >= 128: D7 = 1 theirNumber = abs(int(theirNumber) - 128) else: D7 = 0 if int(theirNumber) >= 64: D6 = 1 theirNumber = abs(int(theirNumber) - 64) else: D6 = 0 if int(theirNumber) >= 32: D5 = 1 theirNumber = abs(int(theirNumber) - 32) else: D5 = 0 if int(theirNumber) >= 16: D4 = 1 theirNumber = abs(int(theirNumber) - 16) else: D4 = 0 if int(theirNumber) >= 8: D3 = 1 theirNumber = abs(int(theirNumber) - 8) else: D3 = 0 if int(theirNumber) >= 4: D2 = 1 theirNumber = abs(int(theirNumber) - 4) else: D2 = 0 if int(theirNumber) >= 2: D1 = 1 theirNumber = abs(int(theirNumber) - 2) else: D1 = 0 if int(theirNumber) >= 1: D0 = 1 theirNumber = abs(int(theirNumber) - 1) else: D0 = 0 print(str(D7) + str(D6) + str(D5) + str(D4) + str(D3) + str(D2) + str(D1) + str(D0)) else: print('That is not a number.') if not playAgain(): print('Ok, maybe another time. See you then!') time.sleep(5) break
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