如何使用另一个函数中引用的函数中的变量?编辑

时间:2019-07-01 21:09:20

标签: python python-3.x function

很难解释为一个句子,但希望您可以通过代码理解。我想从dice_game_round获取总变量的值到我的函数dice_game_user1中。人们可能会说要使其全球化,但这将无法工作,因为这将需要我编写“ def dice_game_user1(total)”,但对我而言却行不通。我不能写“ total = dice_game_round()”,因为它会打印“ ”。

这是代码

这是针对python 3.7.3

import random
total = 0
def dice_game_round(round_number):
    roll1 = random.randint(1,6)
    print("First roll is...",roll1)
    roll2 = random.randint(1,6)
    print("Second roll is...",roll2)
    total = roll1 + roll2
    if total % 2 ==0:        
        total = total + 10
        print("You got bonus 10 points for even total!")
    else:
        total = total - 5
        print("You lost 5 points for getting an odd number!")
    if roll1 == roll2:
        print("You recieved an extra roll")
        input("Press enter to roll")
        print("Rolling...")
        extra_roll = random.randint(1,6)
        print("Bonus roll was...",extra_roll)
        total = total + extra_roll
    if total < 0:
        total = 0
        print("Your score cannot go below 0, new score is 0")
    print("Your total for ROUND" , round_number , "is...",total)
    input("Press enter to continue")
    return total

def dice_game_user1():
    print("Round One!")
    round_number = "ONE"
    dice_game_round(round_number)
    total = dice_game_round
    print("Round Two!")
    round_number = "TWO"
    dice_game_round(round_number)
    total = total + total
    print("Round Three!")
    round_number = "THREE"
    dice_game_round(round_number)
    total = total + total
    print("Round Four!")
    round_number = "FOUR"
    dice_game_round(round_number)
    total = total + total
    print("Round Five!")
    round_number = "FIVE"
    dice_game_round(round_number)
    total = total + total
    print("****")
    print("Your total is :", total)
    print("****")

dice_game_user1()

我希望dice_game_round的合计值会转移到dice_game_user1,但不会,它显示:<函数dice_game_round在0x04382F60>

1 个答案:

答案 0 :(得分:0)

您不需要使用该变量。该函数返回一个值,因此请使用返回的值。

def function1():
    total = function2()
    total += function2()
    total += function2()
    print(total)

如果要使用变量,可以编写

    v1 = function2()
    total += v1