Hello, so I have been given a programming exercise that I find tricky and confusing, as I’m learning how to code in Python. I hope I can get some guidance, I have messed around with codeacademy and w3schools trying to figure out what to do.
The task is as follow:
”Write a Python procedure (a function that doesn’t return a value) which converts a given decimal number into binary form and defines how many bits or bytes it can be placed into. Then, write a main program that can take the decimal integer and then calls the procedure with the input as a parameter. You will not use any built-in functions to convert the given decimal number for this task. The final program should only handle positive integers (up to 65 535). If the integer is bigger than 255 the output should be presented in 16 bits, and in 8 bits if smaller than 256.”
My code looks like this:
## start of main program print('Decimal to binary converter.') def dec2bin(val): if val > 1: dec2bin(val // 2) print(val % 2, end = '') ### end of procedure val_in_ok = False val_in = 0 while val_in_ok is False: val_in = int(input("Enter an integer: ")) if val_in > 65535: print('Error: Can’t handle numbers that big. Try again.') elif val_in < 0: print('Error: Can only handle positive integers. Try again.') else: val_in_ok = True if val_in < 256: print('The number', val_in ,'fits into 8 bit is in binary form:' ) dec2bin(val_in) else: print('The number', val_in ,' fits into 8 bit is in binary form:, ') dec2bin(val_in) ## end of program
My issue here is that I can’t get the binary number to be written in 8 or 16 bit.
I.E, if I enter 5 as an integer, I want it to spell out 00000101 instead of just 101 like it does now.
Does any friendly soul have the knowledge on how to proceed?