Kos - 6 months ago 20

Python Question

When writing this code I found myself doing a lot of repetitive stuff and was wondering if there is an easier or simpler or shorter way to do a repetitive task such as this.

Here is the relevant code:

`from random import randint`

RandomNumber = Zeroes = Ones = Twos = Threes = Fours = Fives = Sixes = i = 0

while i < 1000000:

RandomNumber = (randint(0,6))

if RandomNumber == 0:

Zeroes = Zeroes + 1

if RandomNumber == 1:

Ones = Ones + 1

if RandomNumber == 2:

Twos = Twos + 1

if RandomNumber == 3:

Threes = Threes + 1

if RandomNumber == 4:

Fours = Fours + 1

if RandomNumber == 5:

Fives = Fives + 1

if RandomNumber == 6:

Sixes = Sixes + 1

i = i + 1

Answer

Rather than taking the named variables for each random output, you can take dictionary with each possible value as key. This will shorten you code and made it extendable for any random range

```
from random import randint
randomMax = 6
randomList= {i:0 for i in range(0,randomMax+1)}
totalIterations = 10000
while totalIterations >0:
randomList[randint(0,randomMax)]+=1
totalIterations-=1
```

*Sample Output:*

```
{0: 1400, 1: 1400, 2: 1500, 3: 1400, 4: 1500, 5: 1000, 6: 1800}
```