[Tutor] func-question_y_n.py

Hugo Arts hugo.yoshi at gmail.com
Fri Mar 15 23:54:34 CET 2013


On Fri, Mar 15, 2013 at 10:09 PM, Christopher Emery <cpe.list at gmail.com>wrote:

>
> This code works and produces the results that I am looking for,
> however I know there is a better way to do it and now you have me
> thinking about this again.  I just spent about 3 hours doing this
> code.


Yes! learning is happening :D

I was thinking of combining the Yes and No into one check however I
> was having trouble finding resource of how to do mulitiy checks in a
> statement for while.
>
> thinking like this:
>
> def question_y_n(question):
>     answer = input(question)
>     while(answer != "Yes" Or "No"): #This is wrong code
>         print("Please enter Yes or No for your response!")
>         answer = input(question)
> or
>
>
This is an excellent thought! Nice work, this looks already much, much
better and simpler than the previous version, don't you agree? The only
problem of course is that you have some wrong code in it, but that's okay.
The idea is correct, you just need to write it a little differently so it
is valid python :)

Dave already gave you the answer on how to combine multiple checks in one
statement, with the "and" and "or", and Mark gave you what is called the
"idiomatic" way, which is perhaps a little harder to read at first but
really elegant once you get used to it. I'll put them both together down
here:

if a == 5 or a == 6:
    print("a is 5 or 6!")

if a in (5, 6):
    print("a is 5 or 6!")

The second way is a lot shorter, especially if you need to check many
values. It uses the "in" operator, which allows you to check if a value is
in a list (or more technically, a sequence. Any sequence like tuples,
lists, strings, dictionaries, all support the "in" operator). But if you
don't quite grasp  it yet, the first way is fine too.

NOTE: It's important not to confuse these two:

# this doesn't work like you think it does
if a == 1 or 0:
# this is the right way
if a == 1 or a == 0:

the "or" and "and" operator can only connect *comparisons*, nothing else.
The top if statement will be interpreted like this:

if (a == 1) or (0):

which basically means "execute the code below if "a equals 1" is True OR
"the value 0" is True. That's not what you want, even though if you read it
like it's English it sounds right (the lesson is, don't read code like it's
English, because it isn't even close).

You're almost to a working function that can accept any amount of possible
answers, which is really nice. Keep it up!

HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130315/63c4dcb3/attachment.html>


More information about the Tutor mailing list