2016-04-13 10 views
0

Mein Code versucht, die älteste Bewertung in einer Textdatei zu löschen, wenn die Anzahl der Ergebnisse größer als drei ist. Dies ist die Textdatei:Warum sagt mir dieser Coden, dass lineno1 nicht existiert?

humzah:0:6:5 
ikrah:8:6:4 

Dies ist mein Code:

if userclass=="1": #if userclass is equal to 1 
    with open ("Class1scores.txt", "r") as dataforclass1:#open the class 1 file as 
#data for class 1 in read plus mode 
     lines = dataforclass1.read().splitlines() #lines is equal to each line on 
     #the file (list). 
     for lineno1, line in enumerate(lines): #for the line number 
      usertaken=input("Have you taken this quiz before, yes or no") #first ask if the user 
      #has done this quiz before 
      while True: #this states that while it is true 
         if usertaken=="yes": #if the user says yes continue the script 
         break 
         if usertaken=="no": #if the user says no continue the script 
         break 
         else: 
          print("That is not a valid answer! yes or no")#if the user 
          continue 
      if usertaken=="yes": #if they have then find the line and add to it 
       if line.startswith(username): 
        print("was found on line", lineno1) #tells the user what lines their name is on 
        lines[lineno1] += ":" + str(score) 
        break 
      else: 
       lines.append(username + ":" + str(score)) #if they have not add to 
       #a new line 
       break 
    data = "\n".join(lines) + "\n" #data is the list plus indents (\n means new 
    #line) 
    with open("Class1scores.txt", "w") as file: #opens the file in write mode 
     file.write(data) #this writes in to the file 
     print(data) 

with open('Class1scores.txt','r') as class1file:#with the text file 
#as class1file 
    lines = []#this creates an empty list 
    for x, line in enumerate(class1file):#to find x read the lines 
     if lineno1==x: 
      class1_list = line.split(':')#split the text file by : 
     if len(class1_list) > 4:#if theres more than 4 values 
      del class1_list[1]#delete the first score 
      line = ':'.join(class1_list)#the line is equal to the 
      #data with : as the seperator 
     lines.append(line)#append this to the list 
    with open("Class1scores.txt",'w') as writefile: 
     writefile.write(''.join(lines)) 

Für die Klasse 1 es Schleifen nur die Frage: „Sie dieses Quiz genommen haben, bevor“ und für die anderen Klassen, mit dem gleichen Code kopiert und eingefügt, es heißt "Lineno1 ist nicht definiert". Irgendeine Hilfe?

Antwort

0

lineno1 wird nur im if-Block definiert, in dem die Benutzerklasse gleich 1 ist. In allen anderen Fällen ist die Variable nie definiert und daher wird der Fehler ausgelöst.
Wenn Sie in der ersten Zeile Ihres Codes lineno1 definieren, wird es im ersten if-Block überschrieben, Sie können es aber auch im zweiten if-Block verwenden.

Verwandte Themen