3

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Shawdotion
  • 49
  • 1
  • 2
  • 6
  • 1
    what do you mean properly? what are you trying to do? – shafeen Feb 16 '16 at 04:13
  • 1
    return a, you should have tried a bit before posting – AlokThakur Feb 16 '16 at 04:13
  • The word 'properly' is just thrown in there. I'm trying to run the randombb function with it's purpose to get the result from the function random.random and store it in variable a. – Shawdotion Feb 16 '16 at 04:17
  • and @AlokThakur return a doesn't give out an input when randombb() is called. – Shawdotion Feb 16 '16 at 04:19
  • You use "function" many times but still do not know what does it mean. It is absurd. Function definition is: "A function is a process that associates to each element of a set X a single element of a set Y." I.e. You give it an element and it does **return** an element. – Elis Byberi Oct 14 '19 at 18:19

3 Answers3

7

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
4

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
sameera sy
  • 1,708
  • 13
  • 19
2

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)
Shanu Pandit
  • 122
  • 1
  • 10