How to Sum of First and Last Digit of Number in Python?

21-Jun-2023

.

Admin

How to Sum of First and Last Digit of Number in Python?

Hi Dev,

This tutorial shows you how to sum of first and last digits of numbers in Python. I would like to share with you a sum of the first and last digits in python. you can see the sum of the first and last digits in Python. I would like to share with you the Python sum of the first and last digits of the number. Alright, let’s dive into the steps.

There are several ways to sum the first and last digits of numbers in Python. Here's an example code in Python to find the sum of the first and last digits of a given integer:

Example 1:


main.py

number1 = 356

# Get First Digit from Number

lastDigit = str(number1)[0]

lastDigit = int(lastDigit)

# Get Last Digit from Number

firstDigit = str(number1)[-1]

firstDigit = int(firstDigit)

sum = firstDigit + lastDigit

print(sum)

Output:

9

Example 2:

main.py

num = int(input("Enter an integer: ")) # get input integer

# convert integer to string to access individual digits

num_str = str(num)

# get the first and last digits

first_digit = int(num_str[0])

last_digit = int(num_str[-1])

# calculate the sum of the first and last digits

sum = first_digit + last_digit

print("The sum of the first and last digits of", num, "is", sum)

In this code, we first prompt the user to input an integer. We then convert the integer to a string so that we can access the individual digits. We get the first digit using num_str[0] and the last digit using num_str[-1]. Finally, we add the first and last digits and store the result in the variable sum, which we then print out.

I hope it can help you...

#Python