First and last digits
Write a Python program to find the first and last digits of a number.
74351
First digit: 7 Last digit: 1
Approach
- The last digit is
n % 10; remove digits until one is left for the first digit.
Solution
n = 74351last = n % 10first = nwhile first >= 10: first //= 10print("First digit:", first)print("Last digit:", last)First digit: 7 Last digit: 1
Line by line
Keep dropping the last digit until a single digit remains.
Learn the concept
New to this topic? Read the lesson, then come back.