Python Program to Find Sum of First and Last Digit

This article is created to cover some programs in Python that find and prints sum of first and last digit of a number entered by user at run-time. For example, if user enters a number say 2493, then the output will be first digit (2) + last digit (3) or 5.

Sum of First and Last digit of a Number

The question is, write a Python program that prints sum of first and last digit of a given number. The program given below is answer to this question:

print("Enter a Number: ")
num = int(input())

count = 0
while num!=0:
    if count==0:
        last = num%10
        count = count+1
    rem = num%10
    num = int(num/10)

sum = rem + last
print("\nSum of first and last digit =", sum)

The snapshot given below shows the initial output produced by above Python program:

python sum of first and last digit

Now supply the input say 1203 as number and press ENTER key to find and print sum of first (1) and last (3) digit of given number like shown in the snapshot given below:

sum of first last digit python

What if user enters an invalid input ?

To handle the things, when user enters an invalid input. That is, the program given below produces an error message, when user doesn't enters an integer input.

print("Enter a Number: ", end="")
try:
    num = int(input())

    count = 0
    while num != 0:
        if count == 0:
            last = num % 10
            count = count + 1
        rem = num % 10
        num = int(num / 10)

    print("\nFirst Digit (", rem, ") + Last Digit (", last, ") =", rem + last)

except ValueError:
    print("\nInvalid Input!")

Here is its sample run with user input, 122345:

find sum of first and last digit of number python

Here is another sample run with user input codescracker:

python sum of first and last digit

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!