Chapters 4(2)
Chapters 4(2)
Now we turn to creating our own functions. As an example, let’s write a function to
calculate the area of a circle. Recall that a circle’s area is pi times its radius squared.
Here is a Python function that does this calculation:
import math
def area (radius): # function header (def followed by a space, and then the name of the function)
""" Returns the area of a circle After the function name comes the function parameter list.
with the given radius. This is a list of variable names that label the input to the
function. In our example we have a single input (radius).
For example: Finally a function header ends with a colon (:).
>>> area(5.5)
95.033177771091246
""" #function body. The code in this block is allowed to use the variables from the
return math.pi * radius ** 2 function header.
#Finally, the function returns a value using the return keyword. When a return statement is executed, Python jumps out of the
function and back to the point in the program where it was called.
Save this function inside a Python file (area.py would be a good name); then load it
into the IDLE editor and run it by pressing F5. If everything is typed correctly, a
prompt should appear and nothing else; a function is not executed until you call it.
Python Programming
Functions
Defining Functions
To call it, just type the name of the function, with the radius in brackets:
>>> area(1)
3.1415926535897931
>>> area(5.5)
95.033177771091246
157.07963267948966
Notice:
• The area function can be called just like any other function, the difference being that you have written the function
and so you have control over what it does and how it works.
• As with variable names, a function name must be one or more characters long and consist of letters, numbers, or the
underscore (_) character. The first character of the name cannot be a number.
Python Programming
Functions
Defining Functions
# hello.py
def say_hello_to(name):
""" Prints a hello message.
"""
cap_name = name.capitalize()
print('Hello ' + cap_name + ', how are you?')
Python Programming
Functions
Variable Scope
The scope of a variable is where in a program it is accessible, or visible.
import math
def dist(x, y, a, b):
s = (x - a) ** 2 + (y - b) ** 2
return math.sqrt(s)
def rect_area(x, y, a, b):
width = abs(x - a)
height = abs(y - b)
return width * height
Any variable assigned for the first time within a function is called a local variable.
The function dist has one local variable, s, while rect_area has two local variables, width and height.
The parameters of a function are also considered local. Thus dist has a total of five local variables—
x, y, a, b, and s; rect_area has a total of six.
Notice that variables x, y, a, and b appear in both functions, but they generally label different values.
Importantly, local variables are usable only within the function they are local to. No code outside of the
function can access its local variables. When a function ends, its local variables are automatically deleted.
Python Programming
Functions
Global variables
Variables declared outside of any function are called global variables, and they are readable
anywhere by any function or code within the program.
# global_error.py
name = 'Jack'
def say_hello():
print('Hello ' + name + '!')
def change_name(new_name):
name = new_name
The variable name is a global variable because it is not declared inside any function.
The say_hello() function reads the value of name and prints it to the screen as you would expect:
>>> say_hello()
Hello Jack!
However, things don’t work as expected when you call change_name:
>>> change_name('Piper')
>>> say_hello()
Hello Jack!
Nothing changed—name still labels the value 'Jack'. The problem is that Python treated name inside
the change_name function as being a local variable, and so ignored the global name variable.
Python Programming
Functions
Global variables
To access the global variable, you must use the global statement:
# global_correct.py
name = 'Jack'
def say_hello():
print('Hello ' + name + '!')
def change_name(new_name):
global name
name = new_name
This makes all the difference. Both functions now work as expected:
>>> say_hello()
Hello Jack!
>>> change_name('Piper')
>>> say_hello()
Hello Piper!
Python Programming
Functions
Using a main Function
It is usually a good idea to use at least one function in any Python program you write: main()
A main() function is, by convention, assumed to be the starting point of your program.
# password2.py
def main():
pwd = input('What is the password? ')
if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')
Notice that all the code is indented underneath the main function header.
When you run password2.py in IDLE, nothing happens—only the prompt appears. You must
type main() to execute the code within in it.
The advantage of using a main function is that it is now easier to rerun programs and pass in input
values.
Python Programming
Functions
Using a main Function
# password3.py
def password(pwd):
if pwd == 'apple':
print('Logging on ...')
else:
print('Incorrect password.')
print('All done!')
>>> password('apple')
Logging on ...
All done!
Python Programming
Functions
Function Parameters
Parameters pass data into a function, and Python has several kinds of parameters.
# greetings.py
def greet(name, greeting = 'Hello'):
print(greeting, name + '!')
>>> greet('Bob')
Hello Bob!
>>> greet('Bob', 'Good morning')
Good morning Bob!
An important detail about default parameters is that they are evaluated only once, the first time they are
called. In complicated programs, this can sometimes be the source of subtle bugs, so it is useful to keep
this fact in mind.
Python Programming
Functions
Keyword parameters
Keyword parameters have two big benefits.
• First, they make the parameter values clear, and thus help to make your programs easier
to read.
• Second, the order in which you call keyword parameters does not matter.
# shopping.py
def shop(where = 'store', what = 'pasta', howmuch = '10 pounds'):
print('I want you to go to the', where)
print('and buy', howmuch, 'of', what + '.')
>>> shop()
I want you to go to the store
and buy 10 pounds of pasta.
>>> shop(what = 'towels')
I want you to go to the store
and buy 10 pounds of towels.
>>> shop(howmuch = 'a ton', what = 'towels')
I want you to go to the store
and buy a ton of towels.
>>> shop(howmuch = 'a ton', what = 'towels', where = 'bakery')
I want you to go to the bakery
and buy a ton of towels.
Python Programming
Functions
To create a Python module
A module is collection of related functions and variables.
# shapes.py
>>> rectangle(4,4)
CHAR = '*'
"""A collection of functions ****
for printing basic shapes. ****
"" ****
def rectangle(height, width): ****
""" Prints a rectangle. """ >>> square(2)
for row in range(height): **
for col in range(width):
**
print(CHAR, end = '')
print() >>> triangle(4)
*
def square(side): **
""" Prints a square. """ ***
rectangle(side, side) ****
def triangle(height):
""" Prints a right triangle. """
for row in range(height):
for col in range(1, row + 2):
print(CHAR, end = '') A module is a toolbox of helpful functions that you can use when
print() writing other programs. Thus a module usually does not have
a main() function.
Python Programming
Functions
To create a Python module
The names within a module are visible outside the module only when you use
an import statement. To use a module, you simply import it. For example:
>>> import shapes
>>> dir(shapes)
['CHAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'rectangle', 'square', 'triangle']
>>> print(shapes.__doc__)
A collection of functions
for printing basic shapes.
>>> shapes.CHAR
'*'
>>> print(shapes.rectangle.__doc__)
Prints a rectangle.