Python Practice › Loop Programs › Program 20

First and last digits

EasyLoop Programs · 20 of 90

Write a Python program to find the first and last digits of a number.

Advertisement
Input
74351
Output
First digit: 7
Last digit: 1

Approach

  1. The last digit is n % 10; remove digits until one is left for the first digit.

Solution

Python
n = 74351last = n % 10first = nwhile first >= 10:    first //= 10print("First digit:", first)print("Last digit:", last)
Output
First digit: 7
Last digit: 1

Line by line

Lines 4-5

Keep dropping the last digit until a single digit remains.

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs

Leave a Comment