You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python猜字母游戏中列表输出意外出现None的问题求助

问题原因与解决方法

为什么会出现None?

Python中,没有return语句的函数默认返回None。你的print_all_items函数内部只是循环打印列表元素,没有返回值,当你用print(print_all_items(incorrectguesses))调用时,相当于先执行函数打印元素,再打印函数的返回值None,所以每次都会多出一行None。


解决方法(二选一即可)

方法1:直接调用函数,不要用print包裹

既然函数内部已经实现了打印逻辑,直接调用函数就行,不需要额外用print包裹:

# 替换原来的print(print_all_items(...))
print_all_items(incorrectguesses)

修改后的完整循环代码:

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)  # 直接调用函数

方法2:修改函数返回字符串,再用print输出

如果希望函数只负责生成要打印的内容,把打印逻辑交给外部的print,可以修改函数返回拼接后的字符串:

def print_all_items(list_): 
    # 将列表元素用换行符拼接成字符串并返回
    return '\n'.join(list_)

调用时保持print(print_all_items(incorrectguesses))即可,这样函数返回的是拼接好的字符串,print会输出这个字符串,不会出现None。


修改后的运行效果

以输入a再输入b为例,输出会变成:

what do you think the letter is?? a
a
what do you think the letter is?? b
a
b

内容的提问来源于stack exchange,提问作者Typfout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:20:33