New to python so I guess this is a newbie question.
I have a simple program that take input (a number) from the user and send it to my function that converts the input to it's binary form. The code works but the function prints on a new line for each 1 or 0 which gives a vertical output. I want to change how the output is printed so that it prints horisontal, on one line. I have one restriction, I can't use "return" in the function. I hope someone can help me with this!
Current output form:
Looking for output like this:
Code-section where the function is called:
if inputvalue < 256:
print("The number", inputvalue,"fits in one byte and in binary form: ");
dec2bin(inputvalue, 8)
elif inputvalue > 256:
print("The number", inputvalue, "fits in one word (16-bit) and in binary form: ");
dec2bin(inputvalue, 16)
The function:
def dec2bin(value, number_of_digits):
while number_of_digits > 0:
binaryvalue = 2**(number_of_digits -1)
if value >= binaryvalue:
print("1");
value = value - binaryvalue;
else:
print("0");
number_of_digits = number_of_digits -1;
CodePudding user response:
I might rather use a variable in the dec2bin
function to build the result and print it once it's complete.
def dec2bin(value, number_of_digits):
result = ""
while number_of_digits > 0:
binaryvalue = 2**(number_of_digits -1)
if value >= binaryvalue:
result = "1"
value = value - binaryvalue
else:
result = "0"
number_of_digits = number_of_digits -1
print(result)
Or maybe more common approch - let the function return the result and print it outside.
CodePudding user response:
Adding to my comment, and also handling any case (your code wouldn't work for inputvalue > 65535
), you can use a formatted string:
import math
def dec2bin(value, number_of_digits):
result = ''
while number_of_digits > 0:
binaryvalue = 2**(number_of_digits -1)
if value >= binaryvalue:
result = '1'
value = value - binaryvalue
else:
result = '0'
number_of_digits = number_of_digits -1
return result
inputvalue = -1
while inputvalue < 0:
try:
inputvalue = int(input("Please enter a positive integer: "))
except:
pass
nb_bit = 8
if inputvalue == 0:
pass
else:
while nb_bit <= math.log(inputvalue, 2):
nb_bit = 8
print(f"The number {inputvalue} fits in {nb_bit} bit and in binary form: {dec2bin(inputvalue, nb_bit)}")