this is my code. As you can see by my comment at the top of my code, I want any value under 21 to return the value 0, exactly 21 to return a 1, and anything over 21 to return a 2. This is my best attempt, and almost everything works.
Except when I win in my blackjack game and get 21 points, where the output of winCheck() is still 0. Anything over 21 returns the value 2 correctly, just like when I’m still under 21 points I get returned a 0. I just can’t get it to return the value 1 when I hit 21 points.
Is there something I’ve misunderstood about if/elif statements?
# 0 = under 21, 1 = exactly 21, 2 = bust
def winCheck(points):
if points <= 21:
return 0
elif points == 21:
return 1
elif points >= 21:
return 2
CodePudding user response:
Use < (less) and > (greater) instead of <= (less equal) and >= (greater equal) because 21 <= 21 is true.
def winCheck(points):
if points < 21:
return 0
elif points == 21:
return 1
elif points > 21:
return 2
CodePudding user response:
The conditions are checked in order: if points <= 21 is true (and it is if points is 21), your if statement never bothers checking points == 21. Simply altering the order of the checks will suffice:
def winCheck(points):
if points == 21:
return 0
elif points <= 21:
return 1
elif points >= 21:
return 2
Note, though, that if points == 21 is false, then points <= 21 and points < 21 are equivalent. Using < (and >) is both more readable and allows you to peform the checks in any order, because only one of the three can be true for a given value of points.
def winCheck(points):
if points == 21:
return 0
elif points < 21:
return 1
elif points > 21:
return 2
or
def winCheck(points):
if points < 21:
return 0
elif points == 21:
return 1
elif points > 21:
return 2
