0

I am (attempting) to make a hacking game like Hack Run or Hacknet. But only the terminal. I get this error when I try to print the variable 'currentip' at line 86 ("print("You are currently at " + currentip + ".")"):

UnboundLocalError: local variable 'currentip' referenced before assignment

This looks like a simple error but I cannot figure it out. I have assigned it. Multiple times. Maybe I am reading the order execution wrong but I can't find any info that says I am doing it wrong...

Any ideas for cleaning up and making it neater/better is also very much appreciated.

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

Thanks!

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
Hamish Cox
  • 13
  • 3
  • Please post here the relevant parts of your source code as well as the error stacktrace that you get when you run the program. – Régis B. Aug 14 '16 at 10:29
  • Stacktrace: http://pastebin.com/DkYdgPDV – Hamish Cox Aug 14 '16 at 10:34
  • As for the relevant parts... I have no clue. I am a beginner with python. – Hamish Cox Aug 14 '16 at 10:35
  • 1
    You assign to `currentip`, so it is considered a *local*. Use `global currentip` in the function to mark it as a global instead. – Martijn Pieters Aug 14 '16 at 10:40
  • Thanks. But I will just say that I am a beginner and had no knowledge that local variables couldn't be used in functions and I could have no way of realizing to search for "Python variable scope error". I would have had to know to search for that specifically and having no knowledge of the problem I would have have to know the words to search for beforehand. – Hamish Cox Aug 14 '16 at 10:50

1 Answers1

2

The problem is that you have global variables in your code and you are trying to access them from inside the function without first declaring them global. You need to put a line global currentip at the beginning of your usecommand function.

Also note that if you only used the variable currentip in your function it would work, but if you are both using it and assigning it within the same function the interpreter assumes it is a local variable you are using. Take a look at this:

x = 10

def f():
    print x

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

Running function f() will print 10, but running function f2(0) will produce an error because the interpreter is once again unsure of whether the variable you are using is local or global and assumes it is a local one.

HTH.

Victor
  • 158
  • 8
  • More specifically, OP is modifying that value, pure read is fine, that is, "access" is kinda misleading. – YiFei Aug 14 '16 at 10:43
  • @YiFei, I have modified my answer to include some more information on the subject :) – Victor Aug 14 '16 at 10:45
  • Ohhhhh.... I see. I did not know that global and local variables were so important. I have never had this error before. I thought that golbal variables could be used in different programs etc. Don't ask me how you would do that or why I thought that though. Thanks Victor for your quick response. – Hamish Cox Aug 14 '16 at 10:49