[Tutor] How does this tiny script works?

Alexandre Zani alexandre.zani at gmail.com
Sun Jul 15 07:45:05 CEST 2012


On Sat, Jul 14, 2012 at 8:32 PM, Santosh Kumar <sntshkmr60 at gmail.com> wrote:
> I am reading How to Think Like a Computer Scientist with Python. There
> is a script in the exercise:
>
> if "Ni!":
>     print 'We are the Knights who say, "Ni!"'
> else:
>     print "Stop it! No more of this!"
>
> if 0:
>     print "And now for something completely different.."
> else:
>     print "Whats all this, then?"
>
>
> The question asks "Explain what happened and why it happened." I my
> self is confused because the output is:
>
> We are the Knights who say, "Ni!"
> Whats all this, then?
>
> 1. I was assuming that in first "if" statement we will get "Stop it!
> No more of this!" because we are no setting any input and matching
> string from it (in this case "Ni!").
> 2. I didn't get 2nd part at all.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Long story short, it has to do with how things get translated to
booleans. An empty string, 0, None or an empty collection will be
translated to False. Almost everything else is translated to True.

So in the first case, python "translates" if "Ni!" to if True. In the
second case, python "translates" if 0 to if False.

You can see this if you pull up an interpreter and type

>>> bool("Ni!")
True
>>> bool(0)
False


More information about the Tutor mailing list