![](/img/trans.png)
[英]Python Function is returning none although there is the original Value instead of copy
[英]Why is function returning none instead of the value? (Python)
我正在尝试制作二十一点游戏,但我遇到了递归 function 不返回任何问题。 我有一个 function 来计算手牌的分数并检查它是否超过 21。如果是,它会检查手牌中是否有 11; 如果有,则调用另一个 function 将其改为 1,然后调用 function 计算分数。
我已经添加了一个断点,它加起来很好,直到它将总值返回到 class 变量
def get_score(self, hand):
total = 0
for card in hand:
total += card
if total > 21:
if 11 in hand:
return self.ace_conversion(hand)
else:
return total
def ace_conversion(self, hand):
index = hand.index(11)
hand[index] = 1
self.get_score(hand)
在另一篇文章中,有人建议让 if 语句的两边都返回,那是我开始遇到这个问题的时候。 以前,它是:
…
if total > 21:
if 11 in hand:
self.ace_conversion(hand)
else:
return total
当我有这个时,它会计算出正确的值,然后返回手的原始值。
这些案例并不详尽,您需要涵盖手牌大于 21 而没有 11 的情况。
解决方案:
def get_score(hand):
total = sum(hand)
if total > 21 and 11 in hand:
index = hand.index(11)
hand[index] = 1
return get_score(hand)
else:
return total
请注意,虽然可读,但这会在手上执行两次线性扫描。
if total > 21: if 11 in hand: return self.ace_conversion(hand)
如果手上没有 11,则此分支不会返回任何内容。
即使有 11, ace_conversion
也不会返回任何值,因此在这种情况下也没有任何可返回的值。
ace_conversion
调用返回值的 function 的事实不会自动导致从ace_conversion
返回值。
您需要在ace_conversion
中显式包含一个return
语句,并确保在 total > 21 且手中没有 11 的分支中有一个return
语句。
当 ace_conversion(hand) function 完成时,它不返回任何值。 因此,调用 self.ace_conversion(hand) 时,get_score(hand) function 不会返回任何值。
您可以通过向 ace_conversion(hand) 添加 return 语句来解决此问题,该语句返回 self.get_score(hand) 返回的分数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.