Wednesday, August 29, 2007

Python puzzle this time :-)

First a question for you, what will you get if you execute following code:
i = 0

What is your guess? Will it be -1? Or what else?

Well, today I learned that this is not going to work as I think it would :-)

Of course there's no pre-decrementation operator, there's no post-decrementation, pre-incrementation and post-incrementation also. But if you write:

You'll get invalid syntax error and you'll notice immediately that's something wrong with your code.

In case of --i it's trickier (or ++i) - it works like you would do -(-i), so if i is set to 1, you'll get 1 :-) -(-1) gives you 1.
>>> i = 1
>>> --i
>>> -i

How come I didn't notice this earlier? :-)

No comments:

Post a Comment