0

I am coding a program where I am using curses to create a UI and I have gotten the width and height of the terminal via a different command and I want to make those two variables global so that I can refer to them throughout the program without having to pass them in through parameters everytime (unless I should just do that?) here is a simple layout of the series of calls I have:

def three():
    print width, height

def two():
    three()

def one():
    two()

global width
global height

width, height = console.getTerminalSize()

one()

So I am getting the global name not defined error but not sure why as I have defined them as global first then called the series of functions, where did I go wrong?

Jay Bell
  • 77
  • 6

1 Answers1

1

You don't need to define global out in the main code; any variables declared there are global by default. You need to place global width and global height in the function where you call them. That tells Python to use the global version of the variable instead of making a local one with that name (which is the default behavior).

But to answer your other question: using globals is generally undesirable, and it's better to pass in parameters when you can. It's less risky.

Using global variables in a function other than the one that created them

Community
  • 1
  • 1
TheSoundDefense
  • 6,753
  • 1
  • 30
  • 42