-->

The global Statement - Function [Python]

If you need to modify a global variable from within a function, use the global statement. If you have a line such as global eggs at the top of a function, it tells Python, “In this function, eggs refers to the global variable, so don’t create a local variable with this name.” For example, type the following code into the file editor and save it as sameName2.py:

  1. def spam():
  2. global eggs
  3. eggs = 'spam'
  4. eggs = 'global'
  5. spam()
  6. print(eggs)

When you run this program, the final print() call will output this:

Because eggs is declared global at the top of spam() u, when eggs is set to 'spam' v, this assignment is done to the globally scoped spam. No local spam variable is created.


There are four rules to tell whether a variable is in a local scope or global scope:

  1. If a variable is being used in the global scope (that is, outside of all functions), then it is always a global variable.
  2. If there is a global statement for that variable in a function, it is a global variable.
  3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.
  4. But if the variable is not used in an assignment statement, it is a global variable.

To get a better feel for these rules, here’s an example program. Type the following code into the file editor and save it as sameName3.py:

  1. def spam():
  2. global eggs
  3. eggs = 'spam' # this is the global
  4. def bacon():
  5. eggs = 'bacon' # this is a local
  6. def ham():
  7. print(eggs) # this is the global
  8. eggs = 42 # this is the global
  9. spam()
  10. print(eggs)

In the spam() function, eggs is the global eggs variable, because there’s a global statement for eggs at the beginning of the function u. In bacon(), eggs is a local variable, because there’s an assignment statement for it in that function v. In ham() w, eggs is the global variable, because there is no assignment statement or global statement for it in that function. If you run sameName3. py, the output will look like this:

In a function, a variable will either always be global or always be local. There’s no way that the code in a function can use a local variable named eggs and then later in that same function use the global eggs variable. Not e If you ever want to modify the value stored in a global variable from in a function, you must use a global statement on that variable.

If you try to use a local variable in a function before you assign a value to it, as in the following program, Python will give you an error. To see this, type the following into the file editor and save it as sameName4.py:

  1. def spam():
  2. print(eggs) # ERROR!
  3. eggs = 'spam local'
  4. eggs = 'global'
  5. spam()

If you run the previous program, it produces an error message.

  1. Traceback (most recent call last):
  2. File "C:/test3784.py", line 6, in <module>
  3. spam()
  4. File "C:/test3784.py", line 2, in spam
  5. print(eggs) # ERROR!
  6. UnboundLocalError: local variable 'eggs' referenced before assignment

This error happens because Python sees that there is an assignment statement for eggs in the spam() function u and therefore considers eggs to be local. But because print(eggs) is executed before eggs is assigned anything, the local variable eggs doesn’t exist. Python will not fall back to using the global eggs variable v.

Functions as “Blac k Boxes”

Often, all you need to know about a function are its inputs (the parameters) and output value; you don’t always have to burden yourself with how the function’s code actually works. When you think about functions in this high-level way, it’s common to say that you’re treating the function as a “black box.”

This idea is fundamental to modern programming. Later chapters in this book will show you several modules with functions that were written by other people. While you can take a peek at the source code if you’re curious, you don’t need to know how these functions work in order to use them. And because writing functions without global variables is encouraged, you usually don’t have to worry about the function’s code interacting with the rest of your program.

Exception Handling

Right now, getting an error, or exception, in your Python program means the entire program will crash. You don’t want this to happen in real-world programs. Instead, you want the program to detect errors, handle them, and then continue to run. For example, consider the following program, which has a “divide-byzero” error. Open a new file editor window and enter the following code, saving it as zeroDivide.py:

  1. def spam(divideBy):
  2. return 42 / divideBy
  3.  
  4. print(spam(2))
  5. print(spam(12))
  6. print(spam(0))
  7. print(spam(1))

We’ve defined a function called spam, given it a parameter, and then printed the value of that function with various parameters to see what happens. This is the output you get when you run the previous code:

  1. 21.0
  2. 3.5
  3. Traceback (most recent call last):
  4. File "C:/zeroDivide.py", line 6, in <module>
  5. print(spam(0))
  6. File "C:/zeroDivide.py", line 2, in spam
  7. return 42 / divideBy
  8. ZeroDivisionError: division by zero

A ZeroDivisionError happens whenever you try to divide a number by zero. From the line number given in the error message, you know that the return statement in spam() is causing an error.

Errors can be handled with try and except statements. The code that could potentially have an error is put in a try clause. The program execution moves to the start of a following except clause if an error happens. You can put the previous divide-by-zero code in a try clause and have an except clause contain code to handle what happens when this error occurs.

  1. def spam(divideBy):
  2. try:
  3. return 42 / divideBy
  4. except ZeroDivisionError:
  5. print('Error: Invalid argument.')
  6.  
  7. print(spam(2))
  8. print(spam(12))
  9. print(spam(0))
  10. print(spam(1))

When code in a try clause causes an error, the program execution immediately moves to the code in the except clause. After running that code, the execution continues as normal. The output of the previous program is as follows:

  1. 21.0
  2. 3.5
  3. Error: Invalid argument.
  4. None
  5. 42.0

Note that any errors that occur in function calls in a try block will also be caught. Consider the following program, which instead has the spam() calls in the try block:

  1. def spam(divideBy):
  2. return 42 / divideBy
  3. try:
  4. print(spam(2))
  5. print(spam(12))
  6. print(spam(0))
  7. print(spam(1))
  8. except ZeroDivisionError:
  9. print('Error: Invalid argument.')

When this program is run, the output looks like this:


  1. 21.0
  2. 3.5
  3. Error: Invalid argument.

The reason print(spam(1)) is never executed is because once the execution jumps to the code in the except clause, it does not return to the try clause. Instead, it just continues moving down as normal.


0 Response to "The global Statement - Function [Python]"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel