How it works...

We define a global variable at the top of our module, and we print out its value later, towards the bottom of our module.

That works.

Add this function towards the bottom of our module:

GUI_const_42_print_func.py

In the preceding code snippet, we use the module-level global. It is easy to make a mistake by shadowing global, as demonstrated in the following:

GUI_const_42_777.py

Note how 42 becomes 777, even though we are using the same variable name.

There is no compiler in Python that warns us if we overwrite global variables in a local function. This can lead to difficulties in debugging at runtime.

Without using the global qualifier (line 214), we get an error.

When we qualify our local variable with the global keyword, we can print out the value of the global variable as well as overwrite this value locally:

The global variables can be very useful when programming small applications. They can help us make data available across methods and functions within the same Python module and sometimes the overhead of OOP is not justified.

As our programs grow in complexity, the benefit we gain from using globals can quickly diminish.

It is best to avoid globals and accidentally shadowing variables by using the same name in different scopes. We can use OOP instead of using global variables.

We played around with the global variables within procedural code and learned how it can lead to hard-to-debug bugs. In the next recipe, we will move on to OOP, which can eliminate such bugs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.173.238