python - python函数不返回填充数组
问题描述
我正在使用在线课程,似乎无法诊断此错误。在下面的代码中,如果玩家最初对 draw_one_more() 中的提示响应为否,则返回正确的值。如果玩家拿到一张或多张牌并最终在爆牌前表示没有,则返回 None 值。我在返回之前直接添加了一个打印语句,打印语句显示正确填充的值,但是从函数接收到的值是无。
更新 在处理了一些递归示例后,我有点忘乎所以。正如许多人所说,这个问题不需要递归,TBF 可能是一个糟糕的用例。我按要求添加了更多代码。
def draw_card(hand, card_deck, todraw=1):
for i in range(todraw):
hand.append(card_deck[random.choice(card_deck)])
return hand
player_hand = draw_card(hand=player_hand,
card_deck = card_deck,
todraw=2)
#3D - establish player draw loop
def draw_one_more(ahand):
#print(player_hand)
print(f"line 125 {ahand}")
draw_another = input("Type 'y' to get another card, type 'n' to pass: ")
print("Line 128 Draw another: " + draw_another)
if draw_another != 'y':
print(f"line 129 inside NO returning {ahand}")
return ahand
else:
ahand = draw_card(hand=ahand,
card_deck = card_deck,
todraw=1)
ascore = add_cards(ahand)
#exit 2 - bust
if ascore > 21:
print(f"\tYour cards: {ahand}, current score: {ascore}: PLAYER BUSTS")
print(f"\tComputer's first card: {computer_hand[0]}")
return ahand
#continue recursively
print(f"\tYour cards: {ahand}, current score: {ascore}")
print(f"\tComputer's first card: {computer_hand[0]}")
draw_one_more(ahand)
#4 - computer run loop
#first run player execution
player_hand = draw_one_more(player_hand)
print(f"line 148 player hand {player_hand}")
player_score = add_cards(player_hand)
解决方案
如果在第一次调用 draw_one_more() draw_another == 'y' 时,您的函数将始终返回 None。
在递归函数中,返回的值始终是第一个返回值,如果你的函数没有返回,那么你将得到 None。
前任:
第一次调用 draw_one_more():
. draw_another == 'y'
那么你的函数将执行 else 语句并返回 None,因为你在 else 中没有 return 语句。
前任:
def foo(x):
if (x < 10)
return x
else
foo(x - 1)
是相同的
def foo(x):
if (x < 10)
return x
else
foo(x - 1)
return None
当你调用 foo(x) 时,如果 x < 10 你的函数将返回 x,否则,无
推荐阅读
- javascript - 数组不能在数据表中使用
- docker - 在 docker-compose 中使用 ssh 密钥文件作为环境变量
- c# - Unity3d构建错误重复类com.google.unity.ads
- c++ - 使用 .natvis 文件在 VS Code 中可视化 C++ 对象
- stripe-payments - 我可以在验证域后删除 Apple 域验证文件吗?
- c - 我在测试用例中得到了一些错误的答案,
- c# - 有什么方法可以定义在渲染 img 标签时在哪里查找图像?
- javascript - 如何使子行列可点击?
- sql - 如何跳过 INSERT 语句中引发的异常?
- python - 获取 FigureWidget 的 plotly.graph_objs 属性错误