Home > Back-end >  unexpected "None" in list
unexpected "None" in list

Time:11-28

i wanted to make a game where you guess the letter. and add a function that will show you all you incorrect guesses, so i made the list:

incorrectguesses = []

and then i made it so it asks the user to guess the letter:


while True:
    guess = input("what do you think the letter is??  ")
    if guess == secret_letter:
        print("you guessed it!")
        break
    else:
        incorrectguesses  = [guess]

and you can see that i added the guess to the list if it was wrong.

then, i added a function to print out every item in the given list:

def print_all_items(list_): 
    for x in list_: 
        print(x)

and then i ran the function at the end of the loop:

print(print_all_items(incorrectguesses))

but this was the result:

what do you think the letter is?? a

a

None

what do you think the letter is?? b

a

b

None

as you can see, it adds "None" to the end of the list.

thanks if you could help me

CodePudding user response:

print(print_all_items(incorrectguesses))

You're printing the result of the print_all_items() function.

However, that function has no return statement, so it returns None by default.

So, the result of the function is None, and that gets printed.

Since the function itself prints the results, I think you actually just want to call the function, not print its result.

CodePudding user response:

As someone else pointed earlier (beat me to it), it's because you are printing a function that has no return. (In depth explanation a the end).

while True:
    guess = input("what do you think the letter is??  ")
if guess == secret_letter:
    print("you guessed it!")
    break
else:
    incorrectguesses  = [guess]
    print_all_items(incorrectguesses) # ←

You want to call the function, not print it.

That way the function is being run, and prints the elements of incorrectguesses.


Explanation

When you do print(<something>), the print() function is waiting for a value to be returned.

In this case because the <something> is a function, Python runs that function "inside" the print(). When your function print_all_items() is being run, it prints all the elements of the list. Once print_all_items() has finished running, and printed everything, the function doesn't return a value, so it defaults to None. Therefore, the value of the <something> the print(<something>) was waiting for is gets assigned a None value.

I hope I could help!

  • Related