Python Forum
im not sure what ive done wrong code doesnt run - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: im not sure what ive done wrong code doesnt run (/thread-38696.html)



im not sure what ive done wrong code doesnt run - dgizzly - Nov-12-2022

def main():
    again='y'
    while again=='y' or again=='Y':
        try:
            key=('A', 'C', 'A', 'B', 'B', 'D', 'D', 'A', 'C', 'A',
'B', 'C', 'D', 'C', 'B')
            while again=='y':
                print('_-_-_-_-_-'*5)
                name=input('Enter student name:')

                filename=input('\tEnter student file name: ')
                file=open(filename, 'r')
                i=0
                choice=file.readline()
                while choice!='':
                    choice=choice.rstrip('\n')
                    ans[i]=choice
                    choice=file.readline()
                    i+=1
                    correct=0
main()



RE: im not sure what ive done wrong code doesnt run - Yoriz - Nov-12-2022

It doesn't run because you have a try without a matching except

There are a few issues with your code for starters:
again is assigned as 'y' and never re-assigned so the first while loop will always be True.
The second while loop is not required.
key is repeatedly assigned on every while loop iteration and is never used.
A file is opened and never closed
ans is not defined


RE: im not sure what ive done wrong code doesnt run - rob101 - Nov-12-2022

[removed] posted at the exact same time as Yoriz


RE: im not sure what ive done wrong code doesnt run - deanhystad - Nov-16-2022

You don't need three while loops; one loop for entering the student name and file, one loop for reading the file. Actually, I would make the inner loop a for loop.
for line in file:
It is much easier using the file iterator than using readline().

You should close you file when you are done with it. Either use file.close() or use a context manager (with open(filename, "r") as file:).