Search code examples
pythonloopsuser-input

Using input() to quit


I'm a pretty new programmer and have been working with Python 3 for a few weeks. I tried making a little magic 8 ball program where you get an answer to a question and it asks if you want to play again. however no matter what I enter it never quits and keeps looping. I'm not sure what I'm doing wrong. Any help is greatly appreciated!

#Magic 8 Ball V2
import random
import time

class Magic8ball:

    def __init__(self, color):
        self.color = color

    def getanswer(self):
        responselist = ['The future looks bright!', 'Not too good...', 'Its a fact!',
                        'The future seems cloudy', 'Ask again later', 'Doesnt look too good for you',
                        'How would i know?', 'Maybe another time']
        cho = random.randint(0, 7)
        print ('Getting answer...')
        time.sleep(2)
        print (responselist[cho])

purple = Magic8ball('Purple')
blue = Magic8ball('Blue')
black = Magic8ball('Black')

while True:
    print ('Welcome to the magic 8 ball sim part 2')
    input('Ask your question:')
    black.getanswer()
    print ('Would you like to play again?')
    choice = ' '
    choice = input()
    if choice != 'y' or choice != 'yes':
        break

Solution

  • Three things wrong with your code:

    1)

    choice = ' '
    choice = input()
    

    No need for the first line, you are immediately overriding it.

    2)

    print ('Would you like to play again?')
    choice = input()
    

    Instead of this, use just input("Would you like to play again?")

    3) The logic on the line of if choice != 'y' or choice != 'yes': is wrong.

    In my opinion it would be better if you did this:

    if choice not in ("y", "yes"):
    

    This would make it really clear what you are trying to do.

    Also, you might want to consider using choice.lower() just for the convenience of the users. So that Yes still counts.