search
HomeBackend DevelopmentPython TutorialPython program to find sum of first and last numbers

Python program to find sum of first and last numbers

Sep 13, 2023 am 11:17 AM
numberturn upFirstthe last oneandpython program

Python program to find sum of first and last numbers

In this article, the given task is to add the first and last digits of an integer. Now integers can be very small or very large. Therefore, these plans will be divided into two parts. First, we need to find how big this integer is and then get the first number from it. The second part is to get the last number from the given integer, this can be easily done by dividing the number by ten and finding the remainder. In this Python article, we show how to add the first and last digits of an integer using four different examples.

In the first example, use repeated division by 10 to get the number of digits in an integer. In Example 2, math.log10() is used to get the number of digits of an integer. In Example 3, the integer is converted to a string to find its length; in Example 4, the integer is first converted to a string and then the index values ​​0 and -1 are used to get the first and last numbers. Then add the first and last numbers to get the result.

Example 1: Find the number of numbers by using repeated division to find the sum of the first and last digits of an integer.

algorithm

Step 1 - Write a countDigits function to count the number of digits in an integer.

Step 2 - Use the repeated division method.

Step 3 - Now divide the integer by 10**count to get the first number.

Step 4 - Get the last number by dividing by 10 and taking the remainder.

Step 5 - Add the first and last numbers.

Step 6 - Do this for numbers of different lengths given in the array.

Step 7 - Print the output.

The Chinese translation of

Code

is:

code

listofnumbers =[881234,954321, 7178952, 20033, 459, 20069]
import math
#define function
def countDigits(thenumber):
   count=0
   while thenumber != 0:
      thenumber //= 10
      count += 1
   return count

#Use for loop
for item in listofnumbers:
   c=countDigits(item)

   firstnum=math.floor(item/10**(c-1))
   lastnum=item%10
   total=firstnum+lastnum

   print("\nThe Given number is: " , item)
   print("The first digit is ", firstnum)
   print("The last digit is ", lastnum)
   print("The sum of first and the last digit is " , total)

Output - Example 1

Run the python file in the command window

Open the cmd window. Check the output in cmd window.

The Given number is:  881234
The first digit is  8
The last digit is  4
The sum of first and the last digit is  12

The Given number is:  954321
The first digit is  9
The last digit is  1
The sum of first and the last digit is  10

The Given number is:  7178952
The first digit is  7
The last digit is  2
The sum of first and the last digit is  9

The Given number is:  20033
The first digit is  2
The last digit is  3
The sum of first and the last digit is  5

The Given number is:  459
The first digit is  4
The last digit is  9
The sum of first and the last digit is  13

The Given number is:  20069
The first digit is  2
The last digit is  9
The sum of first and the last digit is  11 

Example 2: Find the number of digits in a number by using the math.log10 function to find the sum of the first and last digits of an integer.

algorithm

Step 1 - To count the number of digits in an integer, write the countDigits function.

Step 2 - Use the formula math.floor(math.log10(thenumber) 1) in this function.

Step 3 - Now divide the integer by 10**count to get the first number

Step 4 - Divide by 10 and get the remainder to get the last number.

Step 5 - To get the sum, add the first number and the last number.

Step 6 - Use an array with different integers to do this for numbers of different lengths.

Step 7 - Print the sum.

listofnumbers =[1234,54321, 678952, 200, 45, 10069]
#Import the required module
import math
#define function
def countDigits(thenumber):
   return math.floor(math.log10(thenumber) + 1)
#Use for loop to iterate item    
for item in listofnumbers:
   c=countDigits(item)
   firstnum=math.floor(item/10**(c-1))
   lastnum=item%10
   total=firstnum+lastnum
    
   print("\nThe Given number is: " , item)
   print("The first digit is ", firstnum)
   print("The last digit is ", lastnum)
   print("The sum of first and the last digit is " , total) 

Output - Example 2

Run the python file in the command window

Open the cmd window. Check the output in cmd window.

The Given number is:  1234
The first digit is  1
The last digit is  4
The sum of first and the last digit is  5

The Given number is:  54321
The first digit is  5
The last digit is  1
The sum of first and the last digit is  6

The Given number is:  678952
The first digit is  6
The last digit is  2
The sum of first and the last digit is  8

