Just starting to learn Python, and encounter a problem

Bob Gailer bgailer at gmail.com
Fri Jul 22 10:36:25 EDT 2016


On Jul 22, 2016 10:00 AM, "Zagyen Leo" <zagyen at gmail.com> wrote:
>
> yeah, it may be quite simple to you experts, but hard to me.
>
> In one of exercises from the Tutorial it said: "Write a program that asks
the user their name, if they enter your name say "That is a nice name", if
they enter "John Cleese" or "Michael Palin", tell them how you feel about
them ;), otherwise tell them "You have a nice name."
>
> And i write so:
>
> name = input("Enter your name here: ")
> if name == "John Cleese" or "Michael Palin":
>     print("Sounds like a gentleman.")
> else:
>     print("You have a nice name.")
>
> But strangely whatever I type in (e.g. Santa Claus), it always say
"Sounds like a gentleman.", not the result I want.

Even without knowing the operator precedence, this will be evaluated either
as:
(name == "John Cleese") or "Michael Palin")
or:
name == ("John Cleese" or "Michael Palin").

Case 1: (name == "John Cleese")  evaluates to either True or False. False
or "Michael Palin" evaluates to  ( believe it or not) " Michael Palin"!
Which, as far as if is concerned, is True. True or "Michael Palin"
evaluates to True.

Case 2: "John Cleese" or "Michael Palin" evaluates to False; name== False
evaluates to False.

One way to get the results you want:
if name in ("John Cleese" or "Michael Palin"):



More information about the Python-list mailing list