Cara menggunakan reverse index python

Contents

Table of Contents

  • Python Program to Reverse a Number
  • Example 1: Reverse Number using String slicing
  • Example 2: Reverse Number using While Loop
  • Related Tutorials
  • Reverse a Python Number Using a While Loop
  • Reverse a Python Number Using String Indexing
  • Reverse a Python Number Using a Custom Function
  • How do you reverse a number in a for loop?
  • Can you do a for loop backwards in Python?
  • How do you reverse a list in a for loop Python?
  • How do you reverse input in Python?

  • Introduction
  • Example 1: Reverse Number using String slicing
  • Example 2: Reverse Number using While Loop
  • Summary

Python Program to Reverse a Number

In this tutorial, we will learn different ways to reverse a number.

Some of the possible ways are given in the below list.

  • Convert number to string, Reverse string using slicing, and then Convert string back to number.
  • Use while loop to pop the last digit in iteration and create a new number with popped digits appended to it.

Example 1: Reverse Number using String slicing

In this example, we convert given number to string using str() and then reverse it using string slicing. The reversed string is converted back to int.

If the given input is not a number, we shall print a message to the user.

Python Program

try:
	n = int(input('Enter a number : '))
	reversed = int(str(n)[::-1])
	print(reversed)
except ValueError:
	print('Given input is not a number.')

Output

D:\>python example.py
Enter a number : 635178
871536

D:\>python example.py
Enter a number : asdf
Given input is not a number.

Example 2: Reverse Number using While Loop

In this program we shall use while loop to iterate over the digits of the number by popping them one by one using modulo operator. Popped digits are appended to form a new number which would be our reversed number.

Python Program

try:
	n = int(input('Enter a number : '))
	reversed = 0
	
	while(n!=0):
		r=int(n%10)
		reversed = reversed*10 + r
		n=int(n/10)
		
	print(reversed)
except ValueError:
	print('Given input is not a number.')

Output

D:\>python example.py
Enter a number : 5236
6325

D:\>python example.py
Enter a number : 865474569
965474568

D:\>python example.py
Enter a number : 52dssa
Given input is not a number.

Summary

In this tutorial of Python Examples, we learned how to reverse a number using while loop and string slicing.

  • Python Complex Number – Initialize, Access
  • Python – Factorial of a Number
  • Python String – Find the number of overlapping occurrences of a substring
  • How to Get Number of Elements in Pandas DataFrame?
  • Python Program to Add Two Numbers
  • Python – Largest of Three Numbers
  • Python – Smallest of Three Numbers
  • Python – Check if Number is Armstrong
  • Numpy sqrt() – Find Square Root of Numbers
  • How to Swap Two Numbers in Python?

In this tutorial, you’ll learn how to use Python to reverse a number. While this is similar to learning how to reverse a string in Python, which you can learn about here, reversing a number allows us to use math to reverse our number. You’ll learn how to use a Python while loop, string indexing, and how to create an easy-to-read function to reverse a number in Python.

The Quick Answer: Use a Python While Loop

Cara menggunakan reverse index python

  • Reverse a Python Number Using a While Loop
  • Reverse a Python Number Using String Indexing
  • Reverse a Python Number Using a Custom Function
  • Conclusion

Reverse a Python Number Using a While Loop

Python makes it easy to reverse a number by using a while loop. We use a while loop with the help of both floor division and the modulus % operator.

Let’s take a look at an example to see how this works and then dive into the why of this works:

number = 67890
reversed_number = 0

while number != 0:
    digit = number % 10
    reversed_number = reversed_number * 10 + digit
    number //= 10
    
print(reversed_number)

# Returns: 9876

Let’s break down what we do here:

  1. We instantiate two variables, number and reversed_number. The first stores our original number and the second is given the value of 0
  2. While our number variable is equal to anything by 0, we repeat our actions below
  3. We instantiate digit, and assign it the modulus (remainder) of our number divided by 10
  4. We multiply our reversed number by 10 and add our digit
  5. Finally, we return the floored result of our number divided by 10 (this essentially removes the number on the right)
  6. This process is repeated until our original number is equal to zero

It’s important to note, this appraoch only works for integers and will not work for floats.

In the next section, you’ll learn how to use Python string indexing to reverse a number.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Reverse a Python Number Using String Indexing

Another way that we can reverse a number is to use string indexing. One of the benefits of this approach is that this approach will work with both integers and floats.

In order to make this work, we first turn the number into a string, reverse it, and turn it back into a number. Since we’ll need to convert it back to its original type, we need to first check the numbers type.

Let’s take a look at how we can accomplish this in Python:

number = 67890.123

reversed_number_string = str(number)[::-1]
if type(number) == float:
    reversed_number = float(reversed_number_string)
elif type(number) == int:
    reversed_number = int(reversed_number_string)
    
print(reversed_number)

# Returns 321.09876

Python indexing allows us to iterate over an iterable object, such as a string. The third parameter is optional, but represents the step counter, meaning how to traverse an item. By default, the value is 1, which means it goes from the first to the last. By using the value of -1, we tell Python to generate a new string in its reverse.

We use the type checking in order to determine what type of number to return back to.

In the next section, you’ll learn how to create a custom function that makes the code easier to follow and understand.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Reverse a Python Number Using a Custom Function

In this section, you’ll learn how to turn what you learned in the section above into an easy to read function. While the code may seem intuitive as we write it, our future readers may not agree. Because of this, we can turn our code into a function that makes it clear what our code is hoping to accomplish.

Let’s take a look at how we can accomplish this in Python:

def reverse_number(number):
    """Reverses a number (either float or int) and returns the appropriate type.

    Args:
        number (int|float): the number to reverse

    Returns:
        int|float: the reversed number
    """
    if type(number) == float:
        return float(str(number)[::-1])
    elif type(number) == int:
        return int(str(number)[::-1])
    else:
        print('Not an integer or float')

print(reverse_number(12345.43))
print(reverse_number(456))

# Returns:
# 34.54321
# 654

Our function accepts a single parameter, a number. The function first checks what the type is. If the type is either float or int, it reverses the number and returns it back to the same type. If the type is anything else, the function prints out that the type is neither a float nor an int.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Conclusion

In this post, you learned how to reverse a number using both math and string indexing. You also learned how to convert the string indexing method to a function that will make it clear to readers of your code what your code is doing.

If you want to learn more about string indexing in Python, check out the official documentation for strings here.

How do you reverse a number in a for loop?

Reverse a number using for loop.

public class ReverseNumberExample2..

public static void main(String[] args).

int number = 123456, reverse = 0;.

//we have not mentioned the initialization part of the for loop..

for( ;number != 0; number=number/10).

Can you do a for loop backwards in Python?

To reverse for loop in Python just need to read the last element first and then the last but one and so on till the element is at index 0. You can do it with the range function, List Comprehension, or reversed() function.

How do you reverse a list in a for loop Python?

3) Using for loop Another way to reverse python list without the use of any build-in methods is using loops. Create an empty list to copy the reversed elements. In the for loop, add the iterator as a list element at the beginning with the new list elements. So in that way, the list elements will be reversed.

How do you reverse input in Python?

Use reversed() Method to Reverse a String in Python You can also use the reversed method in Python which returns a reversed object or iterator of the input string. The only thing you need to do is to perform an additional join operation on the resultant reversed object and return the new string.