if y_n: form

This is the place for queries that don't fit in any of the other categories.

if y_n: form

Postby mckryall » Wed Apr 16, 2014 2:42 am

When asking for "yes" or "no" answers, there are several different ways to check if the data given matches the hardcoded data. I'm not really sure which one is the standard or if there is one, so here we go.
I normally use this, but I'm not sure if it's the best way. Note that it will NOT accept "ye" or "s".
Code: Select all
if y_n.lower() in ["yes", "y", "1"]:
    pass
elif y_n.lower() in ["no", "n", "2"]:
    pass

I won't put one that uses "== ["yes", "y", "1"]:" because that would mean it equalled the entire list.
Some people like to use this, but I don't like it because it accepts "ye" and "s". People need to learn to type correctly sometime.
Code: Select all
if y_n.lower() in "yes":
    pass
elif y_n.lower() in "no":
    pass

And, then, further down the chain, are the people who do this:
Code: Select all
if y_n == "Y":
    pass
elif y_n == "N":
    pass

Back to the first example, if you don't like to type much, then you could set the yes and no lists as variables.
Post what you believe should be the standard.
Last edited by mckryall on Wed Apr 16, 2014 4:37 am, edited 1 time in total.
Python 2.7
Mac Mini
Laptop w/ Ubuntu 14.04
Steam; PSN
mckryall
 
Posts: 94
Joined: Sat Nov 23, 2013 6:13 pm

Re: if y_n: form

Postby mckryall » Wed Apr 16, 2014 2:53 am

Also, what's the standard for raw_input()? I do this:
Code: Select all
y_n = raw_input("Yes or no?\n> ")

So that it looks like this:
Code: Select all
Yes or no?
> yes
Python 2.7
Mac Mini
Laptop w/ Ubuntu 14.04
Steam; PSN
mckryall
 
Posts: 94
Joined: Sat Nov 23, 2013 6:13 pm

Re: if y_n: form

Postby Mekire » Wed Apr 16, 2014 3:21 am

Using the in operator with a set of options (your first example) is generally the best. It also extends well to choosing options from keys in a dictionary and similar. The second one is terrible as it accepts all sorts of things it shouldn't. The last is overly restrictive, but if you really are testing for one result it is still the way to go.

As for you second post, there is no standard. If you are writing a text adventure it would probably be nice to have the newline as you did, but this is all just personal taste.

-Mek

PS. Edit your top post; you mistyped the elif conditional in your first codeblock.
User avatar
Mekire
 
Posts: 976
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: if y_n: form

Postby mckryall » Wed Apr 16, 2014 4:36 am

Thanks for the clarification. Also, I keep thinking of only "yes" and "no" as words and not "y"/"n" and "1"/"2".
Python 2.7
Mac Mini
Laptop w/ Ubuntu 14.04
Steam; PSN
mckryall
 
Posts: 94
Joined: Sat Nov 23, 2013 6:13 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 5 guests