How can I store a result of a function in a variab

2019-02-27 17:43发布

This question already has an answer here:

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

import  random

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

randombb()

How can I properly get a?

Thanks.

3条回答
SAY GOODBYE
2楼-- · 2019-02-27 18:02

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

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 ...

查看更多
Lonely孤独者°
3楼-- · 2019-02-27 18:14

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

import  random

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

x= randombb()
print(x)
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-02-27 18:25

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
查看更多
登录 后发表回答