def intToBin(n):
if n == 0:
return 0
elif n == 1:
return 1
elif n > 1:
return ((n % 2 10 * intToBin((n/2))))
a = 6
b = intToBin(a)
print(b)
CodePudding user response:
You need to pass int(n/2) into function because if n/2 is floating it will cause an error in code when the value is less than 1. see below solution
def intToBin(n):
if n == 0:
return 0
elif n == 1:
return 1
elif n > 1:
return ((n % 2 10 * intToBin(int(n/2))))
a = 6
b = intToBin(a)
print(b)
OUTPUT :
110
CodePudding user response:
Your code:
def intToBin(n):
if n == 0:
return 0
elif n == 1:
return 1
elif n > 1:
return ((n % 2 10 * intToBin((n/2))))
a = 6
b = intToBin(a)
print(b)
In python3, n/2
is a float division operation. So in recursive call, a float is being passed. Now when this float is less than 1, there is no if-else
block that satisfies the condition, hence the function returns None. The multiplication of 10 with None from the recursive call results in error.
For debugging and better understanding, print n:
def intToBin(n):
print(n)
...rest of your code
which outputs:
6
3.0
1.5
0.75
Traceback (most recent call last):
File "zz.py", line 11, in <module>
b = intToBin(a)
File "zz.py", line 8, in intToBin
return ((n % 2 10 * intToBin((n/2))))
File "zz.py", line 8, in intToBin
return ((n % 2 10 * intToBin((n/2))))
File "zz.py", line 8, in intToBin
return ((n % 2 10 * intToBin((n/2))))
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
To fix:
As answered above, either use int(n/2)
or n//2
or have a default base or return case of the function.