Python 4: Functions

Learning Goals:

By the end of this lesson you should be able to:

1.     Create and use your own functions.

2.     Send data (parameters) to functions.

3.     Explain what happens when a function calls itself

Functions:

Functions allows the programmer to create useful blocks of code that can be called from any point in the program.   There are many advantages to using functions:

·        Compact code- Rather than writing the same code over and over again you can put it in a function and call it.

·        Reusability – If you have a function in one program you can copy and paste it into other programs.

·        Testing- Large programs are hard to get right.  It is much easier to debug a program that is written as a series of functions that can be individually tested.

Examples:

 #Prints an address on the screen   def printAddress():     print('Tony Demelo')     print('34 Blue Tree Drive')     print('Kirkland Lake, ON')     print('P2N 1F8')       printAddress() #Return the max of two numbers   def max(a,b):     if(a=b):         return(a)     return(sum(a,b-1)+b)       print(sum(2,6))

Programs

Save each program in you unit 1 folder as a text document called A4Px where x is the program number.  Then copy and paste it into the python interpreter.   Use the # symbol in include your name and the program code at the top of your script.

Ex:  #Tony Demello A4P1

Program 1 – Count ‘em Up

Write a function called ‘countEmUp’ that takes two integers n1 and n2 as parameters and prints all of the integers from n1 to n2.

Bonus: Set up the function so that it returns a string representation of the sequence.

Test your function like this:  countEmUp (2,10)

Program 2- Min of 3

Write a function called ‘min3’ that accepts 3 integers and returns the smallest value.

Test your function like this: print(‘The smallest number is’, min3(5,15,2))

Program 3- Factorial

The factorial of an integer, n, is the product of all of the integers between 1 and n.

The factorial of 5=5 x 4 x 3 x 2 x 1

Write a function called ‘fact’ that takes and integer, n, and uses a loop to calculate the factorial of n.

Test your program like this print( fact(5))

Program 4- Factorial Recursive Style

Write a function called ‘factR’ that takes an integer n, and calculates the factorial of n recursively.

Test your program like this print( factR(5))

Show Mr.Kurz all 4 programs when you are finished.

Next up: Learning to program the GPIO