Never use eval
. Never.
Firstly, let me explain your mistakes. Your expectations about this program is wrong. You probably want reverse(number)
to reverse the number itself. E.g. after reverse(123)
, 123
should become 321
. But, wait, 123
is just a number, like a number in math, you know. Do you really want to 123
to become 321
? Can you predict what will happen after that? You will now pay 321
for a rent instead of 123
, because you have changed the number itself! Though, these are actually good news, because I have exactly $123
on my bank account, and this is probably the easiest way to increase my money.
Well, this is just a joke. But the point is: you cannot change a number passed to the function. This has been done for the security reasons. There are mutable and immutable objects in python. Number is immutable. You cannot change a number, you can only assign another number:
a = 123
a = 312 # 123 is still 123, 321 is still 312, but a is 321 now
Lists are mutable objects, e.g:
a = []
a.append(1) # I can change the list itself, whoa!
a.append(2) # one more time
a = [3] # and even assign a new list
Finally, the main point is: you cannot change passed number to a function. But: you can return a new number! This is the point - just return
a result from your reverse
function and assign it somewhere like that:
def reverse(number):
...
return result
r = reverse(123)
reverse
wont change 123
, it wont break the world, it just returns a new number, and everything works fine.
By the way, there is a simpler way to check a palindrome:
In [5]: def is_palindrome(s):
...: return s == s[::-1]
...:
In [6]: n = input('Enter number: ')
Enter number: 123321
In [7]: if is_palindrome(n):
...: print('You cool')
...: else:
...: print('No luck')
...:
You cool
s[::-1]
means `take each symbol from the start till the end in a reverse order. This is a slice