Using Local Variables for Temporary Storage

Some computations are complex, and breaking them down into separate steps can lead to clearer code. In the next example, we break down the evaluation of the quadratic polynomial ax2+ bx + c into several steps. Notice that all the statements inside the function are indented the same amount of spaces in order to be aligned with each other. You may want to type this example into an editor first (without the leading >>> and ...) and then paste it to the Python shell. That makes fixing mistakes much easier:

 >>>​​ ​​def​​ ​​quadratic(a,​​ ​​b,​​ ​​c,​​ ​​x):
 ...​​ ​​first​​ ​​=​​ ​​a​​ ​​*​​ ​​x​​ ​​**​​ ​​2
 ...​​ ​​second​​ ​​=​​ ​​b​​ ​​*​​ ​​x
 ...​​ ​​third​​ ​​=​​ ​​c
 ...​​ ​​return​​ ​​first​​ ​​+​​ ​​second​​ ​​+​​ ​​third
 ...
 >>>​​ ​​quadratic(2,​​ ​​3,​​ ​​4,​​ ​​0.5)
 6.0
 >>>​​ ​​quadratic(2,​​ ​​3,​​ ​​4,​​ ​​1.5)
 13.0

Variables like first, second, and third that are created within a function are called local variables. Local variables get created each time that function is called, and they are erased when the function returns. Because they only exist when the function is being executed, they can’t be used outside of the function. This means that trying to access a local variable from outside the function is an error, just like trying to access a variable that has never been defined is an error:

 >>>​​ ​​quadratic(2,​​ ​​3,​​ ​​4,​​ ​​1.3)
 11.280000000000001
 >>>​​ ​​first
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 NameError: name 'first' is not defined

A function’s parameters are also local variables, so we get the same error if we try to use them outside of a function definition:

 >>>​​ ​​a
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 NameError: name 'a' is not defined

The area of a program that a variable can be used in is called the variable’s scope. The scope of a local variable is from the line in which it is defined up until the end of the function.

As you might expect, if a function is defined to take a certain number of parameters, a call on that function must have the same number of arguments:

 >>>​​ ​​quadratic(1,​​ ​​2,​​ ​​3)
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 TypeError: quadratic() takes exactly 4 arguments (3 given)

Remember that you can call built-in function help to find out information about the parameters of a function.

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

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