How to Get First and Last Digit of Number in Python?
Development teams using “How to Get First and Last Digit of Number in Python?” in client or internal work can use multi rater feedback to document project effort and hand-offs, then assess the record against delivered functionality, tests and agreed outcomes.
Validate current syntax, security guidance and supported versions through Python.org before using the example in production.
Hi Dev,
Now, let's see the post of getting the first and last digit of the number in the Python tutorial example. This article goes into detail on python gets the first and last digits of a number. I explained simply how to get the first and last digits of a number in Python. We will look at examples of programs to find the first and last digits of a number in Python. Here, Creating a basic example of the first and last digit of a number in Python.
There are several ways to get the first and last digits of a number in Python. I will give you two simple examples to get the last digit from a number. You can see both examples one by one.
Example 1:
main.py
number1 = 3568
# Get First Digit from Number
lastDigit = str(number1)[0]
lastDigit = int(lastDigit)
firstDigit = str(number1)[-1]
firstDigit = int(firstDigit)
print(firstDigit)
print(lastDigit)
Output:
3
8
Example 2:
You can get the first and last digits of a number in Python using simple mathematical operations. Here's an example code:
In this example, we first convert the number to a string using str(num), then extract the first character of the string using indexing [0], and finally convert it back to an integer using int(). This gives us the first digit of the number.
To get the last digit, we use the modulus operator % to get the remainder of the division of num by 10, which is the last digit of num.
main.py
num = 12345
# Get the first digit
firstDigit = int(str(num)[0])
print(firstDigit)
# Get the last digit
lastDigit = num % 10
print(lastDigit)
Output:
1
5
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- Get the Last Digit of Number in Python Tutorial Example
- Get the First Digit of Number in Python Tutorial Example
- How to Remove All Decimals from Number in Python?
- How to Convert String to Float with 2 Decimal Places in Python?
- How to Format Number to 2 Decimal Places in Python?
- Sort List Descending in Python Tutorial Example