[Tutor] func-question_y_n.py

Hugo Arts hugo.yoshi at gmail.com
Fri Mar 15 22:20:16 CET 2013


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

> Hello All,
>
> Okay, I have created a small function that will check to see if a user
> has answered with a Yes, No or other response.  If the user puts yes
> or no the function ends, if they put anything but yes or no then the
> function will ask them the same question and tell them they either
> need to put yes or no for their response
>
> This is what I have as of now:
> ### Start of Code ###
> def question_y_n(question):
>     answer = input(question)
>     while(answer != "Yes"):
>         if answer != "No":
>             print("Please enter Yes or No for your response!")
>             answer = input(question)
>         else:
>             answer = "No"
>             break
>     return answer
>
> answer = question_y_n("You want a drink of water? :")
> print("Your answer to the question was ", answer)
> ### End of Code ###
>
> Is this the best way to handle this?  I would like to use this any
> time I have a yes or no question. In the future I will add to this and
> make it work with yes/no, true/false, 1/0 so that anytime there is
> anything that only has two answer I could use this instead of writing
> more code for each two answer type questions.
>
> Thank you for your advice ahead of time!!!
>
> PS: I hope don't mind me posting code that works to see if I can improve
> on it!
>

Hey Christopher, posting code that works is totally fine! Let's see how we
can improve this little function.

The thing that is bugging me most about this code is that the structure of
the code is kind of hard to understand, because it doesn't quite clearly
match the description you gave of the purpose of the function. Your
description was quite nice and simple already, I'm just going to slightly
reformat it and put it in a numbered step-by-step format:

1. ask a question, receive an answer
2. if the answer is "Yes" or "No", return the answer
3. else, print a message and go back to step 1

That's a very clear description of the problem, and we like that. So
ideally, the code should look as much as possible like that description and
it will be very clear and simple as well!

I could write the code for you now, but I think you will learn far better
if first you try yourself. You might notice some words in the description
are already very similar to python code structures. If you get stuck, don't
hesitate to come back with whatever code you have, even if that's totally
broken and not even valid python. We love seeing people who are trying to
figure stuff out and don't want the solution handed to them :)

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


More information about the Tutor mailing list