How to choose randomly between two values?

Question:

So basically I’m trying to get a piece of code to randomly choose between two values -40 and 40.

To do so, I was thinking of using good old mathematics like –

random_num = ((-1)^value)*40, where value = {1, 2}.

random_num, as the name suggest should be a random number.

Any help ?

I am using python, solution using libraries is acceptable.

Asked By: DonutsSauvage

||

Answers:

Assuming that L is a list of values you want to choose from, then random.choice(L) will do the job.

In your case:

import random
L = [-40, 40]
print(random.choice(L))
Answered By: Guybrush

You can use the choices function in python to achieve this. If you want values to be chosen to be only -40 or 40, the second argument is the probability/weights.

from random import choices
choices([-40,40], [0.5,0.5])
Answered By: Slayer

If you want a random integer values between -40 and +40, then

import random
random.randint(-40, 40)

https://docs.python.org/3.1/library/random.html#random.randint

If you want to choose either -40 or +40, then

 import random
 random.choice([-40, 40])

https://docs.python.org/3/library/random.html#random.choice

If you really prefer to go with your implementation of choosing either 1 or 2, as in your question, then plug in those values in random.choice method.

Provided the above solutions, since I feel there is some ambiguity in the question.

Answered By: Kay Kay
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.