Ask coding questions

← Back to all posts
Having Issues with Random (Python)
aflacc

Hi, so I was bored and started working on a python program that gives you random Math problems and when I run the program, sometimes the code just randomly fails to actually pick a random choice from the operation array which is literally just something I chose to add for weight of operations and chance.

Expectations

Code should 100% of the time pick a random item from the pool array.

Reality

Code most of the time works, but sometimes gives me an error that says something like int is out of range

Answered by 19ecal [earned 5 cycles]
View Answer
Voters
aflacc
Comments
hotnewtop
19ecal

To pick a random item from a list reliably, use operation = random.choice(pool)

Spacecraft

I'm not certain about this because it's hard to recreate this error, but you may occasionally be out of range due to how line 79 is written:

You're calling 2 separate random integer functions. The second embedded one is a range from 0 to whatever. On occasion it may select 0 as the random number. Then, it uses this random number in the first random selection using a range from 1 to <second random number>. In this case, you would be asking it to pick a random number between 1 and 0, which I think will cause a range error. Try changing the range be something equal to or greater than 1 for the second embedded random number generator:

Hopefully that fixes your issue.