Reputation: 25
N=int(input('enter a number'))
sum=0
for digit in str(N):
sum=sum+(int(digit))**2
print(sum)
This code works totally fine with positive numbers but How do I make it work for negative numbers too?
Upvotes: 2
Views: 1494
Reputation: 12425
Use re.findall
to find digits:
import re
num = int(input('Enter a number: '))
sum = 0
for digit in re.findall(r'\d', str(num)):
sum = sum + (int(digit))**2
print(sum)
You can also use a more compact and more Pythonic list comprehension:
sum_sq = sum([int(i)**2 for i in re.findall(r'\d', str(num))])
Finally, the initial conversion of the input to int
and subsequent casting of it back to str
is not needed. Putting it all together:
import re
num = input('Enter a number: ')
sum_sq = sum([int(i)**2 for i in re.findall(r'\d', num)])
print(sum_sq)
Upvotes: 1
Reputation: 782166
Convert the input to positive with abs()
.
N=abs(int(input('enter a number')))
total=0
for digit in str(N):
total=total+(int(digit))**2
print(total)
Upvotes: 1
Reputation: 23174
You could skip characters that are not digits.
N = input('enter a number')
total = 0
for digit in [int(d) for d in N if d.isdigit()]:
total = total + digit**2
print(total)
(note: I also removed the unnecessary conversion of the input at the beginning, but maybe you want an error to be raised if it is not a whole number. In this case, just put it back and replace N
in the list comprehension by str(N)
)
Upvotes: 0