Search code examples
pythonfunctionreturnindentationdice

How can I get a function in Python 3 to return a value that I can use in another function?


I need to design a game of snakes and ladders in python and for part of it, I need to be able to roll a dice and get a random value. For this, I have imported random and then written the function below. However, obviously, I then need to be able to use the dice value in other functions of the game. How do I get it so that the value python returns is retained and able to be used in another function.

Below is the function I have written for rolling the dice. However, when I then run this function and then afterwards try print(dice_value), the program tells me that dice_value has not be defined.

Anybody able to help??

import random 
def roll_dice():
    dice_value = random.randint(1,6)
    print("Its a..." + str(dice_value))
    return dice_value

Solution

  • The variable dice_value exists only inside your function roll_dice(). It is a local variable. You need to call your function with:

    my_variable = roll_dice()
    

    Now the result of your function is stored in the variable my_variable, and you can print it.