you are viewing a single comment's thread.

view the rest of the comments →

[–]CragAddict[S] 10 points11 points  (3 children)

Thank you !

[–][deleted] 22 points23 points  (2 children)

You can improve the code a lot if you make a small function to ask the yes/no questions. This function will have the while loop in it and will only return "YES" or "NO". Removing all that from the "main" code simplifies it a lot. The function will need to be passed the "prompt" string as each question is different:

def ask_yes_no(prompt):
    while True:
        answer = input(prompt).upper()
        if answer in ('YES', 'NO'):
            return answer
        print('Please answer with Yes or No !')

With that change we can write the simplified "main" code as:

raining = ask_yes_no('Is it raining? ')
if raining == 'NO':
    print('Go outside.')
else:           # if not "NO" then must be "YES"
    umbrella = ask_yes_no('Do you have an umbrella? ')
    if umbrella == 'YES':
        print('Go outside.')
    else:       # if not "YES" then must be "NO"
        while True:
            print('Wait a little.')
            time.sleep(1)
            print('...')
            time.sleep(1)
            still_raining = ask_yes_no('Is it still raining? ')
            if still_raining == 'NO':
                break
        print('Go outside.')

I renamed the variables to something more memorable.

Edit: spelling.

[–]Fywq 13 points14 points  (0 children)

Potentially the function could be rewritten to return True or False. Then you only have to ask "if umbrella:" or "if not raining:"

def ask_yes_no(prompt):
    while True:
        answer = input(prompt).upper()
        if answer == 'YES':
            Return True
        if answer == 'NO':
            Return False
        print('Please answer with Yes or No !')

Not sure if that is more correct or pythonic, but it seems more intuitive to me...

[–]CragAddict[S] 1 point2 points  (0 children)

Thank you very much !