Find Sum of First and Last Digit in python

AuthorSumit Dey Sarkar

Pubish Date11 Apr 2023

categoryPython

In this tutorial we will learn how to find sum of first and last digit in python.

 

Find sum of first and last digit in python

Here's we see an example to calculate the sum of the first and last digit of a number in python:

 

num = int(input("Enter a number: "))
first_digit = num
while first_digit >= 10:
    first_digit //= 10  # get the first digit
last_digit = num % 10  # get the last digit
sum = first_digit + last_digit
print("The sum of the first and last digit is:", sum)

In this, firstly ask the user to enter a number. Next, until we reach the first digit, we constantly divide the value by 10 using a while loop (which is the leftmost digit of the number). We store the first digit in the variable first_digit. Simply take the number modulo 10 to obtain the last digit, which is the rightmost digit of the integer. We then add the first and last digit together and store the result in the variable sum. Finally, we print out the result.

Comments 0

Leave a comment