Python 101 (part 6): Hedgehogs, Pythons And Funky Chameleons - Arguing Your Case
(Page 7 of 10 )
Now, if you've been paying attention, you've seen how functions can help you segregate blocks of code, and use the same piece of code over and over again, thereby eliminating unnecessary duplication. But this is just the tip of the iceberg...
The functions you've seen thus far are largely static, in that the variables they use are already defined. But it's also possible to pass variables to a function from the main program - these variables are called "arguments", and they add a whole new level of power and flexibility to your code.
To illustrate this, let's go back a couple of pages and revisit the tempConv() function.
def tempConv():
celsius = 35
fahrenheit = (celsius * 1.8) + 32
return fahrenheit
As is, this function will always calculate the Fahrenheit equivalent of 35 degrees Celsius, no matter how many times you run it or how many roses you buy it. However, it would be so much more useful if it could be modified to accept *any* value, and return the Fahrenheit equivalent of that value to the calling program.
This is where arguments come in - they allow you to define placeholders, if you will, for certain variables; these variables are provided at run-time by the main program.
Let's now modify the tempConv() example to accept an argument.
#!/usr/bin/python
# set a variable - this could be obtained via input()
alpha = 40
# define a function
def tempConv(temperature):
fahrenheit = (temperature * 1.8) + 32
return fahrenheit
# call function with argument
result = tempConv(alpha)
# print
print alpha, "Celsius is", result, "Fahrenheit"
And now, when the tempConv() function is called with an argument, the argument is assigned to the placeholder variable "temperature" within the function, and then acted upon by the code within the function definition.
It's also possible to pass more than one argument to a function - as the following example demonstrates.
>>> def addIt(item1, item2, item3):
... result = item1 + item2 + item3
... return result
...
>>> addIt("hello", "-", "john")
'hello-john'
>>>
Note that there is no requirement to explicitly specify the type of argument(s) being passed to a function - since Python is a dynamically-typed language, it can automatically identify the variable type and act on it appropriately.
Next: Enter The Funky Chameleon >>
More Python Articles
More By Vikram Vaswani, (c) Melonfire