使用 input() 退出

Using input() to quit

我是一个相当新的程序员,已经使用 Python 3 几周了。我尝试制作一个神奇的 8 球小程序,您可以在其中获得问题的答案,然后询问您是否想再玩一次。但是无论我输入什么,它都不会退出并一直循环。我不确定我做错了什么。任何帮助是极大的赞赏!

#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

使用sys.exit()退出shell。

此外,正如@jonrsharpe 指出的那样,您希望在这一行中使用 and 而不是 or

if choice != 'y' or choice != 'yes':

那是因为如果用户提供 'y',程序将进行两项检查:首先,它检查 choice != 'y' 是否为假。然后,因为您使用的是 or,它会检查 choice != 'yes' 是否为 true。因此,无论用户输入什么,程序都会跳出while循环。

您的代码有三处错误:

1)

choice = ' '
choice = input()

不需要第一行,您会立即覆盖它。

2)

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

而不是这个,只使用 input("Would you like to play again?")

3) if choice != 'y' or choice != 'yes':这一行的逻辑是错误的。

在我看来,如果你这样做会更好:

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

这会让您真正清楚地知道您要做什么。

此外,为了方便用户,您可能需要考虑使用 choice.lower()。所以 Yes 仍然很重要。