Search code examples
pythonrandomtic-tac-toe

how to use random function in python?


#program to tic-tac-toe
from random import *
num=[i for i in range(1,10)]
flag=0
ulist=list();
xlist=list();
olist=list();
count=0
while(count < 9):
  if(flag==0):
    x=random.choice(num)
    if(x not in ulist):
      ulist.append(x)
      xlist.append(x)
      flag=1
  if(flag==1):
    o=random.choice(num)
    if(o not in ulist):
        ulist.append(o)
        olist.append(o)
        flag=0
  count+=1

print (ulist)
print (xlist)
print (olist)

this is my code i have called for the random function but still its saying i did not use the random function


Solution

  • Correct usage of random function:

    In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list) you could also use choice:

    >>> import random
    >>> values = list(range(10))
    >>> random.choice(values)
    5
    

    choice also works for one item from a not-continuous sample:

    >>> values = [1, 2, 3, 5, 7, 10]
    >>> random.choice(values)
    7
    

    If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:

    >>> import secrets
    >>> values = list(range(10))
    >>> secrets.choice(values)
    2