Thursday, July 11, 2013

Local

     Can the functions only have 1 argument? The answer is no. You can have as many as you want! You simply do this:

>>> def randomwords(randomword, otherRandomWord):
print(randomword)
print(otherRandomWord)
print("CHEESE")

>>> randomwords("Pickles", "Cow")
Pickles
Cow
CHEESE


     Remember to do the values in order! Otherwise they will be switched around.
     That was only 2 arguments, but that's not all you can do. You can do over 9,000 arguments (if you have the patience, not to mention time, to do that) if you want to. Although... If you want to do at least five or six arguments, you might want to think of doing a list instead of a bunch of variables.

     It's possible for a function to return things to us. It's called a result.
     In order to get results, you use the return function. Try this:

>>> def groceries(oranges):
            orangeCost=9
            orangeTotal=orangeCost * oranges
            return oranges

>>> groceries(3)
27
>>> groceries(8)
72
>>> groceries(19)
171
>>> groceries(9001)
81009

     So, our block of code used the parameter (or argument) to figure something out, then gave us what it figured. That's how the return function works. If you want to do stuff with the return value, you can simply call it inside a variable.
     orangeCost, oranges, and orangeTotal are all in the same block of code. The same line, even. Being variables, these are called local variables.
     Local variables only exist while the function is running. Try printing each variable:

>>> print(orangeCost)
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    print(orangeCost)
NameError: name 'orangeCost' is not defined
>>> print(orangeTotal)
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    print(orangeTotal)
NameError: name 'orangeTotal' is not defined
>>> print(oranges)
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    print(oranges)
NameError: name 'oranges' is not defined

     Right. That's what a local variable is. If a variable is in the main part of a program, and not in a function, that is called a global variable.
     We will continue global variables in the next article. See you next time!

No comments:

Post a Comment