【问题标题】:If statement is True but ELSE gets executed [duplicate]如果语句为真,但 ELSE 被执行 [重复]
【发布时间】:2017-11-16 13:58:41
【问题描述】:

这是我脚本中的一个 sn-p。

while True:

    ## Rules: userInput == [isalpha()=True, isdigit()=True, True, isdigit()=True]

    userInput = raw_input('# ').replace(' ', '').split(',')
    print userInput
    print 'List Index 0', userInput[0].isalpha()
    print 'List Index 1', userInput[1].isdigit()
    print 'List Index 3', userInput[3].isdigit()
    print 'List is', userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()

    if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False:
        print 'Error'
        continue
    else:
        print 'Success'
        break

如果我使用输入运行它,这是我得到的输出:1,1,1,1

# 1,1,1,1
['1', '1', '1', '1']
List Index 0 False
List Index 1 True
List Index 3 True
List is False
Success

据我所知,if 语句是True,应该执行并返回到循环的开头,直到满足规则。但是,会改为执行 else 语句。

我错过了什么?

感谢您的帮助。

【问题讨论】:

  • 我想你可能会认为if condition1 and condition2 == Falseif (condition1 and condition2) == False 相同,而实际上它与if condition1 and (condition2 == False) 相同。
  • 您的 if 语句显示为 if False and True and True,这是错误的,我敢打赌,这正是 Kevin 所说的
  • 谢谢!!!将 if 语句放在括号中效果很好!

标签: python


【解决方案1】:

我想你可能会假设 if condition1 and condition2 == Falseif (condition1 and condition2) == False 相同,而实际上它与 if condition1 and (condition2 == False) 相同。

在这种情况下你应该这样做

if (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()) == False:

if not (userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit()):

if userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit():
    print 'Success'
    break
else:
    print 'Error'
    continue

【讨论】:

  • 谢谢!这就像一个魅力。那些该死的括号带走了我生命中的 2 个小时 lmao
【解决方案2】:

你的布尔逻辑错了,这个:

userInput[0].isalpha() and userInput[1].isdigit() and userInput[3].isdigit() == False

归结为:

False and True and True == False

那就是

False and True and False

这是False,而不是True

【讨论】:

    【解决方案3】:

    您可能应该将while True 的语句更改为类似于while 1:pass 的内容。更多信息见here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-19
      • 2019-05-20
      • 1970-01-01
      • 2017-10-28
      • 2021-06-22
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多