-1

When I run this code, it responds with UnboundLocalError: local variable 'hhh' referenced before assignment. However, the global string 'temp' does not respond with such an error despite being defined in a similar manner. Any help would be fantastic, thank you.

    import random, os
def start():
    global level
    global hhh
    global temp
    level=1
    temp='     +-!'
    hhh='[X'
    os.system('CLS')
    actualcrawl()
def actualcrawl():
    print (temp)
    for a in range(2,128):
        hhh=hhh+temp[random.randrange(1,8)]
    hhh=hhh[:79]+'>'+hhh[80:]
    for i in range(1,3):
        a=random.randrange(3,8)
        b=random.randrange(6,15)
        hhh=hhh[:16*a+b-1]+'='+hhh[16*a+b:]
    for i in range(1,9):
        print (hhh[16*i-16:16*i])
Aeronomo
  • 13
  • 1

1 Answers1

0

Yes,you should take a look at this question Using global variables in a function other than the one that created them

Briefly speaking,if it is only reading from a name, and the name doesn't exist locally, it will try to look up the name in any containing scopes.That's what happens to temp,which will be found in the global scope.But with hhh,you do writing,which will make Python believe that hhh is a local variable.

And another thing,but more important,it is not recomended using global.You could invoke actualcrawl() in start(),and pass in hhh,temp,which is the way most people do.

EDIT

It is simple:

import random,os
def start():
    level=1
    temp='     +-!'
    hhh='[X'
    os.system('CLS')
    actualcrawl(temp,hhh)

def actualcrawl(temp,hhh):
    print (temp)
    for a in range(2,128):
        hhh=hhh+temp[random.randrange(1,8)]
    hhh=hhh[:79]+'>'+hhh[80:]
    for i in range(1,3):
        a=random.randrange(3,8)
        b=random.randrange(6,15)
        hhh=hhh[:16*a+b-1]+'='+hhh[16*a+b:]
    for i in range(1,9):
        print (hhh[16*i-16:16*i])

I don't know what language you use before Python,but you really don't need to declare a variable like in C/C++.Because when you assign to a variable, you are just binding the name to an object.See this python variables are pointers?

Community
  • 1
  • 1
laike9m
  • 18,344
  • 20
  • 107
  • 140
  • I have been programming in python for 2 days now and have no idea how to pass variables. How would one go about doing something like that? – Aeronomo Mar 28 '13 at 05:46
  • Nevermind, thank you very much. Passing variables works beautifully. – Aeronomo Mar 28 '13 at 06:01