Square Every Digit of a Number in Python?
Question:
Square Every Digit of a Number in Python?
if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
write a code but this not working.
def sq(num):
words = num.split() # split the text
for word in words: # for each word in the line:
print(word**2) # print the word
num = 9119
sq(num)
Answers:
We can use list to split every character of a string, also we can use "end" in "print" to indicate the deliminter in the print out.
def sq(num):
words = list(str(num)) # split the text
for word in words: # for each word in the line:
print(int(word)**2, end="") # print the word
num = 9119
sq(num)
Alternatively
return ''.join(str(int(i)**2) for i in str(num))
def sq(num):
z = ''.join(str(int(i)**2) for i in str(num))
return int(z)
We can also support input of negative numbers and zeros. Uses arithmetic operators (% and //) for fun.
def sq(num):
num = abs(num) #Handle negative numbers
output = str((num % 10)**2) #Process rightmost digit
while(num > 0):
num //= 10 #Remove rightmost digit
output = str((num % 10)**2) + output #Add squared digit to output
print(output)
def square_digits(num):
num = str(num)
result = ''
for i in num:
result += str(int(i)**2)
return int(result)
var = square_digits(123)
print(var)
number=str(input("Enter the number :"))
def pc(number):
digits = list(number)
for j in digits:
print(int(j)**2,end="")
pc(number)
You can try this variant:
def square_digits(num):
return int(''.join(str(int(i)**2) for i in str(num)))
Square Every Digit of a Number in Python?
if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
write a code but this not working.
def sq(num):
words = num.split() # split the text
for word in words: # for each word in the line:
print(word**2) # print the word
num = 9119
sq(num)
We can use list to split every character of a string, also we can use "end" in "print" to indicate the deliminter in the print out.
def sq(num):
words = list(str(num)) # split the text
for word in words: # for each word in the line:
print(int(word)**2, end="") # print the word
num = 9119
sq(num)
Alternatively
return ''.join(str(int(i)**2) for i in str(num))
def sq(num):
z = ''.join(str(int(i)**2) for i in str(num))
return int(z)
We can also support input of negative numbers and zeros. Uses arithmetic operators (% and //) for fun.
def sq(num):
num = abs(num) #Handle negative numbers
output = str((num % 10)**2) #Process rightmost digit
while(num > 0):
num //= 10 #Remove rightmost digit
output = str((num % 10)**2) + output #Add squared digit to output
print(output)
def square_digits(num):
num = str(num)
result = ''
for i in num:
result += str(int(i)**2)
return int(result)
var = square_digits(123)
print(var)
number=str(input("Enter the number :"))
def pc(number):
digits = list(number)
for j in digits:
print(int(j)**2,end="")
pc(number)
You can try this variant:
def square_digits(num):
return int(''.join(str(int(i)**2) for i in str(num)))