Check Palindrome Recursively
Check numeric palindromes with a recursive reverse helper. Students compare an unchanged magnitude with an accumulator result and trace the stopping case.
1def reverse_number(n, rev=0):2 if n == 0:3 return rev4 last_digit = n % 105 rev = rev * 10 + last_digit6 return reverse_number(n // 10, rev)78# Check palindrome9num = int(input("Enter a number: "))10reversed_num = reverse_number(abs(num))11if abs(num) == reversed_num:12 print("Palindrome")13else:14 print("Not a palindrome")
Output
Enter a number: 121 Palindrome Enter a number: 123 Not a palindrome
In this one
- Reuse a recursive reverse
- Preserve a comparison target
- Define sign-ignored palindromes
How it works
- 1
Reverse abs(num) through the accumulator helper.
- 2
Wait for its zero base case to return rev.
- 3
Compare that reverse with abs(num).
Edge cases
Does zero pass?
Does zero pass?
Yes. Both magnitude and reverse are zero.
Does -121 pass?
Does -121 pass?
Yes. The code ignores the sign for this comparison.
What's going on
The helper rebuilds reversed digits in rev while dividing n by ten. Its base case returns the accumulated reverse when no digits remain.
The caller compares that result with abs(num), not with a consumed working argument. Thus -121 passes under a sign-ignored definition. Recursive calls keep stack frames until they return, so large digit counts still have a depth limit.
Does zero pass? Yes. Both magnitude and reverse are zero.
Does -121 pass? Yes. The code ignores the sign for this comparison.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is compared at the end?
Pick an answer to check it.
Question 2
Does zero pass?
Pick an answer to check it.
Questions people ask
Does zero pass?
Yes. Both magnitude and reverse are zero.
Does -121 pass?
Yes. The code ignores the sign for this comparison.
What is compared at the end?
Original magnitude and reversed magnitude.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum