alex prezmon - 2 months ago 34

Python Question

I'm studying algorithms. The exercise consist in put a number of 2 digits (between 10 and 99) and then do the addition of the two digits. I made it in python and it works, but my teacher said that there's another way to do it without the conversions that i'm using. Can you help me? Is there a better way? Thanks.

`for i in range(5):`

add = 0

num = input("Number: ")

num = int(num)

if num > 9 and num < 100:

num = str(num)

add = int(num[0]) + int(num[1])

print("The addition of the two digits is: " + str(add))

else:

print("It is not a two digit number.")

Answer

I think he meant:

```
(num // 10) + (num % 10)
```

With `num // 10`

you perform an integer division with 10. But this is the first digit. With `num % 10`

you get the remainder of the division, which is the second digit. For example:

```
>>> 67 // 10
6
>>> 67 % 10
7
```

The most succinct way must be:

```
sum(divmod(num, 10))
```

because `divmod`

performs the integer division with 10 and finding the remainder at the same time. So with `sum`

we get the sum of those two numbers. For example:

```
>>> divmod(67, 10)
(6, 7)
>>> sum(divmod(67, 10))
13
```