Site icon Machine Learning Projects

Python Program to Reverse a Number – 2023

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Reverse a Number.

Example 1: Reverse a Number using a while loop

num = int(input('Enter a number -> '))
reversed_num = 0

while num != 0:
    digit = num % 10
    reversed_num = reversed_num * 10 + digit
    num //= 10

print("Reversed Number: " + str(reversed_num))

Output

Enter a number -> 7042
Reversed Number: 2407

curr = 7042 ; digit = 0 ; reverse = 0
curr = 704 ; digit = 2 ; reverse = 0 x 10 + 2 = 2
curr = 70 ; digit = 4 ; reverse = 2 x 10 + 4 = 24
curr = 7 ; digit = 0 ; reverse = 24 x 10 + 0 = 240
curr = 0 ; digit = 7 ; reverse = 240 x 10 + 7 = 2407

Example 2: Using String slicing

num = int(input('Enter a number -> '))
print(str(num)[::-1])

Output

Enter a number -> 7042
2407

Check out our other python programming examples

Exit mobile version