(初学者)Python程序完全只在单独运行函数时才起作用。比赛追踪计划:

时间:2014-12-24 10:54:38

标签: python sorting indexing tournament

所有这些代码在单独运行时功能完美。但是,当我在运行new和fixture选项后选择standings选项时,代码会抛出错误。对此事的任何帮助将不胜感激。

main():

       print ("Welcome to Tournament Tracker")
       print ("would you like to begin a new tournament (new), input the results of a fixture (fixture) or view the tournament standings(standings)")
       #allows the user to choose from several options including accesing an old tournament or creating a new one.
       response = input()
       #defines a variable "response" which will be checked against predefined, suggested responses using a slection statement
       if response == "new":
       #selection statment checks if variable "response" is = "new" and, if true, executes the following code
                  print ("enter in the name of the tournament")
                  tournamentName = input()
                  #creates variable tournamentName and sets it to user input
                  with  open(tournamentName + ".txt",mode="w",encoding = "utf-8") as tournamentfile:
                             pass
                  #creates file "tournamentName + ".txt""
                  print ("enter in the number of teams in the tournament")
                  numberOfTeams = int(input())
                  allPoints = int(0)
                  awayPoints = int(0)
                  #initalises the two variables "allPoints" and "awayPoints" to be written to text file
                  counter = int(0)
                  #initialises temporary variable counter to be used for iteration
                  while counter < numberOfTeams:
                  # while loop executes the following code unless the condition "counter" < "number of teams"
                             counter = counter +1
                             #one is added to the counter to ensure that the condition "counter" < "number of teams" will be met
                             print ("enter in the name of team {0}".format(counter))
                             teamName = input()
                             #asks the user for the name of each team linked to variable counter
                             print ("Team {0} is {1}".format(counter,teamName))
                             with open(teamName + "Points.txt", mode="w",encoding="utf-8") as allPointsfile:
                                        allPointsfile.write(str(allPoints))
                             #creates a txt file based on the variable "teamName", with "Points.txt" appended to it,
                             #inputted by the user and writes the variable "allPoints" to it 
                             with open(teamName + "AwayPoints.txt", mode = "w",encoding = "utf-8") as awayPointsfile:
                                        awayPointsfile.write(str(awayPoints))
                             #creates a txt file based on the variable "teamName", with "AwayPoints.txt" appended to it,
                             #inputted by the user and writes the variable "awayPoints" to it 
                             with open(tournamentName + ".txt", mode="a",encoding="utf-8") as tournamentfile:
                                        tournamentfile.write(teamName +"\n")
                                        tournamentfile.write(str(allPoints) + "\n")
                                        tournamentfile.write(str(awayPoints) + "\n")
                             #creates a txt file based on the variable "tournamentName", with ".txt" appended to it,
                             #inputted by the user and writes the variables "teamName", "allPoints" and "awayPoints" to it,
                             #each on a new line 
                  print("You may now add the results of fixtures")
                  main()
                  #informs the user that the next recommended option should be to input the results of a fixture
                  #and then calls the main function to give the user access to the all the options again 
       elif response == "fixture":
       #selection statment checks if variable "response" is = "fixture" and, if true,then executes the following code
                  print ("enter in the name of the tournament")
                  tournamentName = input() 
                  print ("enter in the name of the first (home) team")
                  teamOne = str(input())
                  print ("enter in the name of the second (away) team")
                  teamTwo = str(input())
                  print ("enter in the number of goals scored by the first team in their home fixture")
                  teamOneScore = input()
                  print("enter in the number of goals scored by the second team in the same fixture")
                  teamTwoScore = input()
                  #initialises variables "tournamentName", "teamOne", "teamOne", "teamOneScore" and "teamTwoScore"
                  if teamOneScore > teamTwoScore:
                  #selection statment checks if the variable "teamOneScore" > "teamTwoScore" and if true, executes the following code
                            with open(teamOne + "Points.txt", mode="r",encoding="utf-8") as allTeamOnePointsfile:
                                        allTeamOnePoints = allTeamOnePointsfile.read()
                                        if allTeamOnePoints == '':
                                            allTeamOnePoints  = 0
                                        allTeamOnePoints = int(allTeamOnePoints) + int(3)
                            #opens the file " teamOne (variable) + "Points.txt"" in read mode and reads the file. If statement checks if the file is empty
                            #and sets the value read, defined as "allTeamOnePoints" to 0 to avoid an error. Then adds 3 to "allTeamOnePoints"
                            with open(teamOne + "Points.txt", mode="w",encoding="utf-8") as allTeamOnePointsfile:
                                        allTeamOnePointsfile.write(str(allTeamOnePoints))
                            #opens the file " teamOne (variable) + "Points.txt"" in write mode and writes the variable "allTeamOnePoints" to the file. 
                                        print("{0} now has {1} points".format(teamOne,allTeamOnePoints))
                            #outputs the team name and the total number of points that team has
                            with open(teamTwo + "Points.txt", mode="r",encoding="utf-8") as allTeamTwoPointsfile:
                                        allTeamTwoPoints = allTeamTwoPointsfile.read()
                                        if allTeamTwoPoints == '':
                                            allTeamTwoPoints  = 0
                            #opens the file " teamTwo (variable) + "Points.txt"" in read mode and reads the file. If statement checks if the file is empty
                            #and sets the value read, defined as "allTeamTwoPoints" to 0 to avoid an error.
                                        print("{0} now has {1} points".format(teamTwo,allTeamTwoPoints))
                            #outputs the total points for teamTwo 
                            with open(tournamentName + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
                                        tournamentList1 = tournamentFile.readlines()
                                        tournamentList = [elem.strip("\n")for elem in tournamentList1]
                                        #open the file "tournamentName (variable) + ".txt"" and reads it, with each line defined as a different element of an array
                                        #then strips the ""\n"" from the end of each element and defines the variable "tournamentList"
                                        index = 0
                                        #initialises temporary variable "index"
                                        noOfTeams = int(len(tournamentList))
                                        #initialises variable "noOfTeams" as the length of the arrray "tournamentList"
                                        while index < noOfTeams:
                                        #while loop checks if  temporary variable "index" < "noOfTeams"
                                                   if teamOne == tournamentList[index]:
                                                              tournamentList[index]= teamOne
                                                              tournamentList[index+1] = allTeamOnePoints
                                                              index = index +1
                                                   #selection statement checks if the variable "teamOne" is equal to the index'th element of the array "tournamentList"
                                                   #sets variable "teamOne" to the index'th element of array "tournamentList" if the previous condition is true
                                                   #sets variable "allTeamOnePoints" to the index'th element of array "tournamentList" if the previous condition is true
                                                   #adds 1 to index to allow for iteration
                                                   elif teamOne != tournamentList[index]:
                                                              index = index +1
                                                   #selection statement checks if the variable "teamOne" is equal to the index'th element of the array "tournamentList"
                                                   #adds 1 to index to allow for iteration

                                        index2 = 0
                                        #initialises temporary variable "index"
                                        while index2 < noOfTeams:
                                                   if teamTwo == tournamentList[index2]:
                                                              tournamentList[index2] = teamTwo
                                                              tournamentList[index2+1] = allTeamTwoPoints
                                                              index2 = index2 +1
                                                   #selection statement checks if the variable "teamTwo" is equal to the index2'th element of the array "tournamentList"
                                                   #sets variable "teamTwo" to the index'th element of array "tournamentList" if the previous condition is true
                                                   #sets variable "allTeamTwoPoints" to the index'th element of array "tournamentList" if the previous condition is true
                                                   #adds 1 to index2 to allow for iteration
                                                   elif teamTwo != tournamentList[index2]:
                                                              index2 = index2 +1
                                                   #selection statement checks if the variable "teamTwo" is equal to the index'th element of the array "tournamentList"
                                                   #adds 1 to index2 to allow for iteration
                            with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
                                        for counter in range (len(tournamentList)):
                                        #for loop executes the following code the once for each element in array "tournamentList"
                                                   tournamentFile.write(str(tournamentList[counter]) + "\n")
                            #writes variable "tournamentList" to "tournamentName + ".txt"" using for loop 
                                        main()
                                        #calls back the function "main()"



                  elif teamOneScore == teamTwoScore:
                  #the following code is very similar to the above code. Please see above code for documentation.
                            with open(teamOne + "Points.txt", mode="r",encoding="utf-8") as allTeamOnePointsfile:
                                        allTeamOnePoints = allTeamOnePointsfile.read()
                                        if allTeamOnePoints == '':
                                            allTeamOnePoints  = 0
                                        allTeamOnePoints = int(allTeamOnePoints) + int(1)
                            with open(teamOne + "Points.txt", mode="w",encoding="utf-8") as allTeamOnePointsfile:
                                        allTeamOnePointsfile.write(str(allTeamOnePoints))
                                        print("{0} now has {1} points".format(teamOne,allTeamOnePoints))
                            with open(teamTwo + "Points.txt", mode="r",encoding="utf-8") as allTeamTwoPointsfile:
                                        allTeamTwoPoints = allTeamTwoPointsfile.read()
                                        if allTeamTwoPoints == '':
                                            allTeamTwoPoints  = 0
                                        allTeamTwoPoints = int(allTeamTwoPoints) + int(1)
                            with open(teamTwo + "Points.txt", mode="w",encoding="utf-8") as allTeamTwoPointsfile:
                                        allTeamTwoPointsfile.write(str(allTeamTwoPoints))
                                        print("{0} now has {1} points".format(teamTwo,allTeamTwoPoints))
                            with open(teamTwo + "AwayPoints.txt",mode = "r",encoding="utf-8") as awayPointsfile:
                                        awayPoints = awayPointsfile.read()
                                        if awayPoints == '':
                                            awayPoints  = 0
                                        awayPoints = int(awayPoints) + int(1)
                            with open(teamTwo + "AwayPoints.txt",mode = "w",encoding="utf-8") as awayPointsfile:
                                        awayPointsfile.write(str(awayPoints))
                            with open(tournamentName + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
                                         tournamentList1 = tournamentFile.readlines()

                                         tournamentList = [elem.strip("\n")for elem in tournamentList1]

                                         index = 0
                                         noOfTeams = int(len(tournamentList))
                                         while index < noOfTeams:
                                                   if teamOne == tournamentList[index]:
                                                              tournamentList[index]= teamOne
                                                              tournamentList[index+1] = allTeamOnePoints
                                                              index = index+1
                                                   elif teamOne != tournamentList[index]:
                                                              index = index +1
                                         index2 = 0
                                         while index2 < noOfTeams:
                                                   if teamTwo == tournamentList[index2]:
                                                              tournamentList[index2] = teamTwo
                                                              tournamentList[index2+1] = allTeamTwoPoints
                                                              tournamentList[index2+2] = awayPoints
                                                              index2 = index2+1
                                                   elif teamTwo != tournamentList[index]:
                                                              index2 = index2 +1
                            with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
                                        for counter in range (len(tournamentList)):
                                                   tournamentFile.write(str(tournamentList[counter]) + "\n")
                                                   print (tournamentList)
                                        main()



                  elif teamOneScore < teamTwoScore:
                  #the following code is very similar to the above code. Please see above code for documentation.
                             with open(teamTwo + "Points.txt", mode="r",encoding="utf-8") as allTeamTwoPointsfile:
                                        allTeamTwoPoints = allTeamTwoPointsfile.read()
                                        if allTeamTwoPoints == '':
                                            allTeamTwoPoints  = 0
                                        allTeamTwoPoints = int(allTeamTwoPoints) + int(3)
                             with open(teamTwo + "Points.txt", mode="w",encoding="utf-8") as allTeamTwoPointsfile:
                                        allTeamTwoPointsfile.write(str(allTeamTwoPoints))
                                        print("{0} now has {1} points".format(teamTwo,allTeamTwoPoints))
                             with open(teamTwo + "AwayPoints.txt",mode = "r",encoding="utf-8") as awayPointsfile:
                                        awayPoints = awayPointsfile.read()
                                        if awayPoints == '':
                                            awayPoints  = 0
                                        awayPoints = int(awayPoints) + int(3)
                             with open(teamTwo + "AwayPoints.txt",mode = "w",encoding="utf-8") as awayPointsfile:
                                        awayPointsfile.write(str(awayPoints))
                             with open(teamOne + "Points.txt", mode="r",encoding="utf-8") as allTeamOnePointsfile:
                                        allTeamOnePoints = allTeamOnePointsfile.read()
                                        if allTeamOnePoints == '':
                                            allTeamOnePoints  = 0
                                        print("{0} now has {1} points".format(teamOne,allTeamOnePoints))
                             with open(tournamentName + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
                                         tournamentList1 = tournamentFile.readlines()

                                         tournamentList = [elem.strip("\n")for elem in tournamentList1]

                                         index = 0
                                         noOfTeams = int(len(tournamentList))
                                         while index < noOfTeams:
                                                   if teamOne == tournamentList[index]:
                                                              tournamentList[index]= teamOne
                                                              tournamentList[index+1] = allTeamOnePoints
                                                              index = index+1
                                                   elif teamOne != tournamentList[index]:
                                                              index = index +1
                                         index2 = 0
                                         while index2 < noOfTeams:
                                                   if teamTwo == tournamentList[index2]:
                                                              tournamentList[index2] = teamTwo
                                                              tournamentList[index2+1] = allTeamTwoPoints
                                                              tournamentList[index2+2] = awayPoints
                                                              index2 = index2 + 1
                                                   elif teamTwo != tournamentList[index2]:
                                                              index2 = index2 +1
                             with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:

                                        for counter in range (len(tournamentList)):
                                                   tournamentFile.write(str(tournamentList[counter]) + "\n")
                                                   print (tournamentList)
                                        main()

       elif response == "standings":
       #selection statment checks if variable "response" is = "fixture" and, if true,then executes the following code
                  results()

def results():
           print ("enter in the name of the tournament you would like to access")
           tournamentName1 = input()
           #creates variable "tournamentName" and sets it equal to user input
           with open (tournamentName1 + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
                      tournamentTeam1 = tournamentFile.readlines()[::3]
                      tournamentTeams1 = [elem.strip("\n")for elem in tournamentTeam1]
           #opens the file "tournamentName + ".txt"" and reads every third line into a list. Then strips ""\n"" from every element
           #defines the variable "tournamentTeams" as an array of al teams in the tournament
           with open (tournamentName1 + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
                      tournamentPoint1 = tournamentFile.readlines()[1::3]
                      tournamentPoints1 = [elem.strip("\n")for elem in tournamentPoint1]
           #opens the file "tournamentName + ".txt"" and reads every third line starting from the second element
           #into a list. Then strips ""\n"" from every element
           #defines the variable "tournamentPoints" as an array with all the total points for each team
           with open (tournamentName1 + ".txt", mode = "r", encoding = "utf-8") as tournamentFile:
                      tournamentAwayPoint1 = tournamentFile.readlines()[2::3]
                      tournamentAwayPoints1 = [elem.strip("\n")for elem in tournamentAwayPoint1]
           #opens the file "tournamentName + ".txt"" and reads every third line starting from the third element
           #into a list. Then strips ""\n"" from every element
           #defines the variable "tournamentAwayPoints" as an array with all the total away points for each team
                      order = []
                      #defines temporary array order as an empty array
                      pos = 0
                      #defines temporary variable "pos" as equal to 0
                      for count in range(len(tournamentTeams1)):
                           order.append(count)
                           #creates an array of indexes of the teams
                      for count in range(len(tournamentTeams1)-1):
                           if (tournamentPoints1[order[pos]] < tournamentPoints1[order[pos+1]]):
                                 #compares the scores of two consecutive teams and switches them
                                 temp = order[pos]
                                 #temporary variable stores the index of the team
                                 order[pos] = order[pos+1]
                                 order[pos+1] = temp
                                 #switches the order of the teams
                           elif (tournamentPoints1[order[pos]] == tournamentPoints1[order[pos+1]] and tournamentAwayPoints1[order[pos]] <tournamentAwayPoints1[order[pos+1]]):
                                 #if the score is equal, we compare the away score
                                 temp = order[pos]
                                 order[pos] = order[pos+1]
                                 order[pos+1] = temp
                                 #same logic as prior
                           pos = pos +1
                           #adds 1 to variable "pos" in order to allow for iteration
                      index3 = 0
                      #defines temporary variable index as equal to 0
                      print()
                      for count in range(len(order)):
                          index3 = index3 + 1
                          print('{0}: {1} (score {2}) (away score {3})'.format(index3,tournamentTeams1[order[count]],tournamentPoints1[order[count]],tournamentAwayPoints1[order[count]]))
                      print("Congratulations to team {0} for winning the tournament!".format(tournamentTeams1[order[pos]]))
                      #print outs the winning team of the tournament

确切的错误消息:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    main()
  File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 47, in main
    main()
  File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 129, in main
    main()
  File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 244, in main
    results()
  File "/Users/MunshiMuhammed/Desktop/Coursework Coding Folder/Actually done coursework m8 (2).py", line 296, in results
    print("Congratulations to team {0} for winning the tournament!".format(tournamentTeams1[order[pos]]))
IndexError: list index out of range

结果函数中正在读取的文本文件: (队名第一线,第二线是主分,第三线是客场分。下一线是下一队) 3 0 0 4 3 0

这些是要求的打印陈述(tournamentTeams1,order和pos) [&#39; 3&#39;,&#39; 4&#39;] [1,0] 1 1:4(得分3)(客场得分0) [&#39; 3&#39;,&#39; 4&#39;] [1,0] 1 2:3(得分0)(客场得分0) 恭喜第3队赢得比赛!

再一次,此功能仅在重新启动空闲后访问时才有效。

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的那样,需要花费很多代码。

要获得更好的回复MCVE是关键。查看错误消息,您会发现它出现在 结果 功能中。因此,您应该尝试仅使用该函数复制错误,以及一些最小数据。如果你不能,你需要检查哪些输入进入函数(这是插入打印语句的内容)。然后弄清楚代码的哪些位产生了那些奇怪的输入,并尝试隔离代码的那一部分。重复此过程,直到您缩小可能出现问题的代码区域。然后发布代码的位,以及输入和输出。 欢迎来到精彩的调试世界!

所有这一切,我确实通过了代码,我我知道出了什么问题。 当您以递归方式调用main()时,实际上是在不关闭tournamentName文件的情况下调用它,然后您尝试在results()函数中访问该文件。下面是对#(固定装置)中的main()的有问题的递归调用。部分代码。

with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
    for counter in range (len(tournamentList)):
    #for loop executes the following code the once for each element in array "tournamentList"
        tournamentFile.write(str(tournamentList[counter]) + "\n")
        #writes variable "tournamentList" to "tournamentName + ".txt"" using for loop 
    main() #Notice the indentation!

缩进意味着将在写入模式下访问tournamentName.txt文件,因此当您尝试从results()函数访问它时,您将获得一个空文件。如果tournamentName.txt文件为空,则results()函数会在最后一行抛出一个IndexError。

立即解决方案是在open(...)之外对main()进行递归调用,即它应该如下所示:

with open(tournamentName + ".txt", mode = "w", encoding = "utf-8") as tournamentFile:
    #Your for loop remains here
main() #At this point tournamentName.txt is closed, available for results() to access

您需要在代码的所有三个位置更新它。

另一方面,正如@ pm-2ring所述,对main()的递归调用可能不是最好的主意。我强烈建议重构你的代码,以便main函数变成一个如下所示的循环。

def main():
    print("Welcome to Tournament Tracker")
    while True:
        response = input("would you like to begin a new tournament (new), input the results of a fixture (fixture) or view the tournament standings(standings)\n")
        if response == "new":
            create_new_tournament()
        elif response == "fixture":
            add_fixtures()
        elif response == "standings":
            print_results()
            return

我发现你的代码还有其他四个大问题:

  1. 您的results()函数有一个错误,即得分最低的团队最终会在订单列表的末尾,而应该是得分最高的团队。
  2. 你的main()函数太长了。将它拆分成碎片对我在开始时编写的内容有很大帮助 - 小函数可以很容易地隔离导致问题的代码部分,并且可以轻松地将小代码片段发布到stackoverflow上。
  3. 您的评论在字面上描述了代码的功能,并没有提供有关预期效果的详细信息。在编写简短函数之后,您应该解释这些函数期望的输入以及它们应该产生的输出。通常,这是您在Python中需要的所有评论(假设您要小心功能和变量名称!)
  4. 您的代码有很多重复,特别是在&#39;灯具&#39;部分。您需要尽量不要复制和粘贴代码,因为这会使调试/更新变得更加困难 - 您可能会修复一些代码但忘记相同的部分。