简体   繁体   English

为什么我的if语句不能正常工作?

[英]Why doesn`t my if statement work correctly?

Hey guys I'm having some trouble with an if-statement in python I`m working on. 嘿伙计们,我正在使用python中的if语句遇到一些问题。 I simplified the code for this question since the core of the problem stays the same and it makes it easier to understand: So lets say I create two classes, one for Apples and one for Bananas. 我简化了这个问题的代码,因为问题的核心保持不变,这使得它更容易理解:所以我想创建两个类,一个用于Apples,一个用于Bananas。 Their attributes are basically the same (name, color and price). 它们的属性基本相同(名称,颜色和价格)。

class Apple:                                   
    def __init__(self, name, color, price):
        self.name = name
        self.color = color
        self.price = price

A1=Apple("Apple1", "red", 5)
A2=Apple("Apple2", "yellow", 3)

Apple_List=[A1, A2]


class Banana:
    def __init__(self, name, color, price):
        self.name = name
        self.color = color
        self.price= price

B1=Banana("Banana1","yellow", 5)
B2=Banana("Banana2", "brown", 1)

Banana_List=[B1,B2]

So far so good. 到现在为止还挺好。 I wanted to define a method for the banana class which should check first whether the price of the banana is the same as for one of the apple objects. 我想为香蕉类定义一个方法,该方法应首先检查香蕉的价格是否与其中一个苹果对象相同。 If that is the case, the banana should take over that apple's name (again, it doesnt make any sense in this code, but its relevant for the actual project I'm working on). 如果是这样的话,香蕉应该接管苹果的名字(再次,它在这段代码中没有任何意义,但它与我正在研究的实际项目有关)。 In the second place, the method is supposed to check whether the banana has the same color as one of the apple objects and then take over that apples name (I used an elif statement for that one). 第二,该方法应该检查香蕉是否具有与苹果对象之一相同的颜色,然后接管那个苹果名称(我使用了一个elif语句)。 Here's what the method looks like: 这是方法的样子:

def evaluate(self):
    for a in Apple_List:
        if self.price==a.price:
            self.name=a.name

        elif self.color==a.color:
            self.name=a.name

        else:
            pass

    print(self.name)

Now, whenever I try to run that code with Banana1, I get "Apple2" as a result, even though Banana1 has the same price as Apple1 and should therefore be named "Apple1". 现在,每当我尝试用Banana1运行该代码时,我得到“Apple2”,即使Banana1的价格与Apple1相同,因此应命名为“Apple1”。 It looks like the elif statement is executed before the if statement, since Banana1 has the same color as Apple2 and takes over its name. 看起来elif语句在if语句之前执行,因为Banana1与Apple2具有相同的颜色并接管其名称。 But shouldn't the if statement have priority over the elif statement? 但是if语句不应该优先于elif语句吗? Sorry if there is an obvious solution for this problem, I'm very new to python programming. 对不起,如果这个问题有一个明显的解决方案,我对python编程很新。 Thanks in advance for your help! 在此先感谢您的帮助! Heres the full code: 下面是完整的代码:

class Apple:                                   
    def __init__(self, name, color, price):
        self.name = name
        self.color = color
        self.price = price

A1=Apple("Apple1", "red", 5)
A2=Apple("Apple2", "yellow", 3)

Apple_List=[A1, A2]

class Banana:
    def __init__(self, name, color, price):
        self.name = name
        self.color = color
        self.price= price

    def evaluate(self):
        for a in Apple_List:
            if self.price==a.price:
                self.name=a.name

            elif self.color==a.color:
                self.name=a.name

            else:
                pass

        print(self.name)



B1=Banana("Banana1","yellow", 5)
B2=Banana("Banana2", "brown", 1)

Banana_List=[B1,B2]

B1.evaluate()

B1 matches both apples. B1匹配两个苹果。 First it matches A1 , and changes its name to 'Apple1' . 首先它匹配A1 ,并将其名称更改为'Apple1' Then it matches A2 and changes its name to 'Apple2' . 然后它匹配A2并将其名称更改为'Apple2' If you want to see this behavior explicitly, try: 如果要显式查看此行为,请尝试:

def evaluate(self):
    for a in Apple_List:
        if self.price==a.price:
            self.name=a.name
        elif self.color==a.color:
            self.name=a.name
        print(self.name)

If you want to instead only change the name for the first match, you need to either break or return when you want the loop to end: 如果您只想更改第一个匹配的名称,则需要在需要循环结束时breakreturn

def evaluate(self):
    for a in Apple_List:
        if self.price==a.price or self.color==a.color:
            self.name=a.name
            break
    print(self.name)

"The good news about computers is that they do what you tell them to do. The bad news is that they do what you tell them to do." “关于计算机的好消息是,他们按照你告诉他们要做的去做。坏消息是,他们做了你告诉他们做的事情。” - Ted Nelson - 泰德尼尔森

Shouldn't the if statement have priority over the elif statement? if语句不应优先于elif语句吗?

Yes! 是! and it does! 它确实! The reason for your unexpected behavior isn't the order of the if / elif conditions, but rather the fact that you're looping over Apple_List . 您的意外行为的原因不是if / elif条件的顺序,而是您循环Apple_List

Here's how the flow of your evaluate method goes: 以下是evaluate方法的流程:

  • Loop with Apple1 starts Apple1循环启动
    • Does "Apple1" have the same price as "Banana1"? “Apple1”的价格是否与“Banana1”相同? Yes! 是!
    • Change self.name to "Apple1". self.name更改为“ self.name ”。
  • Loop with Apple1 ends Apple1的循环结束
  • Loop with Apple2 starts Apple2循环启动
    • Does "Apple2" have the same price as "Banana1"? “Apple2”的价格与“Banana1”相同吗? No. 没有。
    • Does "Apple2" have the same color as "Banana1"? “Apple2”与“Banana1”颜色相同吗? Yes! 是!
    • Change self.name to "Apple2". 更改self.name为“Apple2”。
  • Loop with Apple2 ends 循环与Apple2结束

As you can see, the if statement does have priority, but assigning self.name doesn't cause the loop to end. 如您所见, if语句确实具有优先级,但分配self.name不会导致循环结束。 It will move on to Apple2, where self.name is reassigned after matching color. 它将转移到Apple2,其中self.name在匹配颜色后重新分配。

If you want to stop the loop after matching the price or color, use Python's break statement . 如果要在匹配价格或颜色后停止循环,请使用Python的break语句

Edit: 编辑:

PS You can delete the else: pass part of the conditionals. PS你可以删除else: pass条件的一部分。 This behavior is identical to omitting the else clause. 此行为与省略else子句相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM