11

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.

Gad
  • 2,867
  • 25
  • 35
DonutsSauvage
  • 157
  • 1
  • 1
  • 5

3 Answers3

26

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.

Kay Kay
  • 278
  • 3
  • 5
6

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))
Guybrush
  • 2,680
  • 1
  • 10
  • 17
2

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])
Slayer
  • 832
  • 1
  • 6
  • 21
  • 2
    OP wants either -40 or 40, not a value between -40 and 40. – Guybrush Mar 28 '19 at 13:59
  • @Guybrush Updated my answer. This should be fine – Slayer Mar 28 '19 at 14:07
  • 2
    I don't think ``choices`` should be preferred to ``choice`` here, because the former returns a list of selected items (even if there is only one item). That means that OP will have to do ``x = choices(...)[0]`` where ``x = choice(...)`` is enough, simpler and more readable ;-) – Guybrush Mar 28 '19 at 14:10
  • Agreed @Guybrush! – Slayer Mar 28 '19 at 14:18