Python code to get the first digit of a number

5976

 

There are many techniques to find the first digit of a number using Python language. We will discuss it using typecast, iteration method, list method and math function.

Python code to print the first digit of a number using typecast

Code:

num = int(input("Enter number: "))
num_str = str(num)
print(num_str[0])

 

Output:

Enter number: 34501
3

 

Python code to print the first digit of a number using iteration

Code:

num = int(input("Enter number: "))
first_digit_of_number = num

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

print(first_digit_of_number)

Output:

Enter number: 45621
4

 

Python code to print the first digit of a number using map()

Code:

num = int(input("Enter number: "))
digits_of_number= list(map(int, str(num)))
print(digits_of_number[0])

 

Output:

Enter number: 45621
4

 

Python code to print the first digit of a number using math function

Code:

import math
num = int(input("Enter any Number: "))
c_total = int(math.log10(num))
first_digit_of_number = int(num // math.pow(10, c_total))
print(first_digit_of_number)

 

Output:

Enter any Number: 9012
9