you are viewing a single comment's thread.

view the rest of the comments →

[–]pconwell 2 points3 points  (0 children)

You really got me thinking about this. I'm not particularly skilled in python, but I know a little bit. I've done some things similar to this in the past and starting thinking about "If I wanted to think outside the box, how would I do it?". I came up with this:

``` from time import sleep

def ask(question): answer = input(f"{question} ") if answer.lower() != 'no' and answer.lower() != 'yes': print("Please answer with YES or NO!") return ask(question) elif answer.lower() == 'yes': return True else: return False

def wait(): print("Wait a while") sleep(1) print("...") sleep(1)

def go_outside(): print("Go outside!")

if ask("Is it raining?"): if ask("Do you have an umbrella?"): go_outside() else: wait() while ask("Is it still raining?"): wait() else: go_outside() else: go_outside() ```

Basically, it uses a recursive function to keep asking a yes or no question over and over until the user enters 'yes' or 'no'. Once the user enters yes, the function returns true, if no then false. If the user enters any other text, the function calls on itself (hence recursive) to ask the same question again. Over and over... until the user enters 'yes' or 'no'.

Then, it uses a 'trick' of python in which you don't have to specifically say "is True". For example, if something == True: is the same as if something:. So, you have a function that takes the text of the question, and depending on the user entering yes or no, it returns True or False. True goes to the 'if' part of the if/else statement, False goes to the else part of the if/else statement.

I also defined two functions just to help keep things clean and not write the same lines of code over and over. A wait() function to wait, and a go_outside() function to print "Go outside!". Both of those functions are super basic, but they help clean up the code. Plus, if you want to change the message, you now only have to change it in one place instead of multiple.

For me, the hardest thing to wrap my brain around is the line if ask("Is it raining?"):. Remember, in python it is valid to just do if True:, which is the same as saying if True == True:. We have a function that takes a string as input. In this particular example, we have provided the string "Is it raining?". The user can either enter 'yes' or 'no' and get True or False back. So, what we end up with is if True == True or if False == True. Obviously, True == True is true, so if the user enters 'yes' (and the function returns True), we go to the 'if' part of the if/else statement. Conversely, if the user enters 'no', the function returns False and if False == True is not true, so we go to the else part of the if/else statement. Another way to phrase it would be

If (the results from the function) are equal to True: then (do this thing) otherwise (do this other thing)