Saturday, August 13, 2022

[FIXED] Why the "NONE" is getting appended in list?

Issue

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.


Solution

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
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.