Python简易日记程序TMC测试失败求助:输入0输出不符
日记程序退出测试失败问题排查
提交至TMC的简易日记程序在test_1_exit_only测试中失败,测试要求输入0退出时程序输出两行内容,但当前代码仅输出一行Bye now!。相关代码如下:
with open("diary.txt") as my_file: entries = my_file.read() while True: operation = input("1 - add an entry, 2 - read entries, 0 - quit\nFunction:") if operation == "1": content = input("Diary entry: ") with open("diary.txt","a") as diary: diary.write(f"{content}\n") print("Diary saved\n") elif operation == "2": print("Entries: ") with open("diary.txt") as diary: for row in diary: print(row) elif operation == "0": print('Bye now!'+"\n") break
问题原因
当前退出分支使用print('Bye now!'+"\n"),虽然视觉上会显示Bye now!和一个空行,但该语句仅调用了一次print函数,输出的是包含换行符的单行内容。而测试用例要求的是两行独立的输出,需要通过两次print调用来实现。
解决方法
将退出分支的代码修改为两次print调用,示例如下:
elif operation == "0": print('Bye now!') print() break
或者根据测试预期的换行位置调整顺序,先输出空行再显示退出提示:
elif operation == "0": print() print('Bye now!') break
这样就能输出两行内容,满足测试要求。
内容的提问来源于stack exchange,提问作者Yan Zhuang
相关产品推荐
相关产品推荐

