关于 else 语句的问题...python 中的二十一点
这里是Python新手。我正在尝试创建一个黑杰克游戏,用户可以在其中与计算机对战。我认为我遇到麻烦的地方是这里的 if、elif 语句。我想知道的是,当我没有 else 语句时,如果任何 if 和 elif 语句的条件都不满足,会发生什么?这里没有 else 语句有问题吗?
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 <= 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
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 <= 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果没有满足任何条件,则任何
if
或elif
块中的条件都不会被执行。如果计算机或玩家在一轮中都没有获胜,那就没问题。否则,您应该包含一个else
语句来涵盖这种情况。If none of the conditions are met then none of the conditionals in any of the
if
orelif
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 anelse
statement to cover that case.如果你没有 else,代码就会“失败”;即不会执行任何条件代码,因此获胜计数不会改变。
看看您的示例的具体情况,我发现的唯一潜在问题是有些游戏未被计算在内。您的要求或设计将决定这是否确实是一个问题。
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.
这是完全正确的。没有 else 语句不是问题。
This is perfectly valid. Having no else statement isn't a problem.