Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么打印语句是';其他';条款仍在执行?_Python_Python 3.x - Fatal编程技术网

Python 为什么打印语句是';其他';条款仍在执行?

Python 为什么打印语句是';其他';条款仍在执行?,python,python-3.x,Python,Python 3.x,我是编程新手,这是我的代码。当我输入'banana'时,结果是'banana is fruit',但它也会从'else'子句中打印'unknown'。为什么? product = str(input("Chose Product : ")) if product == "banana" or product == "apple" or product == "kiwi" or product == "le

我是编程新手,这是我的代码。当我输入'banana'时,结果是'banana is fruit',但它也会从'else'子句中打印'unknown'。为什么?

product = str(input("Chose Product : "))

if product == "banana" or product == "apple" or product == "kiwi" or product == "lemon":
    print(f"{product} is fruite")
if product == "pepper" or product == "tomato" or product == "cucumber" or product == "carrot":
    print(f"{product} is vegetable")

else:
    print("unknown")

在第二种情况下使用elif而不是if。

尝试以下方法:

product = str(input("Chose Product : "))

if product == "banana" or product == "apple" or product == "kiwi" or product == "lemon":
    print(f"{product} is fruite")
elif product == "pepper" or product == "tomato" or product == "cucumber" or product == "carrot":
    print(f"{product} is vegetable")
else:
    print("unknown")
elif
将else链接到第一个if。 在您的代码中,else仅在第二个if不为True时执行,而第一个if单独工作。

试试看

product = str(input("Chose Product : "))


if product == "banana" or product == "apple" or product == "kiwi" or product == "lemon":
    print(f"{product} is fruite")
elif product == "pepper" or product == "tomato" or product == "cucumber" or product == "carrot":
    print(f"{product} is vegetable")
else:
    print("unknown")

如果不使用elif链接if,则如果if高于else为false,则else将起作用

此代码有效

product = str(input("Chose Product : "))
if product == "banana" or product == "apple" or product == "kiwi" or product == "lemon":

    print(f"{product} is fruite")
elif product == "pepper" or product == "tomato" or product == "cucumber" or product == "carrot":
    print(f"{product} is vegetable")

else:
    print("unknown")

只需将中间的if替换为elif,以保持链

将第二个
if
设置为
elif
,使其成为相同条件的一部分,而不是一个全新的条件。另外,在
输入
调用周围不需要
str
,它已经返回了一个
str
:)您需要使用
elif
,因为您使用的是两个
If
块,所以在从第一个块获得结果后,它会检查第二个块,它不在那里,所以
其他
部分会被打印出来,如果产品在(“香蕉”、“苹果”、“猕猴桃”、“柠檬”)中,那么
操作会更容易一些:
而不是所有的
s…天哪,我太笨了,谢谢。请考虑确认答案。