Python:如果语句,Raw_Input和List Gen

时间:2015-11-10 01:16:16

标签: python

我有一个奇怪的问题是接受用户输入,附加一个包含正确信息的列表,并检查列表是否输入正确。

出于某种原因,只有进入' pally'致电end_instance.enter()(没有' polly')。

def enter(self):
    print """Please enter your two passwords to proceed. Check the other doors for answers. You have five guesses."""

    green_count = 0

    green_ans = []

    while green_count < 5:

        green_guess = (raw_input('> '))

        if 'polly' or 'pally' in green_guess:
            green_ans.append(green_guess)
            green_count += 1

            if 'polly' and 'pally' in green_ans:
                print "cool"
                end_instance.enter()
        else:
            print "try again"
            green_count += 1

2 个答案:

答案 0 :(得分:1)

'polly''pally'都是非空字符串,因此等同于 Python中的布尔上下文中的True。使用orand计算 具有短路评估的布尔表达式:

>>> 'polly' or 'pally'
'polly'   # first True value; second not checked
>>> 'polly' and 'pally'
'pally'   # last True value; both checked

所以,行:

if 'polly' and 'pally' in green_ans:

相当于说:

if 'pally' in green_ans:

因此,只有'pally'有效。

答案 1 :(得分:0)

'polly'永远都是真的。

因此,请将您的代码更改为:

def enter(self):
    print """Please enter your two passwords to proceed. Check the other doors for answers. You have five guesses."""

    green_count = 0

    green_ans = []

    while green_count  '))

        if 'polly' in green_guess or 'pally' in green_guess:
            green_ans.append(green_guess)
            green_count += 1

            if 'polly' in green_guess and 'pally' in green_guess:
                print "cool"
                end_instance.enter()
        else:
            print "try again"
            green_count += 1