我在Python代码中找不到错误

时间:2016-08-14 10:26:20

标签: python

我(尝试)制作像Hack Run或Hacknet这样的黑客游戏。但只有终端。当我尝试打印变量' currentip'在第86行("打印("你目前在" + currentip +"。")"):

UnboundLocalError: local variable 'currentip' referenced before assignment

这看起来像一个简单的错误,但我无法弄清楚。我已经分配了它。多次。也许我正在阅读订单执行错误但我无法找到任何信息说我做错了......

任何清理和整理/更好的想法也非常受欢迎。

import os
import random
from time import sleep
os.system("cls")

save = {}
ips = {"1337.1337.1337.1337": "Cheater's Stash"}
shells = []
storyips = ["Bitwise Test PC"]
currentip = "1.1.1.1"
homeip = "1.1.1.1"

def resetip():
  ip1 = random.randint(1, 999)
  ip2 = random.randint(1, 999)
  ip3 = random.randint(1, 999)
  ip4 = random.randint(1, 999)
  homeip = str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4)
  if homeip in ips:
    resetip()
  else:
    ips[homeip] = "Your Computer"
    currentip = homeip

def storyreset():
  for x in storyips:
    ip = (0, 0, 0, 0)
    ip1 = random.randint(1, 999)
    ip2 = random.randint(1, 999)
    ip3 = random.randint(1, 999)
    ip4 = random.randint(1, 999)
    ip = str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4)
    if ip in ips:
      storyreset()
    else:
      ips[ip] = x

def start():
  os.system("cls")
  print("Python 3.5, HackSim 1.1")
  print("")
  print("Loading modules...")
  print("")
  sleep(1)
  print("OS Loaded.")
  sleep(0.5)
  print("HELP Loaded.")
  sleep(0.5)
  print("FILE USE Loaded.")
  sleep(1)
  print("CONNECTIONS Loaded.")
  sleep(0.5)
  print("UTILS Loaded.")
  sleep(0.5)
  print("HACKS Loaded.")
  print("")
  sleep(1)
  print("Initiating command line...")
  sleep(1)
  commandline()

def usecommand(c):
  if c == "reboot":
    print("Rebooting...")
    sleep(3)
    start()
  elif c == "clear":
    os.system("cls")
  elif c == "quit":
    quit()
  elif c == "forkbomb":
    del ips[currentip]
    if homeip in ips:
      currentip = "Your Computer"
    else:
      resetip()
      currentip = "Your Computer"
  elif "connect " in c:
    if c[8:] in ips:
      connectip = ips[c[8:]]
      print("Connecting to ", connectip, " ", c[8:], "...")
      currentip = connectip
    else:
      print("This ip does not exist.")
  elif c == "connect":
    print("You are currently at " + currentip + ".")
    print("The syntax of this command is: connect <ip>.")
  else:
    print("Invalid command. Either the command does not exist or check the required syntax.")

def commandline():
  while True:
    command = input("> ")
    usecommand(command)

storyreset()
resetip()
start()

谢谢!

1 个答案:

答案 0 :(得分:2)

问题是你的代码中有全局变量,并且你试图从函数内部访问它们而不首先声明它们是全局的。您需要在global currentip函数的开头添加一行usecommand

另请注意,如果您在函数中仅使用变量currentip,它将起作用,但如果您同时使用它并在同一函数内分配它,则解释器会认为它是您正在使用的局部变量。看看这个:

x = 10

def f():
    print x

def f2(arg):
    if arg:
        x = 20
    else:
        print x

运行函数f()将打印10,但运行函数f2(0)将产生错误,因为解释器再次不确定您使用的变量是本地变量还是全局变量并假设这是当地的。

HTH。