Get the First Digit of Number in Python Tutorial Example
Hi Dev,
Now, let's see the post of get the first digit of the number in the Python tutorial example. This article goes in detailed on Python getting the first digit of a number. I explained simply how to get the first digit of a number in Python. We will look at an example of a program to find the first digit of a number Python. Here, Creating a basic example of the first digit of a number in Python.
There are several ways to get the first digit of a number in Python. I will give you two simple examples to get the first digit from a number. You can see both examples one by one.
Example 1:
main.py
number1 = 73567
# Get First Digit from Number
firstDigit = str(number1)[0]
result = int(firstDigit)
print(result)
Output:
7
Example 2:
You can use the modulus operator (%) and division operator (/) in Python to get the first digit of a number.
In this code, we first calculate the length of the number using len(str(number)). Then, we calculate the power of 10 by raising it to the length of the number minus 1. Next, we divide the number by the power of 10, which gives us a number with only the first digit. Finally, we use integer division (//) to get rid of any decimal places and assign the result to the firstDigit variable.
main.py
number =3658
# Get First Digit from Number
firstDigit = number // (10 ** (len(str(number))-1))
print(firstDigit)
Output:
3
- Get Last 2 Digits of Number in Python Tutorial Example
- How to Sum of First and Last Digit of Number in Python?
- How to Get First and Last Digit of Number in Python?
- Get the Last 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