Python random number excluding one variable

13,195

Solution 1

Try this:

import random

x = int(raw_input("Number(1-6): ")) # note I made x an int

while True:
    y = random.randint(1, 6)
    if x != y: break

Solution 2

I would suggest you to use random.choice form the list of numbers sans your number of choice

import random
x = raw_input("Number: ")
y = random.choice(range(1, x) + range(x+1, 6))

Solution 3

Rather than use random.randint(), produce a list of possible values and remove the one you don't want. Then use random.choice() on the reduced list:

import random
x = int(input("Number: "))
numbers = list(range(1, 7))
numbers.remove(x)
y = random.choice(numbers)

Demo:

>>> import random
>>> x = 5
>>> numbers = list(range(1, 7))
>>> numbers
[1, 2, 3, 4, 5, 6]
>>> numbers.remove(x)
>>> numbers
[1, 2, 3, 4, 6]
>>> random.choice(numbers)
6
>>> random.choice(numbers)
1
>>> random.choice(numbers)
2
Share:
13,195
Gewoo
Author by

Gewoo

Updated on June 04, 2022

Comments

  • Gewoo
    Gewoo almost 2 years

    Is it possible to create a variable with a random number except for one number that is stored in a variable?

    For example:

    import random
    x = raw_input("Number: ")
    y = random.randint(1,6)
    

    So the variable x could never be y