Python Program to find First Digit of a Number

Write a Python Program to find First Digit of a Number using While Loop, pow, log10, and Functions with an example.

Python Program to find First Digit of a Number using While Loop

This Python program allows users to enter any integer value. Next, this program finds Factors of that number using a While Loop.

# Python Program to find First Digit of a Number

number = int(input("Please Enter any Number: "))

first_digit = number

while (first_digit >= 10):
    first_digit = first_digit // 10

print("The First Digit from a Given Number {0} = {1}".format(number, first_digit))
Python Program to find First Digit of a Number 1

In this python program, number = 984. It means first_digit = 984

First Iteration of the While Loop
while (first_digit >= 10) – It means (984 >= 10) is True
first_digit = first_digit // 10
first_digit = 984 // 10 = 98

Second Iteration
while (98 >= 10)  – Condition is True
first_digit = 98 // 10 = 9

Third Iteration
while (9 >= 10)  – Condition is False. So, it exits from the While Loop, and print 9 as output

Python Program to find First Digit of a Number using Built-in Functions

In this Python program, we are using the building-in functions called math.pow and log10.

import math

number = int(input("Please Enter any Number: "))

count = int(math.log10(number))

first_digit = number // math.pow(10, count)

print("Total number of Digits in a Given Number {0} = {1}".format(number, count))
print("The First Digit from a Given Number {0} = {1}".format(number, first_digit))
Please Enter any Number: 67598
Total number of Digits in a Given Number 67598 = 4
The First Digit from a Given Number 67598 = 6.0

number = 67598

count = log10(number) – This will return 4.67
count = 4

first_digit = 67598 / pow(10, 4) = 67598 / 10000 = 6

Python Program to return First Digit of a Number using Functions

This first digit in a number program is the same as the first example. But this time, we separated the logic by defining a new function called first_digit.

def first_digit(number):
    while (number >= 10):
        number = number // 10
    return number

num = int(input("Please Enter any Number: "))

firstDigit = first_digit(num)

print("The First Digit from a Given Number {0} = {1}".format(num, firstDigit))
Please Enter any Number: 78543
The First Digit from a Given Number 78543 = 7

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.