我的魔法8球

时间:2017-10-06 12:21:34

标签: python

我的魔法8球代码由于某种原因赢了。基本代码有效,但它不会给出一个答案,它会启动一些永不停止的循环。有什么帮助吗?

import sys
import random

ans = True

while ans:
    question = input("Ask the magic 8 ball a question: (press enter to quit) ")

    answers = random.randint(1,8)

    if question == "":
        sys.exit()

    elif answers == 1:
        print ("It is certain")

    elif answers == 2:
        print ("Outlook good")

    elif answers == 3:
        print ("You may rely on it")

    elif answers == 4:
        print ("Ask again later")

    elif answers == 5:
        print ("Concentrate and ask again")

    elif answers == 6:
        print ("Reply hazy, try again")

    elif answers == 7:
        print ("My reply is no")

    elif answers == 8:
        print ("My sources say no")

一般来说,我会自己解决这个问题,但我已经看了两年

2 个答案:

答案 0 :(得分:1)

尝试在最后添加ans = False,如下所示:

import sys
import random

ans = True

while ans:
    question = input("Ask the magic 8 ball a question: (press enter to quit) ")

    answers = random.randint(1,8)

    if question == "":
        sys.exit()

elif answers == 1:
    print ("It is certain")

    elif answers == 2:
        print ("Outlook good")

    elif answers == 3:
        print ("You may rely on it")

    elif answers == 4:
        print ("Ask again later")

    elif answers == 5:
        print ("Concentrate and ask again")

    elif answers == 6:
        print ("Reply hazy, try again")

    elif answers == 7:
        print ("My reply is no")

    elif answers == 8:
        print ("My sources say no")
    ans = False

答案 1 :(得分:0)

如果您不想要循环,请不要使用while。 对于1次回应,请尝试:

import random

answers = ("It is certain","Outlook good","You may rely on it",\
           "Ask again later","Concentrate and ask again",\
           "Reply hazy, try again","My reply is no","My sources say no")

if input("Ask the magic 8 ball a question: (press enter to quit) "):
    print( answers[random.randint(0,len( answers )-1)] )