How do you reverse a number in Python using slicing?

To reverse a number in Python using slicing, you can convert the number to a string and then use slicing to reverse the string. Here is an example:

# Function to reverse a number using slicing
def reverse(num):
  # Convert the number to a string
  num_str = str(num)

  # Reverse the string using slicing
  reversed_str = num_str[::-1]

  # Convert the reversed string back to an integer and return it
  return int(reversed_str)

# Test the function
print(reverse(12345))

The above python program to reverse a number using slicing defines a function reverse() that takes an integer num as input and returns the reversed version of the number. The function first converts the number to a string using the str() function, and then uses slicing to reverse the string. The reversed string is then converted back to an integer using the int() function and returned.

The function is then tested by calling it with the input 12345. The output should be 54321, which is the reversed version of the input number.

Leave a Comment