7. What is the output of the following?
What will strange(1230) return?
def strange():
k = 0
while j > 0:
k = 10 + k + j % 10
j =j // 10
return k
Answers
Given:
def strange():
k = 0
while j > 0:
k = 10 + k + j % 10
j =j // 10
return k
print(strange(1230))
Output:
TypeError: strange() takes 0 positional arguments but 1 was given
Correct Question:
def strange(j):
k = 0
while j > 0:
k = 10 * k + j % 10
j = j // 10
return k
print(strange(1230))
Output:
321
Explanation:
j = 1230
k = 0
j j > 0 k = 10 * k + j % 10 j = j // 10
1230 True k = 10 * 0 + 1230 % 10 j = 1230 // 10
k = 0 + 0 j = 123
k = 0
123 True k = 10 * 0 + 123 % 10 j = 123 // 10
k = 0 + 3 j = 12
k = 3
12 True k = 10 * 3 + 12 % 10 j = 12 // 10
k = 30 + 2 j = 1
k = 32
1 True k = 10 * 32 + 1 % 10 j = 1 // 10
k = 320 + 1 j = 0
k = 321
0 False
The final value of k is 321.
So, the function will return 321.
Therefore, the output is 321.