[英]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.我需要在 python 中设计一个蛇和梯子的游戏,对于其中的一部分,我需要能够掷骰子并获得随机值。 For this, I have imported random and then written the function below.为此,我导入了 random,然后编写了下面的函数。 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.我如何获得它以便保留 python 返回的值并能够在另一个函数中使用它。
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.但是,当我然后运行此函数然后尝试print(dice_value)
,程序告诉我尚未定义dice_value
。
Anybody able to help??有人能帮忙吗??
import random
def roll_dice():
dice_value = random.randint(1,6)
print("Its a..." + str(dice_value))
return dice_value
The variable dice_value
exists only inside your function roll_dice()
.变量dice_value
仅存在于您的函数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.现在您的函数的结果存储在变量my_variable
,您可以打印它。
You have to save the return value somewhere and then use it or pass it to another function.您必须将返回值保存在某处,然后使用它或将其传递给另一个函数。
For example:例如:
>>> import random
>>> def roll_dice():
... dice_value = random.randint(1,6)
... print("[in roll_dice] Its a..." + str(dice_value))
... return dice_value
...
>>> obtained_dice = roll_dice()
[in roll_dice] Its a...1
>>> print("[outside roll_dice] Its a..." + str(obtained_dice))
[outside roll_dice] Its a...1
variable dice_value
is a local variable inside the function space so you have to return and save it in another variable to continue using it变量dice_value
是函数空间内的局部变量,因此您必须返回并将其保存在另一个变量中才能继续使用它
You can store the return value of your function roll_dice() in a variable that will in return store the value of the return variable (dice_value).您可以将函数 roll_dice() 的返回值存储在一个变量中,该变量将返回存储返回变量 (dice_value) 的值。
random_dice_value = roll_dice()
Note: You need to call the function after you have implemented it since Python is an interpreter language.注意:由于 Python 是一种解释器语言,因此您需要在实现它之后调用该函数。 It will execute the file line by line.它将逐行执行文件。
The problem is that you're trying to call the variable dice_value
outside of its scope.问题是您试图在其范围之外调用变量dice_value
。 If you still go on with your one liner print statement, you can do so by calling the function (that's returning the dice_value
variable) as in:如果您仍然继续使用单行打印语句,则可以通过调用函数(返回dice_value
变量)来实现,如下所示:
print(roll_dice())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.