[Tutor] Using built-in divmod( ) function
Manprit Singh
manpritsinghece at gmail.com
Sat Oct 3 15:18:25 EDT 2020
Dear sir ,
Consider a problem , where i have to write a program which converts an
integer to its binary equivalent. I have seen so many books following this
approach:
x = int(input("Enter a number"))
b, i = 0, 0
while x != 0:
r = x % 2
b = b + (r * (10**i))
x = x // 2
i = i + 1
print(b)
Upon a user input =10, the value b (or the desired output ) becomes 1010
which is the right answer . Now m y question is why we are not using a
divmod operator in this case ? I would prefer writing the above program in
the following way, using divmod( ) :
x = int(input("Enter a number"))
b, i = 0, 0
while x != 0:
x, r = divmod(x, 2)
b = b + (r * (10**i))
i = i + 1
print(b)
What way should i prefer ? need your suggestions .
Regards
Manprit Singh
More information about the Tutor
mailing list