Time for some more serious stuff: functions.
- Download http://www.cs.bath.ac.uk/~mdv/courses/CM10192/firstprogram.py
- Have a look at the code. You should find 4 functions and one function
call. Try to read to code.
- Run the code a few times. What happens if you enter positive
numbers, negative numbers, characters, nothing?
- So what are all the functions doing?
- You were given a program without errors. This is perfect opportunity to
see what happens if you make deliberate mistakes in the program.
This will help you in the future when you make similar mistakes by accident.
What does this tell you about the language?
- remove spaces
- remove :
- change names of parameters
- Now it is time to write some functions yourself.
- Write a function that generates the third power a given number.
- Write a function that takes three numbers as parameters and prints
the smallest, biggest and average
- Write multiplication of two numbers
using only addition (e.g. 3 x 3 = 3 + 3 + 3)
- Write functions add_one and minus_one that adds to or subtract
one of its parameter
- Implement a function (possibly with the assistance of other functions)
that adds two numbers without the use of the + (except in add_one)
- The script you have just finished (or the original) can also be used
as a module. This allows other scripts to use the functions defined in
- This can be done with the import statement. Try this in your environment.
- To call the functions you will need to use "modulename.functionname" instead of functionname
- Try some function calls that way.
Marina De Vos