[Tutor] Why isn't my simple if elif script not working?
Andre' Walker-Loud
walksloud at gmail.com
Wed Jul 18 07:31:45 CEST 2012
>
> On Jul 17, 2012, at 10:29 PM, Alexandre Zani wrote:
>
>
> On Tue, Jul 17, 2012 at 10:21 PM, Andre' Walker-Loud
> <walksloud at gmail.com> wrote:
>> Hi Santosh,
>>
>> On Jul 17, 2012, at 10:09 PM, Santosh Kumar wrote:
>>
>>> Here is my script:
>>>
>>> name = raw_input("What's your name? ")
>>>
>>> if name == "Santosh":
>>> print "Hey!! I have the same name."
>>> elif name == "John Cleese" or "Michael Palin":
>>> print "I have no preference about your name. Really!!"
>>> else:
>>> print "You have a nice name."
>>>
>>>
>>> The if part works well. The elif part works well too. The problem is
>>> even if you enter strings other than "Santosh", "John Cleese" and
>>> "Michael Palin" you still get the print from elif part, not from else
>>> part.
>>
>> you just have to be careful with the multiple boolean line in the elif. You can use either
>>
>> elif name == ("John Cleese" or "Michael Palin"):
>
> That won't work.
>
>>>> "John Cleese" == ("John Cleese" or "Michael Palin")
> True
>>>> "Michael Palin" == ("John Cleese" or "Michael Palin")
> False
>>>> ("John Cleese" or "Michael Palin")
> 'John Cleese'
>
> Python will look at the expression ("John Cleese" or "Michael Palin")
> since bool("John Cleese") is True, the expression immediately
> evaluates to "John Cleese" and the elif clause becomes equivalent to
> name == "John Cleese"
thanks - I fell into the same trap! I tried it in my terminal but it worked for the same reason as the OP.
Andre
More information about the Tutor
mailing list