我的代码有问题。每当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()
答案 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
将在每次迭代时分别为1
,2
和3
。您可能想做的就是将rice_ingredients
转换为int
,例如rice_ingredients = input("How many ingredients: ")
成为rice_ingredients = int(input("How many ingredients: "))
rice_ingredients
是int
,您无需将其与字符串进行比较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!")