Having issues calling variables from one function to another


#1
from random import randint
from time import sleep

print("Hello, welcome to the DICE GAME")
sleep(2)
p1_name = str(input("Player one, please enter your name:\n"))
p2_name = str(input("Player two, please enter your name:\n"))

number_of_sides = 6
def roll_dice(number_of_sides):
    first_roll = randint(1, number_of_sides)
    second_roll = randint(1, number_of_sides)
    third_roll = randint(1, number_of_sides)
    die_max_val = 6
    dice_max_val = die_max_val * 2
    print("Rolling...")
    sleep(2)
    print("The first roll is: %d" % first_roll)
    sleep(2)
    print("The second roll is: %d" % second_roll)
    sleep(2)
    total_roll = int(first_roll) + int(second_roll)
    if first_roll == second_roll:
        print("You rolled a double, you get to roll one more time")
        print("Your third roll is: %d" % third_roll)
        total_roll += int(third_roll)
    else:
        total_roll = int(first_roll) + int(second_roll)
        print("Result...")
        print(total_roll)
        sleep(3)
    total = total_roll
    return total

def p1_roll():
    print(p1_name + ", this is your roll")
    roll_dice(number_of_sides)

def p1_score():
    score_1 = 0
    return total
    score_1 += int(total)
    if int(score_1) % 2 == 0:
        score_1 += 10
    else:
        if int(score_1) > 0:
            score -= 5
            min(0)
        else:
            score == 0

def p2_roll():
    print(p2_name + ", this is your roll")
    roll_dice(number_of_sides)

def p2_score():
    score_2 = 0
    return total
    score_2 += int(total)
    if int(score_2) % 2 == 0:
        score_2 += 10
    else:
        if int(score_2) > 0:
            score_2 -= 5
            min(0)
        else:
            score_2 == 0

p1_roll()
p1_score()

I’m having issues with the code above. Within the function roll_dice there is a variable called total_roll. I created a second variable that was equal to that at the end of the function. I then try to call the new variable total in another function p1_score. However when I do that, I get the error ‘total’ is not defined. I’ve tried searching all around the internet to solutions but it seems that I should be able to call the variable straight from within a function.

Can someone help me correct the code to get it to work?
I’m aware it isn’t formatted correctly on the site, it is correctly indented in Atom.


#2

total has a local scope, it only exists within the roll_dice function

that is where return comes in, we can use return to hand back a result to the function call:

variable_containing_returned_result = roll_dice()
print variable_containing_returned_result