我的程序没有正确迭代

2024-05-19 22:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个简单的程序,我的for循环有点不正常。它只读取最后一个条目。我知道它只是输出最后一个条目,我知道为什么,但我似乎无法修复它。 任何帮助都会很好。我可以让它以另一种方式运行,但我想使用循环

def main(): 



    testfile = open('tests.txt', 'w')

    #### THIS RUNS -- but only output is last entry #####

    for count in range(1, 6):
        test = int(input('Enter the test score: #' + \
                          str(count) + ' % '))




    testfile.write(str(test) + '\n')



    testfile.close()
    print('The scores are in the tests.txt file.')

main()

将输出转换为文本文件

>>> 
Enter the test score: #1 % 89
Enter the test score: #2 % 98
Enter the test score: #3 % 69
Enter the test score: #4 % 36
Enter the test score: #5 % 36
The scores are in the tests.txt file.
>>> 

Tags: theintesttxtformaincounttests
1条回答
网友
1楼 · 发布于 2024-05-19 22:47:26

Python关心缩进:循环中唯一的东西是input语句,因此write只发生一次:在输入最后一个值之后

您需要将write语句缩进到与input语句相同的位置,以将其放入循环中

相关问题 更多 >