Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
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()
Posted
Comments
Sergey Alexandrovich Kryukov 6-Jul-14 0:38am    
Why do you show garbage in your code sample, all those commented out lines? Clear sample is the key for solving problems...
—SA

1 solution

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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900