Just starting to learn Python, and encounter a problem

MRAB python at mrabarnett.plus.com
Fri Jul 22 11:08:17 EDT 2016


On 2016-07-22 14:59, Zagyen Leo 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.
>
This bit:

     name == "John Cleese" or "Michael Palin"

means the same as:

     (name == "John Cleese") or "Michael Palin"

If name is "Santa Claus", that's:

     "Santa Claus" == "John Cleese" or "Michael Palin"

which is:

     False or "Michael Palin"

which is:

     "Michael Palin"

and any string except "" is treated as True.

The condition should be:

     name == "John Cleese" or name == "Michael Palin"

(Shorter alternatives are available; you'll learn about them later!)




More information about the Python-list mailing list