Reputation: 17
For example, if we run 5678 through the function, 25364964 will come out. So I wrote a code like this.
number = 5678
for ch in str(number):
print (int(ch)**2, end="")
And got the correct output.
25364964
However, if I put this code under a function, the expected result isn't showing up.
def square_every_number(number):
for ch in str(number):
return ((int(ch)**2))
print(square_every_number(5678))
Output:
25
I'm getting only the square for the first digit.
Upvotes: 0
Views: 2074
Reputation: 119
You were returning after squaring the first character, please try squaring every character and form the resultant number in your function and return the final result as below.
def sq_every_num(number):
result = ''
for ch in str(number):
result += str(int(ch) ** 2)
return int(result)
output:
result = sq_every_num(5678)
print result, type(result)
25364964 < type 'int'>
Upvotes: 0
Reputation: 6058
You are returning on the first loop. You should build up your result and return that.
def square_every_number(number):
res = ''
for ch in str(number):
res = res + str(int(ch)**2)
return res
Or a shorter function:
def square_every_number(number):
return ''.join(str(int(ch)**2) for ch in str(number))
Upvotes: 6