Python: 如何让两个不同函数中的2个值相等?

Python: How do you make 2 values in two different functions equal?

所以我正在尝试使用随机骰子在 Python 中编写一个二十一点游戏,我试图将玩家功能与庄家功能进行比较,但我不知道如何制作一个功能与另一个相比?如果您能解释我如何使一个函数中的一个局部变量等于另一个函数中的另一个局部变量,那将不胜感激。代码是为了如果你只是想看看我正在尝试做什么,它还没有完成。

玩二十一点骰子的程序。

import random
def roll_die():
return random.randint(1, 11)

def player():
    ''' 
    Implements what happens on player's turn. 
    Returns total and blackjack, which represents
    the player's total score and whether the
    player hit Blackjack, respectively.
    '''
    blackjack = False
    total = 0

    print('************ YOUR TURN ************')
    die1 = random.randint(1,11)
    die2 = random.randint(1,11)
    if die1 == 11 and die2 == 11:
        die1 = 10
    initial_roll = print('Roll: ',die1,die2)
    initial_total = die1+die2
    print('Total: ',initial_total)
    stay_or_roll = input('(s)tay or (r)oll? ')
    next_total = initial_total
    if next_total == 21:
        print(blackjack)

    while stay_or_roll == 'r' or next_total > 21:
        next_roll = (roll_die())
        print('\nRoll: ',next_roll)
        next_total = int(next_total+ next_roll)
        print('Total: ',next_total)
        if next_total > 21:
            print('Bust!')
        dealer()
        stay_or_roll = input('(s)tay or (r)oll? ')      
            if stay_or_roll == 's':
                dealer()     

    # < Insert the rest of your code here. >

def dealer():
    ''' 
    Implements what happens on the dealer's turn. 
    Returns total which represents the dealer's
    total score.
'''

print("\n********** DEALER'S TURN **********")
die1 = random.randint(1,11)
die2 = random.randint(1,11)
if die1 == 11 and die2 == 11:
    die1 = 10
initial_roll = print('Roll: ',die1,die2)
initial_total = die1+die2
print('Total: ',initial_total)
stay_or_roll = input('Press <enter to continue ...')
next_total = initial_total
if next_total >=16 or next_total <21:
    print('done')
if next_total == 21:
    print(Blackjack)
while stay_or_roll == '' and int(next_total) <= 21:
    next_roll = (roll_die())
    print('\nRoll: ',next_roll)
    next_total = int(next_total+ next_roll)
    print('Total: ',next_total)
    if next_total > 21:
        print('Bust!')     
    stay_or_roll = input('Press <enter to continue ...')       
def main():
    ''' 
    The main driver of the program. Connects the 
    player() and dealer() functions together to
    play Blackjack Dice.
    '''

    # The user (or player) plays first.
player_total, blackjack = player()
    print(player())
    print(dealer())
    # < Insert the rest of your code here. >

main()

您不能在函数之间直接共享局部变量。您的实际选择是 return 值、设置全局变量、传入要修改的可变对象以包含数据,或重写以使用 class 将值保留为属性。

您可以使用全局变量并在调用函数时从函数内部设置它们的值。这样您就可以从其他函数访问该值。