【问题标题】:Python if statement runs even if false [duplicate]即使为假,Python if 语句也会运行 [重复]
【发布时间】:2017-11-26 06:55:08
【问题描述】:

我正在尝试进行 Reddit 挑战,但它似乎卡在了 if 声明上,即使是错误的也会播放。

type1 = input()
type2 = input()
if type1[:3] == 'nor':
    if type2[:3] == 'nor'or'fir'or'wat'or'ele'or'gra'or'ice'or'fig'or'poi'or'gro'or'fly'or'psy'or'bug':
        print('Normal 100% Damage')
    elif type2[:3] == 'roc' or 'ste':
        print('Not very effective 50% Damage')
    elif type2[:3] == 'gho':
        print('No effect 0% Damage')
    else:
        print('Not a valid type')

【问题讨论】:

  • 因为 if 语句不是假的,也永远不会是假的。非空字符串被解析为truetype2[:3] == 'nor' 之后的项目不假设您正在与type2[:3] 进行比较。相反,它将字符串解析为条件。请参阅this question,了解如何将一个项目与 if 语句中的多个值进行比较。
  • 叹息......其中另一个......这是一个可悲的常见错误。请仔细阅读有关这些运算符如何工作的文档。

标签: python windows python-3.x if-statement pycharm


【解决方案1】:

这是一个常见的错误:

>>> value = 'maybe'
>>> print(bool(value == 'yes' or 'no'))
True

如果你分解它是有意义的:

>>> print(bool(value == 'yes') or bool('no'))
True
>>> print(bool('no'))
True

你的意思是这样的:

>>> print(value in ['yes', 'no'])
False

这将给出预期的输出。

【讨论】:

  • 我已经尝试实现你所说的,但现在它只是跳到 else 语句。我将 or 替换为 ,并将它们全部放在括号中。示例:('nor'、'fir'等)
  • You must've done it wrong。请注意,这可能不是实现我认为您正在做的事情的最佳方式。在给定攻击类型和防御类型的情况下,嵌套字典等数据结构更适合检查攻击的有效性。
  • 我现在明白了,谢谢。我听说过 python 中的字典,但从未有机会了解更多关于它的信息。我知道它使用这些{}。我一定会更多地了解它们。
【解决方案2】:

我在你的代码中看到的第一个问题是,就像@Sebastian 说你所做的是一个常见的错误,我的解决方案是这样做的:

element_list = [
'nor','fir','wat',
'ele','gra','ice',
'fig','poi','gro',
'fly','psy','bug',
'roc', 'ste'
]

if type2[:3] in element_list:
    print('Normal 100% Damage')
elif type2[:3] in element_list:
    print('Not very effective 50% Damage')
elif type2[:3] in element_list:
    print('No effect 0% Damage')
else:
    print('Not a valid type')

这是因为type2 变量检查该特定字符串是否在列表中。它会根据给定的输入输出不同的结果。

下次你这样做时,请记住:

if a == b or a == c : 不是if a == b or c :

【讨论】:

  • 啊,谢谢我使用多个列表使它工作。