Tyler Poore
Tyler Poore

Reputation: 33

import random isn't working (I think)

I'm very new to Python (first year university student) and while attempting to finish some homework, I ran into a problem. I'm creating a very simple program using random numbers. Here is what I've written so far:

import random

def main():
  print random.randint(2,10)
  a=random.seed()
  b=random.seed(5)
  c=random.seed(5)
  print (a)
  print (b)
  print (c)

The problem is that it always prints NONE for a, b, and c. For random.int, it always prints the lowest integer I enter (2 in this case). So this basically makes it impossible for me to write the actual program (a random candy dispenser). I'm actually just assuming that 'import random' isn't working. I actually have no clue.

I would normally ask my professor about this, but he can't be reached until Monday and this assignment is due tonight. Any help is greatly appreciated, and I apologize for the sheer amateurishness of this post.

Upvotes: 2

Views: 2445

Answers (3)

Pynchia
Pynchia

Reputation: 11606

As you can see by typing

>>> import random
>>> help(random.seed)

seed(a=None, version=2) method of random.Random instance Initialize internal state from hashable object.

None or no argument seeds from current time or from an operating
system specific randomness source if available.

For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray.  For version 1, the hash() of *a* is used instead.

If *a* is an int, all bits are used.

random.seed is used to set up the random generator.

In order to obtain values you need to use one of the many functions provided by the random module

e.g.

import random

def main():
  print random.randint(2,10)
  a=random.seed()
  b=random.randrange(5)
  c=random.randrange(5)
  print (a)
  print (b)
  print (c)

Upvotes: 1

Michel Keijzers
Michel Keijzers

Reputation: 15377

You first should set the seed value, this is a value that 'determines' the random values later, and only needs to be set once normally, during the start (or first use of random numbers).

a=random.seed(5)

Mostly this is based on the current time.

Than you can call consecutive calls to get a random number:

print random.randint(2,10)

Upvotes: 1

Max Noel
Max Noel

Reputation: 8910

That's because random.seed only reseeds the random number generator. It doesn't, by itself, return anything (see https://docs.python.org/2/library/random.html#random.seed). Which means it returns None, which is what you're seeing in your tests.

Upvotes: 3

Related Questions