我想找到一个字符串(蓝色或红色)并将其转换为数字(1 或 2)。
我的代码 2 中有 if-Conditions。他们都是真的。所以我应该得到数字 1 和 2 作为输出。
但是取决于我把返回放在哪里,我总是得到 1 或 2,但不会同时得到 1 和 2。我错过了什么?不能同时有2个if条件吗?
我的输入文本看起来像这样:
myInput = "I like the colors blue and red."
def check_color(document):
for eachColor in document:
if ("blue" in myInput):
color_status = "1"
#return color_status # only 1 as result
if ("red" in myInput):
color_status = "2"
#return color_status # only 1 as result
else:
color_status = "0"
#return color_status # only 1 as result
#return color_status # only 2 as result
没有任何返回 --> 输出:无
函数调用
color_output = check_color(myInput)
print(color_output)
最佳答案
当然,您需要一个return
语句才能获得任何结果。问题在于概念:如果要返回零个或多个值,列表将是最简单的解决方案。 (您的代码只是用 2 覆盖了 1)。
color_status = []
if "blue" in myInput:
color_status.append("1")
if "red" in myInput:
color_status.append("2")
return color_status
关于Python 检查几个 if 条件(查找并用数字替换单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51242426/