Wednesday 23 July 2014

Subroutines: Procedures and Functions


It is possible to write a whole program as one big block but where possible we want to 
break it down into subroutines. There are several advantages to this: 

- The program becomes easier to read. 
- The program becomes easier to test. If you have tested a subroutine you don’t have to 
worry about it when you subsequently use it. 

- Subroutines can often be reused meaning code does not need to be rewritten. 
We will start off with a function that prints out This is my subroutine 3 times. Notice 
how the subroutines come before the main program. 

#Subroutine that prints out sentence 3 times 

def myFirstSubroutine(): 
 for i in range(1,3): 
 print('This is a subroutine') 
#Main Program 
print('Start of main program') 
myFirstSubroutine() 
print('End of program') 

This would output: 
Start of main program 
This is a subroutine 
This is a subroutine 
This is a subroutine 
End of program 


We can use parameters to make subroutines even more useful. The parameters in the 
subroutine below are text and times. 

#Subroutine that prints out sentence 3 times 
def myFirstSubroutine(text, times): 
 for i in range(0,times): 
 print(text) 

#Main Program 
print('Start of main program') 

myFirstSubroutine('Sample text',5) 
print('End of program') 

No comments:

Post a Comment

Wildern Pupils if you log onto your school email account you can leave a comment via that ID.