如何正确使用全局变量(python)? [重复]

问题描述 投票:0回答:0

我正在用 python 编写一个程序来解决旅行商问题,但是我的全局变量一直出错

UnboundLocalError: 局部变量 'count' 在赋值前被引用

import math
import random
currentShortest = math.inf
listOfDistances = []
numOfPoints = int(input("Input number of points:"))
numOfRoutesParameter = numOfPoints - 1
loop = True
global count
count = 0
counter = 0
loop1 = True
equal = True

def numOfRoutes(n):
    summation = 1
    for num in range(2, n + 1):
        summation += num
    return(summation)
numberOfRoutes = numOfRoutes(numOfRoutesParameter)

while loop == True:
  if len(listOfDistances) < numberOfRoutes:
    distance  = int(input("Input next distance:"))
    listOfDistances.append(distance)
  else:
    print(listOfDistances)
    checkIfCorrectDistances = input("These are the distances you entered, in order. Please confirm that it is correct. \nIs it correct?")
    checkIfCorrectDistances = checkIfCorrectDistances.lower()
    if checkIfCorrectDistances == "yes":
      loop = False
    elif checkIfCorrectDistances == "no":
      listOfDistances.clear()
    else:
      print("\nAnswer with yes or no please.\n")

def CalculateADistance():
  calculatedDistance = 0
  a = 1
  b = random.randint(2, numOfPoints)
  if a != b:
    calculatedDistance += listOfDistances[b]
    count += 1
    while loop1 == True:
      if count != numberOfRoutes:
        a = b
        while equal == True:
          b = random.randint(2, numOfPoints)
          if a != b:
            equal = False
            point = a - 1
            point *= numberOfRoutes
            calculatedDistance += listOfDistances[point]
            count += 1
      else:
        loop1 = False
CalculateADistance()

这就是到目前为止的代码(你可以看出它还没有完成,我指的变量被标记为“计数”。 PS:我也遇到了程序自行恢复的问题,尽管这不是问题所在,但如果有人能解释我如何解决这个问题,我将不胜感激。

我试过用“count = 0”交换“global count”,这实际上是原来的方式,这给了我同样的错误。我还尝试将其设为函数内的局部变量,但这不起作用,因为它不再发挥作用,以防万一您不了解它的用途,它会跟踪它已经访问了多少点,如果你知道旅行商问题是什么,这就更有意义了。

python python-3.x global-variables global traveling-salesman
© www.soinside.com 2019 - 2024. All rights reserved.