ClosureSum in Python3

Shrayan Bandyopadhyay
2 min readNov 10, 2022

Problem

Create a python program that will sum the digits formed by the first and last number of an integer and will go on until the number ends.

Example

Input = 123456Iteration 1 : 16 | "2345"
Iteration 2 : 25 | "34"
Iteration 3 : 34 | ""
Sum = 16+25+34 = 75
Output = 75

Solution in Python3

We should convert the input to a string in order to perform concatenation. In order to get the output in integer, we need to perform type-conversion.

The default input type in python is string. So if you are using input() then it will automatically convert the numbers into string.

num = str(123456)
n = num
sum_of_joined_digits = 0
while len(num) >= 1:
#c=len(num)
first_digit = num[0]
last_digit = num[-1]
num = num[1:-1]
joined_digits = first_digit + last_digit
int_joined_digits = int(joined_digits)
sum_of_joined_digits = int(sum_of_joined_digits) + int_joined_digits
print (sum_of_joined_digits)

Code Visualization

You can see the output as 75 as predicted earlier.

Note : If you want to throw an error if anything other than a number is entered then use the following code:

try: 
num = input()
n = num
sum_of_joined_digits = 0
while len(num) >= 1:
#c=len(num)
first_digit = num[0]
last_digit = num[-1]
num = num[1:-1]
joined_digits = first_digit + last_digit
int_joined_digits = int(joined_digits)
sum_of_joined_digits = int(sum_of_joined_digits) + int_joined_digits
print (sum_of_joined_digits)
except ValueError:
print("Invalid input!")

--

--