Как перевернуть число в python

от admin

Как перевернуть число в Python

В этом примере мы преобразуем данное число в строку с помощью str(), а затем поменяем его значение, используя нарезку строки. Перевернутая строка преобразуется обратно в int.

Если данный ввод не является числом, мы напечатаем сообщение пользователю.

Пример 2: с использованием цикла while

В этой программе мы будем использовать цикл while для перебора цифр числа, выталкивая их одну за другой. Выскочившие цифры добавляются, чтобы сформировать новое обратное числом.

Заключение

В этой статье в Python мы узнали, как перевернуть число с помощью цикла while и нарезки строк.

Python: Reverse a Number (3 Easy Ways)

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

Quick Answer - Python Reverse a Number

Table of Contents

Reverse a Python Number Using a While Loop

Python makes it easy to reverse a number by using a while loop. We can use a Python 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 why this works:

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 approach 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.

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:

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.

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

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:

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.

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 to reverse an int in python?

I’m creating a python script which prints out the whole song of ’99 bottles of beer’, but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.

This is my full script,

I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.

Nilesh's user avatar

16 Answers 16

Without converting the number to a string:

Alberto's user avatar

You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?

Which runs like:

Then pass the result to reverse :

This makes it much easier to test each part of the code separately and see what’s going on when you put it all together.

jonrsharpe's user avatar

Something like this?

or one line code is

Satyamskillz IN's user avatar

this is for 32 — bit integer ( -2^31 ; 2^31-1 )

Vinay's user avatar

You can cast an integer to string with str(i) and then use your reverse function.

The following line should do what you are looking for:

Original number is taken in a

We convert the int to string ,then reverse it and again convert in int and store reversed number in b

Print the values of a and b print(a,b)

Skipper's user avatar

This code will not work if the number ends with zeros, example 100 and 1000 return 1

srujan kumar's user avatar

#/ always results into float

#// division that results into whole number adjusted to the left in the number line

passionatedevops's user avatar

I think the following code should be good to reverse your positive integer. You can use it as a function in your code.

If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer

Samit Saxena's user avatar

More robust solution to handle negative numbers:

Gunjan's user avatar

An easy and fast way to do it is as follows:

First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ».join() method.

Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.

Поменять порядок цифр числа на обратный в Python

Поменять порядок цифр числа на обратный в Python

Статьи

Введение

В ходе статьи рассмотрим целых четыре способа поменять порядок цифр числа на обратный в Python.

Первый способ – цикл while

Для начала дадим пользователю возможность ввести число, и создадим переменную number2 равную нулю:

Создадим цикл while, который не закончится, пока number больше нуля:

Внутри цикла в переменную digit сохраняем последнюю цифру переменной number, полученную благодаря делению с остатком на десять:

Удаляем последнюю цифру из переменной number путём деления без остатка на десять:

Увеличим разрядность number2 путём умножения на десять:

Осталось прибавить к number2 значение из переменной digit, и после цикла вывести результат:

Второй способ – цикл for

Второй способ работает по тому же принципу, что и первый, но вместо цикла while используется цикл for:

Третий способ – путём преобразования строки в список

Для начала преобразуем строку с введённым числом в список:

С помощью метода reverse() развернём полученный список:

Превратим итоговый список в строку и выведем результат:

Четвёртый способ – срез

Ну и в последнем способе, который мы рассмотрим будет задействован срез.

Развернём введённое число используя срез из с первого до последнего символа с обратным шагом и выведем результат:

Заключение

В ходе статьи мы с Вами рассмотрели четыре способа поменять порядок цифр числа на обратный в Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! ��

Похожие статьи