【问题标题】:Using input() to quit使用 input() 退出
【发布时间】:2016-04-21 17:39:45
【问题描述】:

我是一个相当新的程序员,并且已经使用 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

【问题讨论】:

  • 你的布尔逻辑错了……
  • 如果你从不放弃,那么其他事情正在发生。正如所写,它应该始终退出

标签: python loops user-input


【解决方案1】:

你的代码有三个问题:

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 仍然很重要。

【讨论】:

  • if choice not in set(["y", "yes"]) 更快。
  • @RoadieRich 怎么会? set() 在创建列表后只是做了一些额外的操作(检查重复并创建一个新对象),增加了更多的开销。实际上,我会将列表更改为元组,因为据我所知它要快一些。
  • item in set(...) 摊销了O(1),因为它散列值。 item in list(...)O(n),因为它需要检查列表中的每个元素。
  • @RoadieRich 来吧,创建集合的开销远远超过 2 个元素的哈希表的微小效率(如果有的话,因为散列需要时间)。
  • 您提到了not item in...item not in...,差异甚至更小,尤其是如果您将集合创建移到循环之外。
【解决方案2】:

使用sys.exit() 退出shell。

另外,正如@jonrsharpe 所说,您希望在这一行使用and 而不是or

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

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

【讨论】:

    猜你喜欢
    • 2016-01-31
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 2014-08-26
    相关资源
    最近更新 更多