Python Forum

Full Version: Converting Decimal to Binary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.
My instructor gave us this code to understand. I think I understand what each line does except one line below in bold. Will someone please explain what 'result[0:-p]' is supposed to do for this code? I've commented it out several times and it appears to not affect the outcome. What is this piece of code telling me?

p.s. Thank you all who are out there helping me with questions. You have helped me understand Python much more. V/r Pete



x = float(input('Enter a decimal number between 0 and 1'))
p = 0
count=0
while ((2**p)*x)%1 != 0:
    print('Remainder = '+ str((2**p)*x - int((2**p)*x)))
    p+=1
    count+=1
    
num=int(x*(2**p))
result = ''
if num == 0:
    result = '0'
    
while num > 0:
    result = str(num%2)+result
    print("this result", result)                        
    num = num//2
for i in range (p - len(result)):
    result = '0' + result
    print("hola",result)                                
result = result[0:-p] + '.'  + result[-p:]  #this is the line in question

print("result[0:-p]",result[0:-p])                      
print("result[-p]",result[-p])                          
print("count=",count)                                   
print('The binary representation of the decimal ' + str(x) + ' is ' + str(result))
print("length of binary number is:",len(result))
This line's effect is to add a dot in result before the p last characters.