Reverse an integer
Exercise
Take an integer and reverse its digits. The result is also an integer. Example: 83657 becomes 75638.
Solution
#!/usr/bin/env python
def reverse_int(n):
return int(str(n)[::-1])
n = 83657
print n # 83657
print reverse_int(n) # 75638
Summary: convert the number to string, reverse the string, then convert it back to integer. Details: 83657 -> str(83657) returns "83657" which is a string -> reverse it, we get "75638" -> int("75638") converts it to an integer.
Notes
If you want to concatenate a string and an integer, first you need to convert the integer to string. Example:
n = 83657 print "The value of n is " + n # error, won't work print "The value of n is " + str(n) # OK

Here is my Ruby solution which is very similar but I think it is more OO like than your Python solution. Could we do the same in Python ? (I mean OO like code).
#!/usr/bin/ruby def reverse_int( n ) n.to_s.reverse.to_i end n = 83657 puts n # 83657 puts reverse_int( n ) # 75638I think we can also use this code( This will be use to reverse a string as well number):
a=str(input("enter a number:")) b=len(a) s=0 for c in range(b,0,-1): d=a[(b-1)-s] s+=1 print(d,end='')Simple and sweet:-
def reverse_int(n): ans = 0 while n > 0: (d,n) = (n%10,n//10) ans = 10*ans + d return(ans)