Jun-09-2019, 02:56 PM
Every time you evaluate, you are looping the entire list. Apple1 which has the same color as banana2, is executed per the elif condition.
With break:
Output:apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana2', 'color': 'red', 'price': 3}
changing name of Banana2 to Apple1 based on color
I usually put prints around to quickly identify controlWith break:
def evaluate(self): for a in Apple_List: print(f'apple = {a.__dict__}') print(f'banana = {self.__dict__}') if self.price==a.price: print(f'changing name of {self.name} to {a.name} based on price') self.name=a.name break elif self.color==a.color: print(f'changing name of {self.name} to {a.name} based on color') self.name=a.name break else: print('else clause') print(self.name)
Output:metulburr@ubuntu:~$ python3.6 test3.py
apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana1', 'color': 'yellow', 'price': 5}
changing name of Banana1 to Apple1 based on price
Apple1
apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana2', 'color': 'red', 'price': 3}
changing name of Banana2 to Apple1 based on color
Apple1
apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana3', 'color': 'green', 'price': 7}
else clause
apple = {'name': 'Apple2', 'color': 'yellow', 'price': 3}
banana = {'name': 'Banana3', 'color': 'green', 'price': 7}
else clause
apple = {'name': 'Apple3', 'color': 'green', 'price': 10}
banana = {'name': 'Banana3', 'color': 'green', 'price': 7}
changing name of Banana3 to Apple3 based on color
Apple3
commenting out the elif break makes it look as you expected because ut changes banana name to apples for the next evaluation. Output:metulburr@ubuntu:~$ python3.6 test3.py
apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana1', 'color': 'yellow', 'price': 5}
changing name of Banana1 to Apple1 based on price
Apple1
apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana2', 'color': 'red', 'price': 3}
changing name of Banana2 to Apple1 based on color
apple = {'name': 'Apple2', 'color': 'yellow', 'price': 3}
banana = {'name': 'Apple1', 'color': 'red', 'price': 3}
changing name of Apple1 to Apple2 based on price
Apple2
apple = {'name': 'Apple1', 'color': 'red', 'price': 5}
banana = {'name': 'Banana3', 'color': 'green', 'price': 7}
else clause
apple = {'name': 'Apple2', 'color': 'yellow', 'price': 3}
banana = {'name': 'Banana3', 'color': 'green', 'price': 7}
else clause
apple = {'name': 'Apple3', 'color': 'green', 'price': 10}
banana = {'name': 'Banana3', 'color': 'green', 'price': 7}
changing name of Banana3 to Apple3 based on color
Apple3
Recommended Tutorials: