如何检查字符串是否包含单词?

时间:2019-01-28 20:23:24

标签: python python-3.x string python-2.7 substring

S0,基本上,我写了一个更长的程序,用另一种语言测试我的时态。它根据掷出的骰子随机测试我。但是,由于某些原因,我引用的代码片段无效。问题是,如果我输入“ present”或“ future”,则会跳至else部分。 “两者”均出于某种原因起作用。我究竟做错了什么?真的很烦我,因为我看不到任何问题。

tenses_tested = input("Would you like to be tested on the present, future simple, or both?")

if "present" in tenses_tested:
    roll_range = 6
    roll_addition = 0
if "future" in tenses_tested:
    roll_range = 6
    roll_addition = 6
if "both" in tenses_tested:
    roll_range = 13
    roll_addition = 0
else:
    print("Something went wrong because this keeps coming up...")
    roll_range = 13
    roll_addition = 0

3 个答案:

答案 0 :(得分:0)

if "present" in tenses_tested:
    roll_range = 6
    roll_addition = 0
elif "future" in tenses_tested:
    roll_range = 6
    roll_addition = 6
elif "both" in tenses_tested:
    roll_range = 13
    roll_addition = 0
else:
    ...

在else仅附加到if "both" ...

之前

通过使用elif,我们将它们全部附加到else上,如果有任何工作,它将不会放在else上

答案 1 :(得分:0)

不,不是这样。根据您输入的是“现在”还是“未来”,它成功进入if块。但是到了最后一个条件。该条件与前两个条件无关,而else仅适用于该条件;因此,由于第三个if为假,则else将会被触发,并将覆盖原始值。

解决方案是使用elif使它们全部成为同一块的一部分。

if "present" in tenses_tested:
    roll_range = 6
    roll_addition = 0
elif "future" in tenses_tested:
    roll_range = 6
    roll_addition = 6
elif "both" in tenses_tested:
    roll_range = 13
    roll_addition = 0
else:
    print("Something went wrong because this keeps coming up...")
    roll_range = 13
    roll_addition = 0

答案 2 :(得分:0)

问题是您使用的是if而不是elif语句,因此您的代码正在测试这三个条件。例如,如果在"present" in tenses_tested:块中添加了一条打印语句,您将意识到它进入了该块。但是它也进入了未来,并且进入了两个障碍,并且因为您键入的内容是!=“ both”,所以进入了其他地方。将来也会发生同样的情况,但两者却不会,因为这是最后的声明。这应该起作用:

tenses_tested = input("Would you like to be tested on the present, future simple, or both?")

if "present" in tenses_tested:
    roll_range = 6
    roll_addition = 0
elif "future" in tenses_tested:
    roll_range = 6
    roll_addition = 6
elif "both" in tenses_tested:
    roll_range = 13
    roll_addition = 0
else:
    print("Something went wrong because this keeps coming up...")
    roll_range = 13
    roll_addition = 0