To understand this example, you should have knowledge of the following Python programming topics:
In this python program, we need to convert a Decimal number to a Binary number. So what is the difference between binary and decimal numbers? A decimal number is a number with base 10, for example, a natural number like 10, etc. A binary number is a number with the base 2. which means a number represented using 1 and 0. the Binary number system is crucial for a programmer as it is a Language that a machine understands called Machine language.
In this python program, we have to convert decimal means from base 10 number to binary, which is base 2. We have to divide the number and display the remainder, and this process has to be continued until the number is 1 or zero.
For example, if you have number 6, then we divide it with 2, and we get 3 and reminder 0 and again divide it with 2, then reminder 1, and finally again a reminder. Hence the binary for 6 is 110. We have to accept a number from the user and save that number in a variable after converting it to an integer using
int. We use a user-defined function in python 'decimalToBinary' and call the function in recursive mode to get the binary result. Recursion is a process that we call a function call itself repeatedly. Let's break the code.
STEP 1: Accept a number from the user using an input function in python programming and convert it to a number using an int datatype.
STEP 2: Call the recursive function and pass the number [value] to the function.
STEP 1: use the def function to define a function in python and add the parameters in the parenthesis.
STEP 2: we have to define the function inside the def function. Use
if the condition to check the user number is greater than 1.
STEP 3: Call the function recursively by dividing the number by two.
STEP 4: Print the number which is the reminder of number mod 2
STEP 5: Use the 'end='' ' to append the remainders to the end of the last result while using a recursive function.
Here we alter the default 'end=' value with no space. for example, we have 'hello' and 'world,' by using ' end= ' ' ' in the print statement, we will get the result as ' Hello world. 'By default, the 'end=' value parameter is ‘\n,’ newline character.
# Function to print binary number using recursion def convertToBinary(n): if n > 1: convertToBinary(n//2) print(n % 2,end = '') # decimal number dec = 34 convertToBinary(dec) print()