Как вывести числа в обратном порядке питон

от admin

Reverse a Number in Python

Python is an interpreted, high-level, general-purpose programming language with different applications. To learn the fundamental concepts of Python, there are some standard programs that would give you a brief understanding of all the concepts practically. Reverse a number in Python is one of these programs which gives the learner a deep understanding of loops and arithmetic operators. This article will help you understand and implement the ways to reverse a number. It will cover the following topics —

  • How to reverse a number in Python?
  • Python program to reverse a number
  • Using loops
  • Using recursion

How to reverse a number in Python?

It’s simple! You can write a Python program that takes an input number and reverse the same. The value of an integer is stored in a variable that is checked using a condition and then each digit of the number is stored in another variable, which will print the reversed number. Numbers can be reversed in Python using different methods, let us take a look at the Python program to implement the same.

Python program to reverse a number

There are two ways to reverse a number in Python programming language —

  • Using a Loop
  • Using Recursion

Reverse a Number using Loop

Output:

Program Explanation

User value: Number = 123456 and Reverse = 0

First Iteration
Reminder = Number %10
Reminder = 123456%10 = 6
Reverse = Reverse *10 + Reminder
Reverse = 0 * 10 + 6 = 0 + 6 = 6
Number = Number //10
Number = 123456 //10 = 12345

Sixth iteration
From the Second Iteration, the values of both Number and Reverse have been changed as Number = 1 and Reverse = 65432
Reminder = Number %10
Reminder = 1 %10 = 1
Reverse = Reverse *10+ Reminder = 65432 * 10 + 1
Reverse = 654320 + 1 = 654321
Number ended:

Reverse a Number using Recursion

Output:

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series that will explain the various other aspects of Python and Data Science.

Обратный список в Python

Давайте рассмотрим все эти способы, как вывести список в обратном порядке на простых примерах.

С использованием функции reverse()

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

Перевернуть и создать новый список с помощью нарезки

Мы можем использовать нарезку для создания нового списка в обратном порядке. Давайте посмотрим на пример.

с использованием нарезки

Здесь исходный список не изменяется. Это простой однострочный способ перевернуть список.

С помощью reversed()

Мы можем использовать встроенную функцию reversed() для создания обратного итератора, а затем использовать его с функцией list() для создания нового списка с элементами в обратном порядке.

Обратный список Python с использованием итератора reversed()

Заключение

Если вы хотите перевернуть список, используйте функцию reverse(). Однако, если вы хотите сохранить исходный список нетронутым, вы можете использовать нарезку, а также итератор reversed().

Python: Reverse a Number (3 Easy Ways)

Python Reverse a Number Cover Image

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
Читать:
Где почитать логи службы сервера 1с

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.

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

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

Статьи

Введение

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

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