This is all the further i've gotten.
import math
num_to_convert = int(input("Please enter any intger from 1 and 100:"))
while num_to_convert < 1 or num_to_convert > 100:
num_to_convert = int(input("Sorry that's not an integer from 1 to 100, try again:"))
else:
print("I'm lost!")
I found this but I don't understand whats going on. Maybe some explanation of what's going on would help.
def decimalToBinary(n):
if(n > 1):
# divide with integral result
# (discard remainder)
decimalToBinary(n//2)
print(n%2, end=' ')
CodePudding user response:
It seems like you want to convert an integer which is not a decimal to binary from your code i would write
while True:
try:
value1=input("Integer you want to convert to binary: ")
binaryvalue=(bin(int(value1)))
print (binaryvalue[2:])
except:
print("I did not understand that")
pass
CodePudding user response:
Valuetoconvert=int(input("Number to convert: "))
u = format(Valuetoconvert, "08b")
print(u)
Try this then
CodePudding user response:
See Below:
def toBin(n):
if n < 2:
return str(n)
else:
if n % 2 == 0:
return toBin(n//2) "0"
else:
return toBin(n//2) "1"
Explanation:
This is my sollution which works similar to yours. I hope you know what recursion is otherwise this is going to be difficult to understand. Anyway the algorithm is to devide the number repeatedly by 2 until the number is smaller than 2 cause then you have the sollution right away(base case).
When the current number is greater than 2 you check wether it is divisible by 2. If it is even you append a 0 to your string else append a 1. You can try this out on paper to better understand it.