如何用RandomCard()函数替换AceOfSpades()中的卡牌生成代码?
问题
现有以下Python代码:
def RandomCard(): x=number[ran.randint(0,12)] y=suit[ran.randint(0,3)] print("Your card is the:", x, "of", y) def AceOfSpades(): count = 1 x=number[ran.randint(0,12)] y=suit[ran.randint(0,3)] while x != 'Ace' or y != 'Spades': x=number[ran.randint(0,12)] y=suit[ran.randint(0,3)] count += 1 else: print("Your card is the:", x, "of", y) print("It took", count, "tries to get the Ace of Spades!")
想将AceOfSpades()函数中生成随机牌的代码:
x=number[ran.randint(0,12)] y=suit[ran.randint(0,3)]
替换为调用RandomCard(),但直接替换后无法达到预期效果,该如何操作?
解决方案
直接替换无效的原因是原RandomCard()仅打印结果,没有返回生成的牌面和花色值,导致AceOfSpades()无法获取x和y来判断是否为黑桃A。需要修改RandomCard()让它返回牌面和花色,再在AceOfSpades()中接收返回值。
修改后的代码
- 调整
RandomCard()函数,使其返回生成的牌面与花色:
def RandomCard(): x = number[ran.randint(0,12)] y = suit[ran.randint(0,3)] # 若需保留打印功能,可保留下方print语句;不需要则删除 # print("Your card is the:", x, "of", y) return x, y
- 修改
AceOfSpades(),调用RandomCard()并接收返回值:
def AceOfSpades(): count = 1 x, y = RandomCard() while x != 'Ace' or y != 'Spades': x, y = RandomCard() count += 1 print("Your card is the:", x, "of", y) print("It took", count, "tries to get the Ace of Spades!")
说明
修改后,RandomCard()生成牌面和花色后会将其返回,AceOfSpades()通过x, y = RandomCard()获取这些值,就能正常进行循环判断,直到生成黑桃A为止。
内容的提问来源于stack exchange,提问作者ConquestAce
相关产品推荐
相关产品推荐

