Here's an answer that spits out a number in reverse, instead of reversing a string, by repeatedly dividing it by 10 and getting the remainder each time:
num = int(input("Enter a number: "))
while num > 0:
num, remainder = divmod(num, 10)
print remainder,
Oh and I didn't read the requirements carefully either! It has to be a for loop. Tsk.
from math import ceil, log10
num = int(input("Enter a number: "))
for i in range(int(ceil(math.log10(num)))): # => how many digits in the number
num, remainder = divmod(num, 10)
print remainder,
You don't need to make it int and again make it str! Make it straight like this:
num = input("insert a number of your choice ")
print (num[::-1])
Or, try this using for loop:
>>> rev = ''
>>> for i in range(len(num), 0, -1):
... rev += num[i-1]
>>> print(int(rev))
Best way to loop over a python string backwards says the most efficient/recommended way would be:
>>> for c in reversed(num):
... print(c, end='')
Use reversed() function (efficient since range implements __reversed__):
reversed(range(10))
It's much more meaningful.
Update: list cast
If you want it to be a list (as @btk pointed out):
list(reversed(range(10)))
Update: range-only solution
If you want to use only range to achieve the same result, you can use all its parameters. range(start, stop, step)
For example, to generate a list [3, 2, 1, 0], you can use the following:
range(3, -1, -1)
It may be less intuitive, but it works the same with less text. This answer by @Wolf indicates this approach is slightly faster than reversed.
Use the 'range' built-in function. The signature is range(start, stop, step). This produces a sequence that yields numbers, starting with start, and ending if stop has been reached, excluding stop.
>>> range(9,-1,-1)
range(9, -1, -1)
>>> list(range(9,-1,-1))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> list(range(-2, 6, 2))
[-2, 0, 2, 4]
The list constructor converts range (which is a python generator), into a list.