小能豆

如何用另一个函数替换一个函数的一部分?

python

这是我的 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!")

我该如何更换

    x=number[ran.randint(0,12)]
    y=suit[ran.randint(0,3)]

AceOfSpades()fn 中RandomCard()代替?

当我简单地将RandomCard()放置到位时x=number[ran.randint(0,12)] y=suit[ran.randint(0,3)],它并没有像我想要的那样运行。


阅读 75

收藏
2023-05-23

共1个答案

小能豆

如果你想在AceOfSpades()函数中调用RandomCard()函数来替代x=number[ran.randint(0,12)]y=suit[ran.randint(0,3)],你可以将这些代码行从RandomCard()函数中提取出来,并在AceOfSpades()函数中调用RandomCard()

下面是修改后的代码:

import random as ran

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
    RandomCard()  # 调用RandomCard()函数获取随机卡牌
    x = number[ran.randint(0, 12)]
    y = suit[ran.randint(0, 3)]
    while x != 'Ace' or y != 'Spades':
        RandomCard()  # 调用RandomCard()函数获取随机卡牌
        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()函数时,它将首先调用RandomCard()函数获取一个随机卡牌,然后继续执行后续的循环和判断逻辑。这样就可以实现你想要的效果。

2023-05-23