+ 2
Basically, the trunc function takes the decimal off of a number. In order to get the tens place, you can divide a two-digit number by 10 and take off the decimal.
This will not work with three-digit numbers unless you add another variable to get the extra digit.
from math import trunc
number = int(input("Enter a three-digit number:"))
x = trunc(number / 100)
y = trunc((number % 100) / 10)
z = number % 10
sum = x + y + z
print(sum)
+ 6
You can also parse the digits by using a loop, as follows:
n = 2018
sum = 0
while(n != 0):
r = n%10
sum += r
print(str(r) + " is added to sum => " + str(sum))
n //= 10
print("Sum of digits from 2018 = " +str(sum))
@Colin's answer is more elegant however, either way, your choice : )
Hth, cmiiw
+ 2
Yes! There is an easy way to do that:
from math import trunc
number = int(input("Enter a two-digit number:"))
x = trunc(number / 10)
y = number % 10
sum = x + y
print(sum)