ItSolutionStuff.com

How to Get the First Digit of a Number in Python?

By Hardik Savani • October 30, 2023
Python

Hi Friends,

This article is focused on python get first digit of a number. I would like to share with you how to get first digit of a number in python. I would like to share with you program to find first digit of a number python. This article goes in detailed on first digit of a number in python. follow the below step for find 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 = 43567
  
# Get First Digit from Number
firstDigit = str(number1)[0]
result = int(firstDigit)
    
print(result)

Output:

4

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 = 9658
  
# Get First Digit from Number
firstDigit = number // (10 ** (len(str(number))-1))

print(firstDigit)

Output:

9

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Python Convert String to Float with 2 Decimal Places Example

Read Now →

Python Format Number to 2 Decimal Places Example

Read Now →

How to Sort List Descending in Python?

Read Now →

How to Generate Random Float Numbers in Python?

Read Now →

Python Generate Random Number Between 0 to 1 Example

Read Now →

Python Generate Random Number Between 1 and 10 Example

Read Now →

Python Smallest and Largest Numbers in a List Example

Read Now →

How to Get Smallest Number in List Python?

Read Now →

Python Generate List of Unique Random Numbers Example

Read Now →

How to Find Sum of All Elements in List in Python?

Read Now →

Python List Remove Element by Value Example

Read Now →

Python List Remove Element by Index Example

Read Now →

Python Delete Files with Specific Extension Example

Read Now →

Python Delete Directory if Exists Example

Read Now →