What will be the input for decimalToBinary function

Viewed 36

what is the input for the decimalToBinary function? if I set num =2. How this function works.

def decimalToBinary(num): # num = 2 at the start
"""This function converts decimal number
to binary and prints it"""
if num > 1:       #terminate loop
  decimalToBinary(num // 2) # what this function will give output ? num =2 or 1?
print(num % 2) # what will be the input  values here? num = 1 or 2

decimal number

number = int(input("Enter any decimal number: ")) decimalToBinary(number)

2 Answers

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value.

See the example below.

a = 23

#Built-In function that converts the base 10 (decimal) number to its equivalet in base 2 (Binary) bin_a = bin(a) print(bin_a)

#Again converting the Base 2 (Binary) number in Base 10 (Decimal) equivalent print(int(bin_a, 2)) #Base 2 (Binary)

Furthermore, if you want to create your own function. Here you go.

def decToBin(param_number):
    temp = param_number
    strBinary = ''
    temp_bin = 0

    while temp > 0:
        temp_bin = temp%2
        temp = temp - temp_bin
        temp = temp/2

        strBinary = str(int(temp_bin)) + strBinary
    
    return(strBinary)

val = decToBin(23)
Related