How do I square every digit of a number in Python
def squares(num):
s = 0
for i in str(num):
y = int(i) * int(i)
s += y
return s
I'm trying to square each digit of a number as shown below. How ever, i'm getting the output as 162 when i pass input as 99 instead of expected output 8181. Any suggestions?
2 Answers
4 years ago by Divya
Since you are adding the integers, it automatically performs addition. If you append the data as a string, you can get the expected output as 8181 like below
def squares(num):
s = 0
for i in str(num):
y = int(i) * int(i)
s += str(y)
return s
4 years ago by Divya
num = input("enter a number to get its square")
s = num ** 2
print(f"the square of {num} is {s}")
1 year ago by Rodaina