- Functions are useful for carrying out actions that you will want to use multiple times.
- Arguments allow us to pass different values to a function - the function's actions are carried out on those values.
- Functions compute values and give them back to us via a return statement.
def myAdd(x, y):
# add 2 values and return the sum
result = myAdd(1, 3) # run myAdd with x set to 1, y set to 3
# store the value returned by myAdd in the result variable
print result # what will be printed?
# run myAdd with x set to "foo", y set to "bar"
# store the returned value in the result variable
result = myAdd("foo", "bar")
print result # what happens? what is printed?
# run myAdd with x set to 3, y set to "abc"
# store return value in result
result = myAdd(3, "abc")
print result # what happens?
Exercise: Write a function square() that takes a value and returns the square of that value. For example:
>>> answer = square(4)
>>> print answer
>>> result = square("hello")
>>> print result
Exercise: Write a Python program which contains two functions, main() and maximumValue().
- maximumValue(x, y, z) -- returns the largest of the 3 inputs, without using any math module functions.
- main() -- prompts the user for 3 integers, and
then calls maximumValue() to determine which is largest. Then prompts
the user for 3 strings and prints the largest.