如何将函数的结果存储在 Python 中的变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35423564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:25:33  来源:igfitidea点击:

How can I store a result of a function in a variable in Python?

pythonfunctionpython-2.7variablesrandom

提问by Shawdotion

I'm trying to store the result of random.randominto a variable like so:

我试图将结果存储random.random到一个变量中,如下所示:

import  random

def randombb():
 a = random.random()
    print(a)

randombb()

How can I properly get a?

我怎样才能正确地得到一个?

Thanks.

谢谢。

采纳答案by mgilson

Generally, you returnthe value. Once you've done that, you can assign a name to the return value just like anything else:

一般来说,你return的价值。完成后,您可以像其他任何事情一样为返回值分配一个名称:

def randombb():
    return random.random()

a = randombb()

As a side note -- The python tutorial is really great for anyone looking to learn a thing or two about the basics of python. I'd highly recommend you check it out. Here is the section on functions: https://docs.python.org/2/tutorial/controlflow.html#defining-functions...

作为旁注——python 教程非常适合任何想要学习一两件事关于 python 基础知识的人。我强烈建议你检查一下。这是关于函数的部分:https: //docs.python.org/2/tutorial/controlflow.html#defining-functions...

回答by Shanu Pandit

You can simply store the value of random.random()as you are doing to store in a, and after that you may return the value

您可以像存储在 a 中一样简单地存储random.random()的值,然后您可以返回该值

import  random

def randombb():
        a = random.random()
        print(a)
        return a

x= randombb()
print(x)

回答by sameera sy

You can make it a global variable if you don't want to return it. Try something like this

如果您不想返回它,可以将其设为全局变量。尝试这样的事情

a = 0 #any value of your choice

def setavalue():
    global a    # need to declare when you want to change the value
    a = random.random()

def printavalue():
    print a    # when reading no need to declare

setavalue()
printavalue()
print a