Ask OK

This odd function asks the user a question. The question is provided as a parameter to the ask_ok() function and is called prompt, and it is used in the call to input() to display a prompt on screen for the user.

We then receive some keyboard input and store it in ok. A series of simple-conditions perform checks on the responses. We use membership testing (in) and empty/non-empty string testing.

In [10]:
def ask_ok(prompt):
    ok = input(prompt)
    ok = ok.lower()
    
    if ok in ["y", "ye", "yes", "yeah"]:
        return "Affirmative!"
    if ok in ["n", "no", "knope", "nay", "nah"]:
        return "Negatory!"
    #if ok == "":
    if not ok:
        return "Cat got your tongue?"
    #if ok != "":
    if ok:
        return "You're speaking gibberish"
    
In [7]:
ask_ok("Please enter a response (yes/no): ")
Please enter a response (yes/no): yeah
Out[7]:
'Affirmative!'
In [8]:
ask_ok("Please enter a response (yes/no): ")
Please enter a response (yes/no): spam
Out[8]:
"You're speaking gibberish"

Evaluating objects as booleans

Above shows you a technique of evaluating any expression (even a single object) into a boolean without using any relational operators. When used incorrectly it can make code hard to understand, but certain techniques are common, e.g. if ok:. Python has rules for forcing (coericion, conversion) of any non-bool value into bool value. An empty string or empty list, for example is effectively False when converted to a bool. Any non-zero int is considered True. There are many examples:

In [9]:
ok = ""
bool(ok)
Out[9]:
False
In [11]:
ok = "foobar"
bool(ok)
Out[11]:
True
In [13]:
num = 0
bool(num)
Out[13]:
False
In [14]:
num = -100
bool(num)
Out[14]:
True
In [15]:
num = 0.0
bool(num)
Out[15]:
False
In [16]:
num = 343443.0233443
bool(num)
Out[16]:
True
In [17]:
seq = []
bool(seq)
Out[17]:
False
In [18]:
seq = [1,2,3,4]
bool(seq)
Out[18]:
True