Why doesn't the if statement execute?

https://github.com/gabrirm/python-roulette-game.git

if betType == "red" and bet in red == True:
    self.balance += betprice[0] * 2
else:
    self.balance -= betprice[0]
    print("Oh, the ball landed on a black number :(. This is your current balance: ".format(self.balance))

if betType == "black" and bet in black == True:
    self.balance += betprice[0] * 2
else:
    self.balance -= betprice[0]
    print("Oh, the ball landed on a red number :(. This is your current balance: ".format(self. Balance))

So in this piece of code, when the user types 'red', why does the else statement keep executing, even though betType == 'red' and bet in red == True? both parts are true right? the else shouldn't execute.

Upvotes: 0

Views: 72

Answers (1)

S.B
S.B

Reputation: 16556

From documentation:

If A, B and C are operands and x is a comparison operator, then:

A x B x C is equivalent to:

(A x B) and (B x C)

You have this situation in this part: bet in red == True

So now this line:

betType == "red" and bet in red == True

is actually:

(betType == "red") and (bet in red) and (red == True)

From this table, both == and in are comparison operators.

If you want your condition to work as expected put parenthesis around the membership testing like: (bet in red) == True or better is to leave it like bet in red. That's it. No need to compare to True:

betType == "red" and bet in red

Upvotes: 1

Related Questions