1

I'm not really sure how to interpret them and i'm still struggling to find out what they're exactly doing..

color = self.color2

color = self.fill1 if color == self.fill2 else self.fill2

what is this exactly saying?

Kara
  • 737
  • 5
  • 9
  • 28

4 Answers4

5

This is known as a conditional expression.

The expression x if C else y first evaluates the condition, C (not x); if C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.

So, your specific example is equivalent to:

if color == self.fill2:
    color = self.fill1
else:
    color = self.fill2
David Heffernan
  • 572,264
  • 40
  • 974
  • 1,389
3

This is not list comprehension. It is sort of a syntactic sugar. Ironically it is meant to improve readability.

It can be interpreted as:

if color == self.fill2:
    color = self.fill1
else:
    color = self.fill2
Anurag Ramdasan
  • 3,807
  • 4
  • 27
  • 49
1

It's a conditional expression See PEP-308.

So something like this

x = true_value if condition else false_value 

It can also be written as

if condition:
    x = true_value
else:
    x = false_value
pradyunsg
  • 13,385
  • 10
  • 36
  • 80
0

Well, it says exactly what it says: put the value of self.fill1 into color variable if value of color equals to self.fill1, otherwise put self.fill2. It's called ternary operator, you can find more information about it here.

aga
  • 25,984
  • 9
  • 77
  • 115