Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it returns none type when i entered number out of range?

when i enter number program expect, everything run smooth, but if i enter number out of range and then enter number program expect, it returns None. Can any1 explain it to me? Thanks

def zadani_x():
    x=int(input("Turn for \"x\"(0-19): "))
    if x not in xx and x in yy:
        xx.append(x)
        return x
    else:
        print ("Try again")
        zadani_x()
xx=[]
yy=[x for x in range(20)]
like image 540
china Avatar asked Jan 29 '26 17:01

china


1 Answers

the problem here is the recursive call to the function, you don't return the value you get from it

def zadani_x():
    x=int(input("Turn for \"x\"(0-19): "))
    if x not in xx and x in yy:
        xx.append(x)
        return x
    else:
        print ("Try again")
        return zadani_x()   #here was the problem

in this particular case is better write this in a while loop if you want to ejecute the same code over and over, because calling a function cost more that a loop and with a loop is more crear your intention:

def zadani_x():
    while True:
        x=int(input("Turn for \"x\"(0-19): "))
        if x not in xx and x in yy:
            xx.append(x)
            return x
        else:
            print ("Try again")

I don't know what your intentions are with this function, but in any of the versions when xx have all the elements of yy you will fall in a infinite loop if you call this function...

like image 86
Copperfield Avatar answered Feb 02 '26 14:02

Copperfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!