In this tutorial we will see python code to extract the first and last digit of a number.
Python Code to Extract the First and Last Digit of a Number
Here's an example Python code to get the first and last digit of a number:
num = int(input("Enter a number: "))
first_digit = num
while first_digit >= 10:
first_digit //= 10 # get the first digit
last_digit = num % 10 # get the last digit
print("First digit:", first_digit)
print("Last digit:", last_digit)
In this code, we first ask the user to enter a number. Then, we use a while loop to repeatedly divide the number by 10 until we get the first digit (which is the leftmost digit of the number). We store the first digit in the variable first_digit
. To get the last digit (which is the rightmost digit of the number), we simply take the number modulo 10. We then print out the first and last digit separately using the print()
function.