The Given number is:  200
The first digit is  2
The last digit is  0
The sum of first and the last digit is  2

The Given number is:  45
The first digit is  4
The last digit is  5
The sum of first and the last digit is  9

The Given number is:  10069
The first digit is  1
The last digit is  9
The sum of first and the last digit is  10

Example 3: Find the sum of the first and last digits of an integer by converting an int to str and using the len function to find the digits

algorithm

Step 1 - Write a countDigits function to count the number of digits in an integer.

Second step - Inside this function, for the count, first convert the int to str and then get its length.

Step 3 - Now divide the integer by 10**count to get the first number.

Step Four - Get the last number by dividing by ten and getting the remainder.

Step 5 - Now add the first and last number.

Step 6 - Execute this method for all numbers given in the array.

Step 7 - Print the sum.

listofnumbers =[11234,554321, 6789521, 2004, 3455, 60069]
import math
def countDigits(thenumber):
   snum=str(thenumber)
   l=len(snum)
   return l
    
for item in listofnumbers:
   c=countDigits(item)
   firstnum=math.floor(item/10**(c-1))
   lastnum=item%10
   total=firstnum+lastnum
   print("\nThe Given number is: " , item)
   print("The first digit is ", firstnum)
   print("The last digit is ", lastnum)
   print("The sum of first and the last digit is " , total) 

Output - Example 3

Run the python file in the command window

Open the cmd window. Check the output in cmd window.

The Given number is:  11234
The first digit is  1
The last digit is  4
The sum of first and the last digit is  5

The Given number is:  554321
The first digit is  5
The last digit is  1
The sum of first and the last digit is  6

The Given number is:  6789521
The first digit is  6
The last digit is  1
The sum of first and the last digit is  7

The Given number is:  2004
The first digit is  2
The last digit is  4
The sum of first and the last digit is  6

The Given number is:  3455
The first digit is  3
The last digit is  5
The sum of first and the last digit is  8

The Given number is:  60069
The first digit is  6
The last digit is  9
The sum of first and the last digit is  15

Figure 3: Output of Example 3 in the CMD window

Example 4: Find the sum of the first and last digits of an integer by using a string index value to find the first and last digits

algorithm

Step 1 - First convert the integer to a string.

Step 2 - Get the first number using index 0 and convert it back to an integer.

Step 3 - Get the last digit using index -1 and convert it back to an integer.

Step 4 - Add the first and last numbers.

Step 5 - Do this for numbers of different lengths given in the array.

Step 6 - Print the calculated total.

listofnumbers =[12343,543210, 6789529, 9200, 45, 810069]
#Use for loop
for item in listofnumbers:
    snum=str(item)
    firstnum=int(snum[0])
    lastnum=int(snum[-1])
    total=firstnum+lastnum
    print("\nThe Given number is: " , item)
    print("The first digit is ", firstnum)
    print("The last digit is ", lastnum)
    print("The sum of first and the last digit is " , total)

Output - Example 4

Run the python file in the command window

Open the cmd window. Check the output in cmd window.

The Given number is:  12343
The first digit is  1
The last digit is  3
The sum of first and the last digit is  4

The Given number is:  543210
The first digit is  5
The last digit is  0
The sum of first and the last digit is  5

The Given number is:  6789529
The first digit is  6
The last digit is  9
The sum of first and the last digit is  15

The Given number is:  9200
The first digit is  9
The last digit is  0
The sum of first and the last digit is  9

The Given number is:  45
The first digit is  4
The last digit is  5
The sum of first and the last digit is  9

The Given number is:  810069
The first digit is  8
The last digit is  9
The sum of first and the last digit is  17 

The numbers are specified and extracted from an array.

in conclusion

We have given here various methods to show how to add the first and last digits of an integer. Different integers of different lengths are written into an array. Then use different methods on these integers. The methods differ mainly in the method of finding the median of an integer or the method of finding the first and last numbers from it.

The above is the detailed content of Python program to find sum of first and last numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python vs. C  : Pros and Cons for DevelopersPython vs. C : Pros and Cons for DevelopersApr 17, 2025 am 12:04 AM

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

Python: Time Commitment and Learning PacePython: Time Commitment and Learning PaceApr 17, 2025 am 12:03 AM

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment