如果if / elif语句不满足条件后else语句未执行,该怎么办?

时间:2019-12-06 11:13:37

标签: python python-3.x if-statement visual-studio-code

我的代码有问题。每当rice_ingredients = input("How many ingredients: ") is > 8时,我都会收到一个用于if语句的输出,而不是else语句的输出,该输出应该是“成分太多,不专业!”

def Chef() -> int:
    rice_ingredients = input("How many ingredients: ")
    for ingredients in rice_ingredients:
        if ingredients <= str(6):
            print("Professional")
        elif ingredients == str(7) or str(8):
            print("Well, can still be considered professional")
        else:
            print("Too much ingredients, unprofessional!")
        exit()

3 个答案:

答案 0 :(得分:3)

此:

elif ingredients == str(7) or str(8):

不同于:

elif ingredients == str(7) or ingredients == str(8):

这:

elif ingredients == (str(7) or str(8)):

第二种形式可能是您要实现的逻辑,也可以写成:

elif any(ingredients == str(x) for x in (7, 8)):

或:

elif ingredients in {str(7), str(8)}:

编辑

此外,也许您想整体检查代码:

  • Chef()不遵循PEP8的命名约定,并且不返回int(与注释相反)。
  • rice_ingredients包含一个字符串,该字符串应包含一个数字(根据您提出的问题"How many ingredients: "),循环遍历该字符串将导致您分别考虑输入的每个字符,因此,如果您类型123,则ingredients将在每次迭代时分别为123。您可能想做的就是将rice_ingredients转换为int,例如rice_ingredients = input("How many ingredients: ")成为rice_ingredients = int(input("How many ingredients: "))
  • 现在rice_ingredientsint,您无需将其与字符串进行比较
  • exit()将完全退出解释器,如果您只想退出该功能,请使用return。请注意,不需要在函数末尾显式退出该函数,而是会自动退出
  • if-elif-else子句的逻辑可以进一步简化

可能的清理代码如下:

def chef():
    rice_ingredients = int(input("How many ingredients: "))
    if rice_ingredients <= 6:
        print("Professional")
    elif rice_ingredients <= 8:
        print("Well, can still be considered professional")
    else:
        print("Too much ingredients, unprofessional!")

答案 1 :(得分:1)

我不确定是否理解您的问题,但是出现逻辑错误:

def Chef() -> int:
    rice_ingredients = input("How many ingredients: ")
    for ingredients in rice_ingredients:
        if ingredients <= str(6):
            print("Professional")
        #elif ingredients == str(7) or str(8): please note
        elif ingredients == str(7) or ingredients == str(8):
            print("Well, can still be considered professional")
        else:
            print("Too much ingredients, unprofessional!")
        exit()

请注意,在这种情况下,您应该考虑使用其他支票,例如(<>)或in

答案 2 :(得分:1)

这也可以解决您的问题。本质上您想比较数字,所以转换为整数是合乎逻辑的。

def Chef() -> int:
    rice_ingredients = input("How many ingredients: ")
    for ingredients in rice_ingredients:
        value = int(ingredients)
        if value < 7:
            print("Professional")
        elif value < 9:
            print("Well, can still be considered professional")
        else:
            print("Too much ingredients, unprofessional!")