0

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.

Ramkumar G
  • 17
  • 1
  • 7

2 Answers2

6

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))
Dan D.
  • 73,243
  • 15
  • 104
  • 123
Jim Wright
  • 5,905
  • 1
  • 15
  • 34
0

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'>
satyakrish
  • 119
  • 5
  • Thanks! I'm afraid there still appears to be unformatted code and there's no expansion of why OP's code didn't work. – Richard Jan 19 '18 at 02:26