Python Forum
How to get a reverse order of a number?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get a reverse order of a number?
#1
num = 4576
num_p = 0
num_t = num
while num != 0:
    num_p = num_p * 10 + num % 10                     
    num = num / 10                                    
print(num, num_p)
I'd like to get the reverse order of num, and put it to the num_p.
but the answer is 4576, inf.
What is wrong with my code?
Reply
#2
You want integer division.
num = 4576
num_p = 0
num_t = num
while num != 0:
    num_p = num_p * 10 + num % 10                     
    num = num // 10  # Result is int, not float                                  
print(num, num_p)
In your program num was 457.6 after the first loop instead of 457. Because of the decimals in num, "num != 0" is always True and you kept multiplying num_p by 10 and adding a tiny number
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reverse order of phrase Error ilondire05 4 2,519 Aug-29-2019, 04:19 PM
Last Post: buran
  Input a number with any number of digits and output it in reverse order of digits. sarada2099 6 6,697 Mar-12-2017, 05:45 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020