Difference between revisions of "Subroutines - Python"
(Created page with "=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 exam...") |
(No difference)
|
Revision as of 11:40, 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")
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)