Difference between revisions of "Subroutines - Python"
(→Calling a subroutine) |
|||
Line 11: | Line 11: | ||
print("chorus line 3") | print("chorus line 3") | ||
print("chorus line 4") | print("chorus line 4") | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | you can use parameters, for example: | ||
+ | |||
+ | <syntaxhighlight lang=python> | ||
+ | def answer(person): | ||
+ | if person="Wayne": | ||
+ | print("yes") | ||
+ | else: | ||
+ | print("no") | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Line 26: | Line 36: | ||
print(verse 2 line 3) | print(verse 2 line 3) | ||
print(verse 2 line 4) | print(verse 2 line 4) | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | alternatively if you are using parameters: | ||
+ | |||
+ | <syntaxhighlight lang=python> | ||
+ | name = input("please enter your name") | ||
+ | print("do I like you???" | ||
+ | answer(name) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | =Procedure vs Function= | ||
+ | There are 2 types of subroutine. A procedure is essentially what we have looked at above, you can pass parameters into a procedure and a procedure is a name for a block of code. A function however allows all of this but can also return a value. |
Revision as of 11:53, 21 June 2018
Contents
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")
you can use parameters, for example:
def answer(person):
if person="Wayne":
print("yes")
else:
print("no")
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)
alternatively if you are using parameters:
name = input("please enter your name")
print("do I like you???"
answer(name)
Procedure vs Function
There are 2 types of subroutine. A procedure is essentially what we have looked at above, you can pass parameters into a procedure and a procedure is a name for a block of code. A function however allows all of this but can also return a value.