Last active
August 29, 2015 14:13
-
-
Save HoughIO/cd4203708ef78e9aaf42 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Name: Graham Hough | |
#Date due: 1/23/15 | |
#Purpose: to show how to convert numbers to and from binary | |
def main(): | |
user_num = input('Please type the corrisponding number: \n1. Binary to deciaml\n2. Decimal to binary\n') | |
if user_num == '1': | |
x = input('what is the number you want to convert?') | |
result1 = binary_to_dec(x) | |
print('The converted number is ' + str(result1)) | |
elif user_num == '2': | |
try: | |
x = int(input("What is the base 10 number you would like to convert? ")) | |
except ValueError: | |
print("That's not an int!") | |
result2 = dec_to_binary(x) | |
print('The converted number is ' + result2) | |
def binary_to_dec(a): | |
dec = int(a, 2) | |
return dec | |
def dec_to_binary(a): | |
end = False | |
temp = a | |
binary_string = '' | |
while end != True: | |
print(str(temp) + ' /2 = ' + str((temp/2))) | |
temp = temp/2 | |
if temp % 1 == 0: | |
binary_string += '0' | |
print('\t\t\tRemainder: 0') | |
else: | |
binary_string += '1' | |
temp = temp - .5 | |
print('\t\t\tRemainder: 1') | |
if temp < 0.6: | |
end = True | |
result = str(binary_string[::-1]) | |
return result | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment