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

Python家庭物品追踪程序输入行出现None异常的问题求助

问题:Python程序运行时出现未预期的"None"输出

我编写了一款用于追踪家庭物品并将数据输出至文本文件的Python程序,通过while循环让程序持续运行,直至输入“exit”时退出。但运行时输入行下方会出现未预期的“None”字样,我并未编写相关输出逻辑,怀疑是否由while(True)导致?

原代码:

HouseHoldItems = open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a')
Items = ''
Value = ''

# while loop to keep program running until user enters "Exit"
while(True):

    # Items is the primary variable, determines if user is entering new household item or wants to end the program
    Items = input(print("Enter an Item (Or type 'Exit' to quit) : "))

    # If statement to determine if user wants to end program
    if(Items.lower() == "exit"):
        break

    # Else statement to write household items to the file, followed by value of items
    else:
        HouseHoldItems.write(Items + ', ')
        Value = input(print("Enter an estimated Value: "))
        HouseHoldItems.write(Value + '\n')

HouseHoldItems.close()

问题原因

这个问题和while(True)完全无关,根源在你调用input()的方式:

你在input()里嵌套了print()函数,而print()本身的返回值是None。执行input(print("提示语"))时,会先运行print()输出提示,然后input()会把它接收的参数(也就是print()返回的None)打印出来,这就是你看到的多余"None"的原因。

修正方案

直接把提示字符串作为input()的参数即可,input()函数本身就支持输出提示文本,不需要嵌套print():

修正后的代码

HouseHoldItems = open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a')
Items = ''
Value = ''

while True:
    Items = input("Enter an Item (Or type 'Exit' to quit) : ")
    
    if Items.lower() == "exit":
        break
    
    HouseHoldItems.write(Items + ', ')
    Value = input("Enter an estimated Value: ")
    HouseHoldItems.write(Value + '\n')

HouseHoldItems.close()

另外补充两个小优化建议:

  • while(True)可以简化为while True,Python里不需要括号包裹条件
  • 推荐使用with语句管理文件,避免忘记关闭文件的问题,优化后的代码如下:
with open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a') as HouseHoldItems:
    Items = ''
    Value = ''
    
    while True:
        Items = input("Enter an Item (Or type 'Exit' to quit) : ")
        
        if Items.lower() == "exit":
            break
        
        HouseHoldItems.write(Items + ', ')
        Value = input("Enter an estimated Value: ")
        HouseHoldItems.write(Value + '\n')

使用with语句的话,文件会在代码块结束后自动关闭,更安全可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:11:08