-2

This seems like an incredibly silly problem, but it's doing my nut in. I just started working with Python a few days ago, after spending a while in other languages, and I've run into a very weird problem. I'm attempting to set a top-level string variable called 'word' to the concatenation of itself and a letter. Python is able to find the variable just fine, as demonstrated below.

statement of "word = letter"

However, any time I try to concatenate, I suddenly get an error telling me Python is unable to find the variable.

statements of "word += letter" and "word = word + letter"

The yellow squiggle is my IDE telling me that the variable can't be found. I've tried literally directly copy+pasting other solutions from other stack-exchange posts. It's a little embarrassing to be having this much trouble with concatenation, but I've tried most of the stuff I can think of.

Edit:Here's my code. As you can see, "word" is initialized at the top of the file:


word_dict = PyDictionary()
repeats = 5
word = "e"



 def handle_input(x, y, letter): 
    word += letter

    print(word)

    coords = make_coords(x, y)
    for list in grid:
        for button in list:
           button.update(disabled=True)
    for coord in coords:
        x = coord[0]
        y = coord[1]
        list = grid[y]
        button = list[x]
        button.update(disabled=False)



OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

3

Since your word is defined outside of the function, you need to redeclare it as a global variable:

def handle_input(x, y, letter): 
  global word #add this line
  word += letter

  print(word)

  coords = make_coords(x, y)
  for list in grid:
      for button in list:
          button.update(disabled=True)
  for coord in coords:
      x = coord[0]
      y = coord[1]
      list = grid[y]
      button = list[x]
      button.update(disabled=False)
Aniketh Malyala
  • 2,650
  • 1
  • 5
  • 14
0

When you defined your variable word outside the function, it became a global variable. Global variables are available from within any scope. So you can use it inside your function, but first you must redeclare it as a global variable inside your function by adding global word at the first line in the function.

def handle_input(x, y, letter): 
    global word

Another solution is to define your variable `word` inside the function so that it is declared as a local variable which can be accessible only in that function.
def handle_input(x, y, letter): 
    word = "e"
Mark Saleh
  • 41
  • 9