write a python program to find first and last digit of a number

Hi Guys, welcome to my blog in this article you will learn about how to Write A Python Program To Find First And Last Digit Of A Number

 

Title : 

Write A Python Program To Find First And Last Digit Of A Number



write a python program to find first and last digit of a number


 

Description : 

Hi guys in this article you will learn about a python program that takes a integer number as input and finds the first and last digit of the given input number Let's take a number variable and use the input function call to ask the user to enter a number and convert it into integer using the type conversion. Now take two variables first and last to store the first and last digit of a given input number. Copy the contents of number to the first variable, in order to get the last digit just initialize the last variable by modulating the given number by 10, we have found the last digit


    

number = int(input("Enter a number: "))

first = number
last = number % 10

    


Now in order to find the first digit of a number obviously we know it is a single digit so let us use a while loop until the first variable becomes a single digit we keep performing true division Until the first variable becomes a single digit. Finally use the print function called to print the first and last digit of a given number and exit the program.


    

while first > 9:
   first //= 10

print(f"The first digit of a number is: {first}")
print(f"The last digit of a number is: {last}")


    




Complete Python Code : 


    

number = int(input("Enter a number: "))

first = number
last = number % 10

while first > 9:
   first //= 10

print(f"The first digit of a number is: {first}")
print(f"The last digit of a number is: {last}")


    

 

 

Output : 


    
Enter a number: 5686
The first digit of a number is: 5
The last digit of a number is: 6

    

 

Output : 


    
Enter a number: 12345678
The first digit of a number is: 1
The last digit of a number is: 8

    



Conclusion :

The above Python program is only applicable for the integer type variable inputs. if the non integer values are given as an input for example float and complex numbers so it won't be printing the first and last digit. To print the first and last digit of a non-integer number like a complex number you should be using the string indexing method and try to print the first and last digit of a number. Comment it down below if you have any query is regarding the above Python program

 

Post a Comment

0 Comments