PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 13, 2022

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

 August 13, 2022     append, function, list, python, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing