Search code examples
pythonpython-3.xpycharm

How to use lists in control flow statements in Python


So I've been working on a basic bot in Python 3.7 and I was working on a shutdown feature. When the user types the word "shutdown" or "Shutdown" the bot confirms if you really want to shut down the program.

For "Yes: and "No" commands, I stored all the commands in a list. Now when I use the program that I created, it only works for the first item in the list but not for the other items. The example is given below:

import time


shutdownAnswerYes = ["Yes", "yes", "Ye", "ye", "Y", "y"]
shutdownAnswerNo = ["No", "no", "nah", "nope", "N", "n"]

shutdown = "shutdown"

while True:
    question = input("What do you want to do?: ")

    if question == shutdown:
        shutdownAnswer = input("Are you sure you want to shutdown?: ")
        if shutdownAnswer == shutdownAnswerNo[0]:
            print("Got it! Resuming back to normal mode.")
        elif shutdownAnswer == shutdownAnswerYes[0]:
            print("Got it! Shutting down.")
            time.sleep(1)
            exit("Shutdown Complete.")

If you try to run this code, you will notice that if you type "Yes" or "No" which is the first item in the list the program will work fine. But if you type any other items in the list such as "yes" or "no" it will not work.

I have tried this code by changing the numbers in [] brackets too but it does not work.


Solution

  • You just checked for the first element with index 0.

    import time
    
    
    shutdownAnswerYes = ["Yes", "yes", "Ye", "ye", "Y", "y"]
    shutdownAnswerNo = ["No", "no", "nah", "nope", "N", "n"]
    
    shutdown = "shutdown"
    
    while True:
        question = input("What do you want to do?: ")
    
        if question == shutdown:
            shutdownAnswer = input("Are you sure you want to shutdown?: ")
            if shutdownAnswer in shutdownAnswerNo:
                print("Got it! Resuming back to normal mode.")
            elif shutdownAnswer in shutdownAnswerYes:
                print("Got it! Shutting down.")
                time.sleep(1)
                exit("Shutdown Complete.")