Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

what's wrong in my code when using files in python?

+2 votes
asked Nov 19, 2020 by npatel300 (1,440 points)
name1_front = "Charles"

student_name = "charles", "Chelsea", "Mary"

name3_end = "Mary"

def main():

num_students = int(input('how many students in class:?'))

#open the names.txt file for reading

name_file = open('names.txt', 'r')

for count in range(1, num_students + 1):

student_name = int(input('enter the name of student:'))

#read the names to file

name_file.read(student_name)

#close the File

name_file.close()

print('Data read to names.txt.')

print('The student that would be front of the line is', name1_front)

print('The student that would be end of the line is', name3_end)

#call the main function

main()

1 Answer

0 votes
answered Nov 19, 2020 by LiOS (6,420 points)
The initial issue with your code is the indentation but this may been caused by you pasting your code. Python uses indentation to enter and leave code blocks. Other languages such as C use curly braces { }

Once your indentation is sorted, re-look at what you want to do and your code. One issue is that you've opened a handle to a file in read and trying to write to it. Additionally, the loop to enter names is incorrect and causes an error as your asking for an integer input but based on the question wanting a name (string).

There's some other issues but you should find them - Best of luck!
commented Nov 19, 2020 by npatel300 (1,440 points)
yes, I had indented the code but I pasted it, so became unindented. And I have fixed the integer to string. But, still the code doesn't work.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...