2016-04-13 19 views
0

私のコードは、スコアの数が3より大きい場合、テキストファイルの中で最も古いスコアを削除しようとしています。これは私のコードであるなぜこのコードはlineno1が存在しないと伝えますか?

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

:クラス1の場合

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)) 

それだけで同じであり、他のクラスのために、「あなたは前にこのクイズをとっている」という質問をループこれはテキストファイルです"lineno1が定義されていません"と表示されます。どんな助け?

答えて

0

lineno1は、userclassが1のifブロックでのみ定義されます。それ以外の場合、変数は決して定義されないため、エラーがスローされます。
lineno1をコードの最初の行に定義すると、最初のifブロックで上書きされますが、2番目のifブロックでも使用できます。

関連する問題