Python:If语句、原始输入和列表生成器

2024-10-02 16:23:04 发布

您现在位置: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

Tags: instance用户in信息列表ifcountgreen
2条回答

'polly''pally'都是非空字符串,因此等同于 ^Python中布尔上下文中的{}。使用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'起作用

'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

相关问题 更多 >