Simple Yes No Function in Python

Preface

I’m a Network Engineer learning Python, and these are purely my notes. I’m not an expert by any means. Feel free to use any of these examples and improve upon them. Feel free to call me out where things can be done better.

Onward

I regularly need a simple yes/no function in Python when interacting with users. This function uses sets of data to represent “yes” and “no”. Sets are unordered collections of elements, and can be used similarly to lists (e.g. x in set). The function will take in an answer (yes/no). This will be converted to lowercase and then checked against each set. Result is returned.

# Function for a Yes/No result based on the answer provided as an arguement

def yes_no(answer):
    yes = set(['yes','y', 'ye', ''])
    no = set(['no','n'])
    
    while True:
        choice = raw_input(answer).lower()
        if choice in yes:
           return True
        elif choice in no:
           return False
        else:
           print "Please respond with 'yes' or 'no'\n"

Example:

>>> pyanswer = yes_no('Do you like Python? ')
Do you like Python? yes
>>> 
>>> pyanswer
True
>>> pyanswer = yes_no('Do you like Python? ')
Do you like Python? NO
>>> 
>>> pyanswer
False
>>> 
>>> pyanswer = yes_no('Do you like Python? ')
Do you like Python? sometimes
Please respond with 'yes' or 'no'

Do you like Python? y
>>> pyanswer
True
>>> 
>>> if pyanswer:
...    print "Groovy, baby"
... 
Groovy, baby

mike-myers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s