Difference between revisions of "Subroutines - Python"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Declaring a subroutine)
(Calling a subroutine)
Line 14: Line 14:
  
 
=Calling a subroutine=
 
=Calling a subroutine=
With your subroutine declared you can then call it anywhere within your program, this call must also provide the parameters required for the routine (ie inside the brackets () ). For example using the chorus subroutine above:
+
With your subroutine declared you can then call it anywhere within your program, this call must also provide the parameters required for the routine ie inside the brackets () . For example using the chorus subroutine above:
  
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>

Revision as of 12:43, 21 June 2018

What is a subroutine & Why do we have them

A subroutine is essentially defining a name for a block of code. This code can then be used elsewhere just by calling it. For example, if you think of one of your favourite songs it is likely to have several verses and a repeating chorus. A subroutine could be used to define what the chorus is, so we could now replace the lines of the actual chorus with just chorus.

Declaring a subroutine

Python uses the def command to declare a function, you must supply the name of the routine and any parameters accepted by the routine ie the brackets () . So for example:

def chorus():
     print("chorus line 1")
     print("chorus line 2")
     print("chorus line 3")
     print("chorus line 4")

Calling a subroutine

With your subroutine declared you can then call it anywhere within your program, this call must also provide the parameters required for the routine ie inside the brackets () . For example using the chorus subroutine above:

print(verse 1 line 1)
print(verse 1 line 2)
print(verse 1 line 3)
print(verse 1 line 4)
chorus()
print(verse 2 line 1)
print(verse 2 line 2)
print(verse 2 line 3)
print(verse 2 line 4)