Python newbie here. I'm trying to create a black jack game in which the user plays against the computer. I think where I'm having trouble is with the if, elif statements here. What I want to know is, what happens when none of the criteria of any of the if and elif statements are met when I don't have an else statement? Is it problematic here not to have an else statement?
def game_winner(n):
p_wins = 0
d_wins = 0
for i in range(n):
player_sum = player_game()
dealer_sum = dealer_game()
if player_sum > dealer_sum and player_sum <= 21:
p_wins = p_wins + 1
elif dealer_sum > 21 and player_sum &开发者_Python百科lt;= 21:
p_wins = p_wins + 1
elif player_sum > 21 and dealer_sum <= 21:
d_wins = d_wins + 1
elif dealer_sum > player_sum and dealer_sum <= 21:
d_wins = d_wins + 1
return p_wins, d_wins
If none of the conditions are met then none of the conditionals in any of the if
or elif
blocks are executed. If it is ok that neither the computer or the player wins in a round, then it's fine. Otherwise you should include an else
statement to cover that case.
If you don't have an else, the code will simply "fall through"; i.e. none of the conditional code will be executed, so the win counts will not be changed.
Looking at the specifics of your example, the only potential problem I see is that there will be some games that aren't counted. Your requirements or design will determine if this is really a problem or not.
This is perfectly valid. Having no else statement isn't a problem.
try:
rng = xrange # Python 2.x
except NameError:
rng = range # Python 3.x
def game_winner(n):
p_wins, d_wins = 0, 0
for i in rng(n):
player = player_game()
if player > 21:
d_wins += 1
else:
dealer = dealer_game()
if player <= dealer <= 21:
d_wins += 1
else:
p_wins += 1
return p_wins, d_wins
精彩评论