[Tutor] (no subject)

Lance E Sloan lsloan@umich.edu
Fri, 09 Aug 2002 10:44:41 -0400


--On Friday, August 9, 2002 5:39 PM +0530 Anand Ramakrishna 
<anandrs@hexaware.com> wrote:
>     I am having a strange problem with my python code for reversing a
> number. I tried it on a few combinations and works fine with most of them
> except when the number starts in '1'. If I give input as 123 it reverses
> and displays as 442. If I give input as 12 it reverses and displays as
> 12. Where as if I give any other number, it reverses properly and
> displays the correct result. The code is pasted below.

I don't know what's wrong with the math in your attempt.  I didn't try to 
figure it out, as it sounds like this problem is more easily solved using 
strings:



print 'This program accepts a number and then reverses it'
# The int() here may be unneccessary as we convert back to a string next,
# but it does help remove nondigits and leading zeroes.
number = int(raw_input("Enter a number = "))

numString = str(number)

# There's probably a more clever way to do this part.
newnumString = ''
for n in numString:
  newnumString = n + newnumString

newnum = int(newnumString)
print 'The reversed number is ', newnum



--
Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting.  Specializing in Python & Perl CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"