[Tutor] (no subject)
Don Arnold
darnold02@sprynet.com
Fri, 9 Aug 2002 15:05:51 -0500
>>Hi,
Hello!
>> 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.
>>print 'This program accepts a number and then reverses it'
>>number = int(raw_input("Enter a number = "))
>>temp_var = 0
>>while (number/10) > 1 :
>> temp_var = (temp_var*10) + (number%10)
>> number = number/10
>>else:
>> temp_var = (temp_var*10) + number
>> print 'The reversed number is ', temp_var
>>Anbudan,
>>Anand~
You're being bitten by Python's integer division, which drops the remainder:
>>> print 19/10
1
>>> print 12/5
2
As a result, you're 'while' loop exits as soon as number drops below 20
(since 19/10 equals 1) and throws off your results. You can get around this
by dividing by 10.0 to force a floating point division (which won't drop the
remainder), or restating the loop as 'while number > 10' (which takes the
division out of the picture).
Don