算命先生列表和raw_input

时间:2014-05-22 18:44:46

标签: python

所以这是我现在的python代码,如果用户回答是,我遇到循环问题的问题。当用户回答“否”时,它仍会询问他们的问题。这是非常令人沮丧的,因为我是一个初学者,我不能为我的生活弄清楚这一点。这是我的代码:

import random

answers = ["Of course", "No freaking way man", "I don't think so", "Maybe", "Get out of       here with that nonsense, no way!"]
question = 'What is your question? '

name=raw_input('What is your name : ')
print ("Hi %s! I am fortune teller Idris" % name)

def prompt_question(question):
    response = raw_input(question)
    print random.choice(answers)


prompt_question(question)

def ask_again():
    response2 = raw_input('Do you Have another question? ')
    if response2 == 'Yes' or 'yes' or 'Y':
         print prompt_question(question)
    elif response2 == 'No' or response2 == 'no':
        print "goodbye"
    else:
        print 'You need to say yes or no'


ask_again()

我能得到的任何帮助都会很棒,谢谢。

2 个答案:

答案 0 :(得分:4)

非空字符串返回True。因此{@ 1}}将永远被采用。你需要使用

if 'yes':

if response2 in ['Yes', 'yes', 'Y']:

修改:我会写一个if response2 == 'Yes' or response2 == 'yes' or response2 == 'Y': 函数

main()

答案 1 :(得分:0)

糟糕:

    if response2 == 'Yes' or 'yes' or 'Y':

更好:

    if response2 == 'Yes' or response2 == 'yes' or response2 == 'Y':

“any或'yes'”将始终为true,因为只有空字符串('')为false。或者评估它之间的每一个东西,而不是像英语一样在列表之间选择。

因此,在您的代码中,机器永远不会试图查看响应是否为“否”。它只是假设它应该提出另一个问题,因为“是”是真的。