I'd like to know how to generate random numbers in Python. I'm with version 3.4.

8

I'd like to know how to generate random numbers in Python. I'm with version 3.4.

asked by anonymous 24.07.2015 / 02:02

14

```
from random import randint
print(randint(0,9))
```

This generates integers between 0 and 9.

You can use several other functions available in documentation . Each one may be better for what you want.

```
from random import randrange, uniform
print(randrange(0, 9)) #faixa de inteiro
print(uniform(0, 9)) #faixa de ponto flutuante
```

You can import everything and use what you want:

```
from random import *
random.seed() #inicia a semente dos número pseudo randômicos
random.randrange(0, 9, 2) # pares entre 0 e 9
random.choice('abcdefghij') # seleciona um dos elementos aleatoriamente
items = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(items) # embaralha os itens aleatoriamente
```

24.07.2015 / 02:10

8

```
from random import *
print random()
print uniform(10,20)
print randint(100,1000)
print randrange(100,1000,2)
```

random () returns a float x such that 0

24.07.2015 / 02:05

2

I can not comment yet because I have no punctuation for this, but `randint`

includes the last number, unlike `randrange,`

that works more like the rest of Python (closed interval at the beginning and open at the end). So, in the lai0n response, `randint(100,1000)`

includes the 1000 in the possibilities.
At least in Python 3.4, which is what I use. Therefore, `randrange(a, b+1)`

is the same as `randint(a, b)`

25.07.2015 / 19:22

1

Here is a function as a suggestion, which generates random numbers (from 0.0 to 1.0) in a vector with a given size:

```
def gerar():
from random import random
tamanho = int(input())
resposta = [0.0] * tamanho
for i in range(tamanho):
resposta[i] = random()
return resposta
```

23.03.2017 / 00:27