1

i did it in while loop but couldn't do it in for loop

my code using while loop :

x=int(input("enter a number: "))
i=0
while(x>0):
    remainder=x%10
    i=(i*10)+remainder
    x//=10
print(i)
  • Check this answer https://stackoverflow.com/questions/22290425/python-write-a-for-loop-to-display-a-given-number-in-reverse – Paras Saini Jan 09 '21 at 08:57
  • 1
    remove `int()` and it will be simpler to reverse – furas Jan 09 '21 at 08:57
  • 1
    Does this answer your question? [Python - Write a for loop to display a given number in reverse](https://stackoverflow.com/questions/22290425/python-write-a-for-loop-to-display-a-given-number-in-reverse) – costaparas Jan 09 '21 at 08:57

2 Answers2

0

In your example your using arithmetic, but why not convert to a string to make life easier?

x = int(input("enter a number: "))
result = ""
for char in str(x)[::-1]:
  result += char
print(result)

Note that [::-1] means "iterate backwards" and that if your number ends with zeros, they'll appear at the start of the reversed string. If you want, you can trim them with lstrip:

print(result.lstrip("0"))
mackorone
  • 1,056
  • 6
  • 15
0

If you remove int() then you will no need loop

x = input("enter a number: ")

result = x[::-1]

print(result)

You may need lstrip('0') to remove 0 when you convert 10 to 01 and you want to skip 0.

OR convert to int after reversing and it removes 0

x = input("enter a number: ")

result = x[::-1]
i = int(result)

print(i)

Another example - it uses for-loop but it still need str at start

x = input("enter a number: ")

i = 0

for char in reversed(x):
    i = i*10 + int(char)

print(i)

With for-loop you would have to convert int to str to know how much diggits it has.

for-loop is good when you know how many items you have. while is better when you don't know how many items you have, or you don't want to work with items one-by-one but skip something, repeate it, etc.

With for-loop you could eventually use iterator/generator which will raise __StopIter__ at the end of data - but probably this iterator/generator whould have to use while for this :)

furas
  • 134,197
  • 12
  • 106
  • 148