简体   繁体   中英

How to add exception to random.randint in Python?

So I have a variable that creates a random number between 0 and 10, however, I would not like the random number created to be 5. How do I go about adding exceptions to random.randint in Python? What I have below is not doing this:

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

This is only returning True or False based on whether the random number equals 5 or not... how do I fix this?

You can do

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

How about

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

for a one-liner

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

!= 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM