Reverse an Integer in Python
String slicing provides a readable introduction to digit reversal.
What is Reverse an Integer?
String slicing provides a readable introduction to digit reversal.
Reverse the decimal digits of an integer.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
number = 12345
# Reverse the digit text, then convert it back to an integer.
reversed_number = int(str(number)[::-1])
print(reversed_number)
Expected output
54321
How it works
The slice reads all digit characters from the end to the beginning.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.