How to add exception to random.randint in Python?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC D Schuberts Piano Sonata D 850 in D
--
Chapters
00:00 How To Add Exception To Random.Randint In Python?
00:35 Accepted Answer Score 8
00:49 Answer 2 Score 6
01:03 Answer 3 Score 1
01:36 Answer 4 Score 0
01:50 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
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Track title: CC D Schuberts Piano Sonata D 850 in D
--
Chapters
00:00 How To Add Exception To Random.Randint In Python?
00:35 Accepted Answer Score 8
00:49 Answer 2 Score 6
01:03 Answer 3 Score 1
01:36 Answer 4 Score 0
01:50 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)