This python code's aim is to convert decimal number to binary number. I know I can use int() function in the code but I am not able to determine the process that is happening in the code.
def decimal_to_binary(n):
if(n > 1):
decimal_to_binary(n//2)
print(n % 2 , end='')
print(decimal_to_binary(18))
# The output for it is : 10010None
It is said that when the program enters if condition , it will first the interprete the code inside the if statement so how can it perform the print(n % 2 , end='')simultaneously. According to me, I think this print(n % 2 , end='') will only print one value(0 or 1). To me, it seems recursion and the print statement after the if statement are being interpreted simultaneously.
And secondly, why None is also printed with output?
Noneis the return value ofdecimal_to_binary(18), it is the default return value of functions that don't specify one withreturn. If you don't want to have it printed, just don'tprint()it, just calldecimal_to_binary(18)at the end of your code, this function prints what it has to print itself. The rest of your question is really unclear to me. Anyway: there can't be anything interpreted simultaneously. If you wnat to understand what is going on, take a pencil and a piece of paper and follow the program.decimal_to_binarydoesn't convert decimal to binary: it converts a Pythonintto a binary string representation of thatint. Pythonints are stored in a form of binary, not in decimal. (When you dodecimal_to_binary(18), the conversion from the decimal numeric literal18to the internal binary format actually occurs at parsing time, long beforedecimal_to_binaryis called.)