Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check First and Last Digits Equal

Read the first and last digits of a four-digit integer with Python. Beginners compare place values using floor division, remainder, and one equality condition.

IntermediatePhase 1 - Level 3: Math and Number LogicExample 3 of 10
check-first-and-last-digits-equal.py
1# Take 4-digit number
2num = int(input("Enter a 4-digit number: "))
3
4# Extract first and last digits
5first_digit = num // 1000
6last_digit = num % 10
7
8# Check if equal
9if first_digit == last_digit:
10 print("First and last digits are equal")
11else:
12 print("First and last digits are not equal")

Output

Enter a 4-digit number: 1231
First and last digits are equal

Enter a 4-digit number: 1234
First and last digits are not equal

In this one

  • Use thousands-place division
  • Extract a units digit
  • Compare outer positions

How it works

  1. 1

    Read the four-digit input.

  2. 2

    Compute num // 1000 and num % 10.

  3. 3

    Compare those values and print the result.

Edge cases

Does 9999 pass?

Does 9999 pass?

Yes. Its first and last digits are both nine.

Does 12345 fit this algorithm?

Does 12345 fit this algorithm?

No. num // 1000 gives 12, not the leading digit alone.

What's going on

For a positive four-digit number, dividing by one thousand and discarding the remainder gives the first digit. Taking remainder ten gives the last digit.

The equality test ignores the two inside positions. Input 1231 passes because both outer digits are one. This fixed-place technique is not a general first-digit algorithm: a five-digit number divided by one thousand gives two digits.

Does 9999 pass? Yes. Its first and last digits are both nine.

Does 12345 fit this algorithm? No. num // 1000 gives 12, not the leading digit alone.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which expression extracts the last digit?

Pick an answer to check it.

Question 2

Does 9999 pass?

Pick an answer to check it.

Questions people ask

Does 9999 pass?

Yes. Its first and last digits are both nine.

Does 12345 fit this algorithm?

No. num // 1000 gives 12, not the leading digit alone.

Which expression extracts the last digit?

num % 10.