Python random function

前端 未结 9 1131
后悔当初
后悔当初 2020-12-10 03:26

I\'m having problems with Python\'s import random function. It seems that import random and from random import random are importing different thing

9条回答
  •  鱼传尺愫
    2020-12-10 04:31

    The random module contains a function named random(), so you need to be aware of whether you have imported the module into your namespace, or imported functions from the module.

    import random will import the random module whereas from random import random will specifically import the random function from the module.

    So you will be able to do one of the following:

    import random
    a = random.random()
    b = random.randint(1, 5)
    # you can call any function from the random module using random.
    

    or...

    from random import random, randint   # add any other functions you need here
    a = random()
    b = randint(1, 5)
    # those function names from the import statement are added to your namespace
    

提交回复
热议问题