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.
1# Take 4-digit number2num = int(input("Enter a 4-digit number: "))34# Extract first and last digits5first_digit = num // 10006last_digit = num % 1078# Check if equal9if 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
Read the four-digit input.
- 2
Compute num // 1000 and num % 10.
- 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.
๐Related Content
- ๐
Phase 1 - Learn Concepts
Review Phase 1 concepts and explanations
- ๐
Phase 1 - Quiz
Test your Phase 1 understanding with quiz questions
- ๐ป
Phase 1 - All Practice Problems
Explore all practice problems for Phase 1
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum