The Python Oracle

How to add exception to random.randint in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 Question
00:42 Accepted answer (Score 8)
00:54 Answer 2 (Score 6)
01:09 Answer 3 (Score 1)
01:48 Answer 4 (Score 0)
02:03 Thank you

--

Full question
https://stackoverflow.com/questions/4210...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #random

#avk47



ACCEPTED ANSWER

Score 8


You can do

number = random.randint(0,10)
while number == 5:
   number = random.randint(0,10)



ANSWER 2

Score 6


How about

random.choice([x for x in range(11) if x != 5])

for a one-liner




ANSWER 3

Score 1


If you actually want an error to be raised then you can use assert

number = random.randint(0, 10)
assert number != 5

or raise an error if your condition is met.

number = random.randint(0, 10)
if number == 5:
    raise ValueError # or another Exception of choice

Or if you want to keep trying until you get a random number that isn't 5, then

while True:
    number = random.randint(0, 10)
    if number != 5:
        break



ANSWER 4

Score 0


!= is actually an operator that returns true or false try this:

import random
l=[i for i in range(1,11)]
l.remove(5)
print random.choice(l)