Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact

Well House Consultants
You are on the site of Well House Consultants who provide Open Source Training Courses and business hotel accommodation. You are welcome to browse and use our resources subject to our copyright statement and to add in links from your pages to ours.
Other subject areas - resources
Java Resources
Well House Manor Resources
Perl Resources
Python Resources
PHP Resources
Object Orientation and General topics
MySQL Resources
Linux / LAMP / Tomcat Resources
Well House Consultants Resources
Extras Resources
C and C++ Resources
Ruby Resources
Tcl/Tk Resources
Web and Intranet Resources
Python module Y105
Functions, Modules and Packages
Exercises, examples and other material relating to training module Y105. This topic is presented on public courses Learning to program in Python, Python Programming

In Python, blocks of code can be named. Such named blocks of code can be run from elsewhere in your program, and are known as functions. A module is a text file that contains a number of functions and other items, and a package is a group of related modules.

Related technical and longer articles
Python Calling functions and methods. Using objects and modules.

Articles and tips on this subjectupdated
4441Reading command line parameters in Python
The sys module in Python gives you access to operating system parameters such as the command line interface, via an ordered collection (I think a list, may be a tuple) called argv. Although many / most users these days don't use the command line directly, it's often used internally between programs in ...
4410A good example of recursion - a real use in Python
Recursion is where a named block of code calls itself. The "classic" demonstration is the code to generate a factorial number:   def factorial(n):     if n ...
4407Python - even named code blocks are objects
In Python, "everything is as object" and objects / variables share the same data storage area and naming convention if they're "classic" variables containing data values used in your program, or if they're names pieces of code (functions or methods). That sharing gives a great power in facilities to ...
4361Multiple yields and no loops in a Python generator?
Python generator functions return their results in parts and don't have a return statement but rather a yield statement whenever a results is ready to be returned - typically, the production of a list that's returned all at once is replaced by the production (in a loop) of a series of values, each of ...
4212Python functions - an introduction to how they work
When I'm writing code, I'll sometimes come to a complicated algorithm and wonder just to to tackle it. I know my inputs and outputs well, but how I calculate it requires considerable thought. Take, for example, a postal delivery service in a traditional English street where the practical thing is to ...
4161Python varables - checking existance, and call by name or by value?
A couple of good questions from a recent delegate... Q. How do I check for the existance of a variable in Python? A. Reference it and see if an exception is thrown. Here's an example in which I create a variable only if my program is run with command line parameters:   import sys   if ...
4029Exception, Lambda, Generator, Slice, Dict - examples in one Python program
A new example from last week's Python course, showing exception, lambda, generator and list slices in a practical programming example. The task we took was to go through a file of railway stations and ticket sales figures, and report on the most and least used 20 in the UK. The programs's [here]. a) ...
3945vargs in Python - how to call a method with unknown number of parameters
In C, a few functions such as printf can take a variable number of arguments, and it's possible (but not common) for you to write functions like that too. In Python, though, it's much more common. In declaring a function, you can specify:   a) Mandatory parameters, just with a name   b) ...
3931Optional positional and named parameters in Python
Functions are commonly called with a set number of positional parameters. However, you have more flexibility in Python. If you define your function with a parameter starting with a "*", then all remaining parameters after anything to its left are stored in that parameter as a tuple. And if you conclude ...
3885Default local - a good choice by the author of Python
Although it would be convenient at times to be able to refer to any variable anywhere in your program, this is not how most languages work by default. And they're designed that way! That's to avoid confusion as a program grows, when there's a strong possibility of several programmers on the same ...
3852Static variables in Python?
Each time you call a function, you start off with a fresh set of variables. That's usually exactly what you want, as you don't usually want one calculation to be influenced by the debris of the previous similar calculation. In Python, you can define a variable as an attribute of the method (using methodname-dot ...
3766Python timing - when to use a list, and when to use a generator
If you're going to cook dinner for the family, it's much more efficient to cook everyone's meal together. If you're a family of four, you won't want to cook four separate pans of carrots, but rather you'll want to cook them all together. But now imagine you're holding a carrot street party, and providing ...
3695Functions are first class variables in Lua and Python
I've been training in Lua and Python this week - and the two languages are very diferent, but in many ways they're also much the same. Both languages are slim (ie not bloated with facilities). For example neither supports the ++ operator which those of us who do a lot of coding in Perl, PHP, C and C++ ...
3662Finding all the unique lines in a file, using Python or Perl
A question - how do I process all the unique lines from a file in Python? Asked by a delegate today, solved neatly and easily using a generator which means that there's no need to store all the data - unique values can be passed back and processed onwards as they're found. This is fantastic news if ...
3474Python Packages - groupings of modules. An introduction
As your Python code grows in volume, you'll want to arrange it into subdirectories, with a mirroring mechanism within the language to let you have the extra heirarcy as you load the code from the subdirectory. And you're looking at python packages. They work as follows: a) You put the modules that ...
3472Static variables in functions - and better ways using objects
Usually, I don't want leftovers from a previous call to a function to hang around when I call the same function again later in my program. After all, the cosine of 45 degrees is not dependent on what the previous cosine request I made was! However, there are some occasions where I may want to have ...
3464Passing optional and named parameters to python methods
When you call a named block of code (a method or function), you'll wish to pass in originating values that are changed from one call / use to the next - these are commonly known as the parameters. If I'm calling a function to calculate the area of a rectangle, for example, I would pass in the width ...
3459Catching the fishes first?
If you make a fish pie for your friends, you'll catch all the fish you need before you start the preparation and cooking work, and you'll do the cooking all at once. If you run a fish pie factory, you'll have a steady flow of fish arriving while your production line is running. Receiving ...
3280Passing parameters to Python functions - the options you have
Parameters to Python functions / methods are (by default) position dependent. If you def a function with 2 parameters, and call it with two, the first incoming address is taken as being the incoming address saved accessed through the first variable, and the second incoming address is taken as being ...
3159Returning multiple values from a function call in various languages - a comparison
I've always thought it a bit odd that you call a function with any number of parameters, and yet it returns a single value; in Java, C or C++ you declare a return type (void if there is not to be anything returned) and you are then constrained by that specification. There are, of course, other ways ...
2998Using an exception to initialise a static variable in a Python function / method
Exceptions are sometimes "sold" as a way of trapping errors - but they're more than that - they're an excellent way of trapping conditions where there isn't a valid result. "How many people live in this house" you may ask of a function / method call, and the answer may come back as "2" or "5" ... or ...
2994Python - some common questions answered in code examples
Some tips and new examples from last week ... Python in Plymouth! • How do I put comments in a Python regular expression to make it more readable: [source] • How do I use a python dictionary as a table of counters - in our example, counting the number of people in our team who have each of ...
2929Passing a variable number of parameters in to a function / method
How many columns are there in each row in a table? It will vary, depending on the table! If I want to write a "row" function in PHP, passing in as parameters each of my columns, I don't know the parameter count. But I can find out using the fun_num_args function, and I can then get each of them using ...
2878Program for reliability and efficiency - do not duplicate, but rather share and re-use
When you're writing a new piece of code - especially if you're also quite new to programming - you'll be concentrating so much on getting it to work that you may not be giving too much thought to making it easy look after your code later on (maintainance), nor to sharing a piece of code between programs. ...
912Recursion in Python
I'm not a great advocate of recursion - pieces of code that call themselves; most of the examples that I see in books are "training examples" that are over complex and achieve results that could much more easily be achieved by alternative means. I'm not telling you NEVER to use recursion - sometimes ...
2766Optional and named parameters to Python functions/methods
Do you want to call a function with a differing number of arguments - sometimes simply looking for a function to run with all defaults, and at other times passing in some specific values / variables? Do you have so many different possible parameters that you would like to be able to "I want to give ...
959It's the 1st, not the 1nd 1rd or 1th.
Here's a function in Python that takes the day number in the month (in the range 1 to 31 ...) and returns "st","nd","rd" or "th" as appropriate def somehow(val):   "Somehow, your time will come"   ding = (["st","nd","rd"]+["th"]*7)[(val-1) % 10]   if val/10 == 1: ding = ...
2718Python - access to variables in the outer scope
In Python, variables are local to the block in which they're used unless declares in some other way. And that's good news, because the last thing you want in a substantial script is for data to "leak" between functions as can happen in default-accepting Perl or Lua. But there is an exception ... if ...
2520Global and Enable - two misused words!
The word global is used in declaring variables in some languages such as Tcl and Python to indicate that the variable being referred to is shared with the variable of the same name at the top scope. To use the word global, which implies that the declaration makes the variable visible everywhere, is misleading The ...
2506Good example of recursion in Python - analyse an RSS feed
I'm not keen on recursive code - code that calls itself. Very often, such code is elegant in a way, yet so 'clever' that it is hard to follow. There are, however, exceptions where I say "THAT is a good use of recursion". Once such is in the handling / parsing of RSS (Really Simple Syndication) feeds. I ...
2481Sample code with errors in it on our web site
Feedback is lifeblood ... ignore it at your peril, and remember that for each person who lets you know you have a problem, a further ten will have noticed and not said anything. From my mailbox: > Your webpage > > http://www.wellho.net/resources/ex.php4?item=y105/locvar.py > > contains the following ...
2440Optional parameters to Python functions
Python functions (and methods) can be called with any number (0 or more) parameters, but the calling sequence must match the 'template' or 'function prototype' given when defining the function. Let's define a function: def fred(a,b,c=3,d=4,e=5,f=6):     print a,b,c,d,e,f That ...
2439Multiple returns from a function in Python
Convention states that you can call a function with many parameters, but you return just one. There's some truth in that statement, but of course you can often return a collection - an array, list, hash, dictionary or other composite object. Here's a Python example ... 3 parameters in and 2 return ...
2011Conversion of OSI grid references to Eastings and Northings
In both Ireland and the UK, the Ordnance survey divides down the country into a series of lettered 100km x 100km squares, represented by 1 letter (Ireland) or 2 (UK mainland), and then measures / reports and Easting / Northing within that square. Example: ST645332 (UK, box ST, 64.5 km east, 33.2 km ...
949Sludge off the mountain, and Python and PHP
Is Python 2.3 compatible with version 2.2? How about PHP 5.1 with PHP 4.4? In an ideal world, the answer to every such compatibility question would be "yes, it is" but it's not always quite that simple. Python's upwards compatibility is excellent - as a language, it was designed for the purpose for ...
913Python - A list of methods
In Python everything - even named blocks of code - are objects. Which means that you can have a list or a dictionary of functions, and you can pass named blocks of code in and out of other functions and methods games = [] colls = [350, 120.5, 1, 400, 289, 400] c2 = [4,3,4,5,4,7] games.append(lambda ...
1879Dynamic code - Python
When I learned to program, named blocks of code (subroutines and functions) were built into each program and weren't things you could change at run time. But these days, in some languages like Python it's very different and you can write code that includes dynamic functions and methods - after all, ...
1871Optional and named parameters in Python
When you're calling a named block of code (either a function or a method in Python terms), you'll pass in a number of parameters. Some of those will be mandatory - needed every time. Some will be optional, but frequently used, and others will be wanted on very rare occasions indeed and selected from ...
1870What to do with a huge crop of apples
Last year, you had a good crop of apples on your tree .... what did you do with them? Make apple pies for all the neighbours! How? • You collect all the apples and bring them into the kitchen. • You prepare the apples ready for the pies. • You make the pastry and apple pies. • You ...
1869Anonymous functions (lambdas) and map in Python
Why do you name variables? So that you can use them again later. But if you don't want to use them more than once, why bother with a name at all? Most programming languages create temporary or anonymous variables within a single line, and if you've programmed almost anything, you'll have used them without ...
1790Sharing variables with functions, but keeping them local too - Python
""" One of the big issues with any programming language is how in shares (scopes) variables between blocks of code. On one hand there's a desire to have variables easily accessible without a lot of passing around. On the other hand there's the need to keep information in vary different parts of you code ...
1784Global - Tcl, PHP, Python
PHP, Python, Tcl and a number of other languages have a global keyword. And it's a misnomer in most (if not all) cases. To the un-initiated, "Global" means "worldwide" or "shared all around". So you would think that if you declare something as global, you're going to be sharing it with the same thing ...
418Difference between import and from in Python
Python's "import" loads a Python module into its own namespace, so that you have to add the module name followed by a dot in front of references to any names from the imported module that you refer to: import feathers duster = feathers.ostrich("South Africa") "from" loads a Python module into the current ...
105Distance Learning
From time to time, I'm asked about providing "distance learning" for Perl, PHP, Ruby, Python ... and it's an excellent question. It's something we're considered, reviewed, and no doubt will review again in the future ... but here's my views and our decision on the subject at present: We don't offer ...
96Variable Scope
One of the vital topics on all our programming courses is that of variable scope. Variable Scope may be defined as the area of a program in which a variable is visible, and how long that variable is accessible for. Why do I describe variable scope as a vital subject when you can write simple programs ...
1464Python Script - easy examples of lots of basics
Here's a Python script which is pretty imperfect, but shows a whole lot of the basic facilities of the language in use - a sort of "you can do it this way" crib sheet for newcomers. Written during last week's course, with delegates making suggestions as I went along - so if you think the code looks ...
1202Returning multiple values from a function (Perl, PHP, Python)
Function in PHP and Python and subs in Perl can only return one "thing" - one item, one object. But all three languages allow that returned item to be a collection - in other words, a composite. And all three languages provide a very easy way of breaking the returned structure down into a series of individual ...
1163A better alternative to cutting and pasting code
If you're new to coding, you'll be so concerned to be writing code that works that you may not take a look at coding technique. Your nose will be so close to the grindstone as you work that you won't take the time to look and ask "Do I need to keep grinding anyway?" If you find yourself writing a piece ...
1134Function / method parameters with * and ** in Python
In Python, you can define a function with optional parameters; if you specify a single * in front of a parameter, then that will be a tuple of all remaining unnamed values. And if you specify two *s in front of a parameter, that will be a dictionary of all remaining named parameters. Let's see an ...
900Python - function v method
What's the difference between a function and a method? A function is a named piece of code that performs an operation, and a method is a function with an extra parameter which is the object that it's to run on. Example: class hotel:  def __init__(self,name,nightly):   self.name = ...
821Dynamic functions and names - Python
In Python, everything is held as an object in a variable - and I do mean everything, even named pieces of code. So that means that you can do some amazing things (or things that would be amazing in other languages) such as set up a named piece of code to perform action "x", the replace it dynamically ...
775Do not duplicate your code
If you've writing or maintaining a program and you find yourself cutting and pasting a chunk of code, STOP and think again. By duplicating a block of code, you're duplicating your maintainance task from that point onwards - any fixes applied to the original much be applied to the copy too. And that's ...
749Cottage industry or production line data handling methods
If you're running a cottage industry, for efficiency's sake you'll run the first process on each of your raw components first, and store the partially-completed elements in a basket as they're processed. When you've completed that first process, you'll then apply the second process to each element ...
668Python - block insets help with documentation
For many programmers, documenting their code is a chore, yet every piece of code that's going to be (re)used needs both instructions for the user, and adequate explanation of techniques for the code maintainer. The need for BOTH of these forms of support documentation is often overlooked by the newcomer, ...
745Python modules. The distribution, The Cheese Shop and the Vaults of Parnassus.
What if Python doesn't include a class / method that you would like, but you've got that feeling that "surely someone's done this before"? 1. They probably have 2. They've probably made it an available 'Open Source' 3. It's just a question of you knowing where to look! Where to look ... a) The built ...
Examples from our training material
acsh2   Dynamic function definition
apers   static variables in Python?
avg.py   Demonstration of variable scope in Python
better   An extra x - range v xrange and readlines v xreadlines
cardy   Main program - methods and attributes from a module
colin.py   A tiny module
dbc   Functions are objects
dfg   Using a generator to process a big file
dream   Good structure of named blocks of code
drought.py   Assorted function call examples
electric.py   a generator function - carries on where it left off at previous call
extrastep.py   importing a name from a module into the current namespace
f1   more options with modules and functions
fat.py   A second program that uses shared functions in mod2.py
ffx   Dynamic function definition
firstclass   List of fucntions and callback demo
flook.py   Program to use a module and the attributes of its functions
fm   use of functions from a module
fun.py   definition and use of a function
gen   A generator - two code branches both live
gen2   Using a generator function to provide an iteration
gen_control   No using a generator - each runs to completion
genex   Generator v regular function
gentwo   generator - multiple yields and no loop!
geom.py   Full module, documentation, test harness, static variables
gubbins.py   A bunch of functions in a module
jen.iter   Generator with multiple yields
jenny   Generator v list comparison
local.py   File of functions to be loaded by other examples
locvar.py   Local and global variables
m1   map to transform and filter to select from a list
mapfunc.py   Use of the map function to transform a list
mod2.py   A module with doc strings and attributes defined
mod_demo.py   Program that uses the module in local.py
mutton   Anonymous varaibles and subs and lambdas
myne.py   Module with documentation string and test harness
mystuff.py   functions, statics, test code, doc strings ...
noa   Mandatory, optional, ordered and named parameters
params.py   Optional parameters, and variable number of parameters
passenger   Calling program - sample answer with separate module for functions
pf   Defining and calling a function - postal delivery order
pgob   Using objects to pass in (and out) of generators
places.xyz   Sample data for jenny demo
poc.py   Scope of variables - some samples
qv2   Example that uses mystuff.py
qv3   alternative example using mystuff.py
recur.py   Recursion - when a function calls itself
repeater   retaining a variable from one call to the next
sheep.py   A Lambda function - one line function definition
silksheets.py   Functions that we'll share between applications
slumbermore   Good structure of named blocks of code
snoresleep   A further Good structure of named blocks of code
ststar   * and ** in function calls
ststst   function calling - options demonstrated
sweetdream   Another example of a module reuse
sysdemo.py   use of a standard module (sys)
tax.py   functions to work out tax and net from gross
taxcalcs.py   Collecting function parameters
taxi   Exercise answer - net and tax from gross amount
vargs   vargs in Python
yf   Using a generator
yum   Brining in elements from a namespace
Studious group during a practical
Background information
Some modules are available for download as a sample of our material or under an Open Training Notes License for free download from http://www.training-notes.co.uk.
Topics covered in this module
Why use functions.
A first function.
A first module.
More flexibility in calling functions.
Doc strings and function attributes.
Defining your own attributes.
Variable scope.
Advanced function capabilities and recent additions.
Lambda example.
Generator Example.
Built-in modules.
Complete learning
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule page.

Well House Consultants specialise in training courses in Python, Perl, PHP, and MySQL. We run Private Courses throughout the UK (and beyond for longer courses), and Public Courses at our training centre in Melksham, Wiltshire, England. It's surprisingly cost effective to come on our public courses - even if you live in a different country or continent to us.

We have a technical library of over 700 books on the subjects on which we teach. These books are available for reference at our training centre. Also available is the Opentalk Forum for discussion of technical questions.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2015: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/resources/Y105.html • PAGE BUILT: Thu Sep 18 11:03:17 2014 • BUILD SYSTEM: WomanWithCat