kidsprogramming

 

Functions_Python

Page history last edited by Mike Leishman 1 yr ago

Functions

 

Functions in Python can work in two ways.

 

The first is such that the body appears like a small program in its own right in the same way that a procedure would be used in another language such as Pascal.

 

The second is when the function works in the same manner as the inbuilt functions. So for example, I could define a function named Add1 so I could use it in a statement where a variable was assigned the value returned from the function. eg newnumber = add1(oldnumber)

 

Function arguments are passed by value (the original values are not changed by what happens in the function). Python dos not support passing values "by refererence" which enables new values for parameter variables to be returned if required. Global variables maybe modified from within a function.

 

Functions as Procedures

 

A function can be used in Python as a procedure where nothing is returned. An example would be a function that prints a table or calculated values. It is typical of the use of a procedure where parameter values are passed in but not out of the procedure.

 

Functions as Functions

 

This function returns the area of a circle. It is typical of the use of a function that represents a value and where the function can programaticaly be treated much like a variable.

 

#Calculate area of a circle  written in Python

 

print 'Area of Circle calculator' #program heading

 

#define the function

def Area_Circle(r):

    a = 3.14 * r * r;

    return a

 

#main program

radius = int(raw_input('Enter the radius of the circle -> '))

area = Area_Circle(radius)

print 'The area of a circle with radius %d is %5.2f' % (radius, area) 

 

 

Exercises

  1. Two functions are created that accepts two values as parameters. The functions will determine which is the bigger and which is the smaller value. The program then calls these functions and displays the larger value followed by the smaller value. Test your program with both numbers and strings.
  2. Write a function that will accept the date in dd/mm/yyyy format and return it as a string in three different fields of dd Month and yyyy. ie 12/03/2001 would return 12  March 2001.
  3. Extend exercise 2 to return the date entered in the form Day-DD Month and yyyy ( ie 12/03/2001) and to return the string Sunday 12 March 2001. 

 

Comments (0)

You don't have permission to comment on this page.