Will there be any possibility to exclude for example: the number 50, 99, 80 for so that it is not printed?
x = (random.randint(1, 100))
print(x)
Will there be any possibility to exclude for example: the number 50, 99, 80 for so that it is not printed?
x = (random.randint(1, 100))
print(x)
I copy exactly what it says in this question:
from random import choice
print(choice([i for i in range(0,9) if i not in [2,5,7]]))
In your case print(choice([i for i in range(1,101) if i not in [50,99,80]]))
As César adds in the comments, the range that returns random.randint
is inclusive, so for it to include 100, you should put 101.
A similar but somewhat different approach to Adrian's answer, provided the list of cases is relatively small, is:
generate a random value but to use as a list selection index.
import random
elementos = [n for n in range(0, 101) if n not in [50, 99, 80]]
x = elementos[random.randint(0, len(elementos))]
It may eventually be more optimal if the number of excluded values is significant.
The last part should start from 0, it would be elementos[random.randint(0, len(elementos) - 1)]
but you are excluding the first element, and at the end restartle one so that it does not give a IndexError
. Remember that these are positions in a list.
HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution