如何使此循环正常工作? [英] How do I get this loop to work correctly?

查看:86
本文介绍了如何使此循环正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Wondering why I am not getting output into a file with this code. The loop is not working it is only catching the last entry. Whatever the last score I put in is what goes in the file. I have tried everything that I can think of or find online. The program jumps to main() back to def main(): then to testfile and I get an error that reads global name open is not defined, then the program terminates. Any help would be great. Thanks!



def main():  
    
    #num_tests = 0
    testfile = open('tests.txt', 'w')

    #### THIS RUNS -- but no output #####

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

   
    

    #test1 = int(input('Enter test number 1: % '))
    #test2 = int(input('Enter test number 2: % '))
    #test3 = int(input('Enter test number 3: % '))
    #test4 = int(input('Enter test number 4: % '))
    #test5 = int(input('Enter test number 5: % '))

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

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

main()

推荐答案

循环确实有效;它只是没有效果,因为你多次将值赋值给同一个变量。每次分配时,前一个值都会丢失,因此您只能看到上次分配的效果。以前的所有作业都没有副作用(输入数据请求除外,输入),因此整个循环只相当于一个作业,即最后一个作业。



-SA
The loop does work; it just has no effect, because you assign the value to the same variable several times. Each time you assign, the previous value is lost, so you see only the effect of the last assignment. All previous assignments have no side effect (except the request for input data, input), so the whole loop is equivalent to just one assignment, the last one.

—SA


这篇关于如何使此循环正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