Python if语句即使运行也是错误的

时间:2017-11-26 06:55:08

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

我正在尝试进行Reddit挑战,但它似乎已经卡在if语句中,即使在错误时也会播放。

Screen shot of it happening

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')

2 个答案:

答案 0 :(得分:2)

这是一个常见的错误:

>>> 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

这将给出预期的输出。

答案 1 :(得分:0)

我在你的代码中看到的第一个问题是,就像@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 :

相关问题