Why the "NONE" is getting appended in list?

Question:

I have made 2 functions: one to generate random values from 0 to 20, and another to check if the value generated by function random matches the value of list. If the value matches then random should start again to produce new value

My code is:

import random
mylist=[6,2,4]
y=int()
def randoom():
    str=random.randint(0,20)
    return str
        
def checklist():
    y=randoom()
    print(y,"Generated value y")    
    if y in mylist:
        print(y,"already exist in list")
        checklist()
    if y not in mylist:
        return y

for b in range(1,10):
    x=checklist()
    print(x," X got the value")
    mylist.append(x)
    print(mylist)

My output is: [6, 2, 4, 5, 12, 7, 16, 13, None, 17, 19, None]

Why is None getting appended?

I tried everything in last 3 days to figure out why None is getting appended in list even when I made sure the function runs again to produce a new value of y if it matches the list.

Asked By: Julian ._.

||

Answers:

The return value of checklist is not being saved in your variable after being executed. Fixing this should make your Code work.

Still, you have at the very top of your program a variable named str. Since str is also a function in python, this could cause issues down the road. I would recommend to change this.

Answered By: ductTapeIsMagic

Your checklist function can return None if y is in mylist:

if y in mylist:
    print(y,"already exist in list")
    checklist()  # Executes checklist again, but discards the return value

There is no path after this that can return a value, so the function returns None. You can fix this by returning checklist():

if y in mylist:
    print(y,"already exist in list")
    return checklist()  # Executes checklist again, but returns the value
Answered By: TheMikeste1