Skip to content


Subversion checkout URL

You can clone with
Download ZIP
100644 265 lines (253 sloc) 16.649 kB
83567d0 @stoive directory restructure
1 <document>
2 <lesson number="5" title="Functions" author="Steven Thurlow" style="../../stylesheet.css">
3 <content>
4 <section title="Introduction">
5 <p>Last lesson I said that we would delve into purposefull programming. That involves user input, and user input requires a thing called functions.</p>
6 <p>What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.</p>
7 </section>
8 <section title="Using a function">
9 <p>Python has lots of pre-made functions, that you can use right now, simply by 'calling' them. 'Calling' a function involves you giving a function input, and it will return a value (like a variable would) as output. Don't understand? Here is the general form that calling a function takes:</p>
10 <code title="How to call a function">
11 <l>function_name(parameters)</l>
12 </code>
13 <p>See? Easy.</p>
14 <unorderedList>
15 <entry>Function_name identifies which function it is you want to use (You'd figure...). For example, the function raw_input, which will be the first function that we will use.</entry>
16 <entry>Parameters are the values you pass to the function to tell it what is should do, and how to do it.. for example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70 x 5.</entry>
17 </unorderedList>
18 </section>
19 <section title="Parameters and Returned Values - Communicating with Functions">
20 <p>Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what is does?</p>
21 <p>Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Variables do the exact same thing - the computer doesn't see the variable name, it sees the value that the variable holds. Lets call this program that multiplied any number by five, multiply(). You put the number you want multiplied in the brackets. So if you typed this:</p>
22 <code title="Using a function">
23 <l>a = multiply(70)</l>
24 </code>
25 <p>The computer would actually see this:</p>
26 <code title="What the computer sees">
27 <l>a = 350</l>
28 </code>
29 <p>note: don't bother typing in this code - multiply() isn't a real function, unless you create it.</p>
30 <p>The function ran itself, then returned a number to the main program, based on what parameters it was given.</p>
31 <p>Now let's try this with a real function, and see what it does. The function is called raw_input, and asks the user to type in something. It then turns it into a string of text. Try the code below:</p>
32 <code title="Using raw_input">
33 <l># this line makes 'a' equal to whatever you type in</l>
34 <l>a = raw_input("Type in something, and it will be repeated on screen:")</l>
35 <l># this line prints what 'a' is now worth</l>
36 <l>print a</l>
37 <code>
38 <p>Say in the above program, you typed in 'hello' when it asked you to type something in. To the computer, this program would look like this:</p>
39 <code>
40 <l>a = "hello"</l>
41 <l>print "hello"</l>
42 <code>
43 <p>Remember, a variable is just a stored value. To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.</p>
44 </section>
45 <section title="A Calculator Program">
46 <p>Lets write another program, that will act as a calculator. This time it will do something more adventerous than what we have done before. There will be a menu, that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the raw_input function returns what you type in as a string - we want the number 1, not the letter 1 (and yes, in python, there is a difference.).</p>
47 <p>Luckily, somebody wrote the function input, which returns what you typed in, to the main program - but this time, it puts it in as a number. If you type an integer (a whole number), what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can add and subtract, etc.</p>
48 <p>Now, lets design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.</p>
49 <p>We want it to do an option in the menu if you type in that number. That involves you typing in a number (a.k.a input) and an if loop.</p>
50 <p>Lets write it out in understandable English first:</p>
51 <code title="human-language example">
53 <l>print opening message</l>
54 <l></l>
55 <l>while we let the program run, do this:</l>
56 <l> #Print what options you have</l>
57 <l> print Option 1 - add</l>
58 <l> print Option 2 - subtract</l>
59 <l> print Option 3 - multiply</l>
60 <l> print Option 4 - divide</l>
61 <l> print Option 5 - quit program</l>
62 <l> </l>
63 <l> ask for which option is is you want</l>
64 <l> if it is option 1:</l>
65 <l> ask for first number</l>
66 <l> ask for second number</l>
67 <l> add them together</l>
68 <l> print the result onscreen</l>
69 <l> if it is option 2:</l>
70 <l> ask for first number</l>
71 <l> ask for second number</l>
72 <l> subtract one from the other</l>
73 <l> print the result onscreen</l>
74 <l> if it is option 3:</l>
75 <l> ask for first number</l>
76 <l> ask for second number</l>
77 <l> multiply!</l>
78 <l> print the result onscreen</l>
79 <l> if it is option 4:</l>
80 <l> ask for first number</l>
81 <l> ask for second number</l>
82 <l> divide one by the other</l>
83 <l> print the result onscreen</l>
84 <l> if it is option 5:</l>
85 <l> tell the loop to stop looping</l>
86 <l>Print onscreen a goodbye message</l>
87 <l>END PROGRAM</l>
88 </code>
89 <p>Lets put this in something that python can understand:</p>
90 <code title="Python verion of menu">
91 <l>#calculator program</l>
92 <l></l>
93 <l>#this variable tells the loop whether it should loop or not.</l>
94 <l># 1 means loop. anything else means don't loop.</l>
95 <l></l>
96 <l>loop = 1</l>
97 <l></l>
98 <l>#this variable holds the user's choice in the menu:</l>
99 <l></l>
100 <l>choice = 0</l>
101 <l></l>
102 <l>while loop == 1:</l>
103 <l> #print what options you have</l>
104 <l> print "Welcome to"</l>
105 <l></l>
106 <l> print "your options are:"</l>
107 <l> print " "</l>
108 <l> print "1) Addition"</l>
109 <l> print "2) Subtraction"</l>
110 <l></l>
111 <l> print "3) Multiplication"</l>
112 <l></l>
113 <l> print "4) Division"</l>
114 <l> print "5) Quit"</l>
115 <l> print " "</l>
116 <l></l>
117 <l> choice = input("Choose your option: ")</l>
118 <l> if choice == 1:</l>
119 <l> add1 = input("Add this: ")</l>
120 <l> add2 = input("to this: ")</l>
121 <l> print add1, "+", add2, "=", add1 + add2</l>
122 <l> elif choice == 2:</l>
123 <l> sub2 = input("Subtract this: ")</l>
124 <l> sub1 = input("from this: ")</l>
125 <l> print sub1, "-", sub2, "=", sub1 - sub2</l>
126 <l> elif choice == 3:</l>
127 <l> mul1 = input("Multiply this: ")</l>
128 <l> mul2 = input("with this: ")</l>
129 <l> print mul1, "*", mul2, "=", mul1 * mul2</l>
130 <l> elif choice == 4:</l>
131 <l> div1 = input("Divide this: ")</l>
132 <l> div2 = input("by this: ")</l>
133 <l> print div1, "/", div2, "=", div1 / div2</l>
134 <l> elif choice == 5:</l>
135 <l> loop = 0</l>
136 <l> </l>
137 <l>print "Thankyou for using!"</l>
138 </code>
139 <p>Wow! That is an impressive program! Paste it into python IDLE, save it as '' and run it. Play around with it - try all options, entering in integers (numbers without decimal points), and numbers with stuff after the decimal point (known in programming as a floating point). Try typing in text, and see how the program chucks a minor fit, and stops running (That can be dealt with, using error handling, which we can address later.)</p>
140 </section>
141 <section title="Define Your Own Functions">
142 <p>Well, it is all well and good that you can use other people's functions, but what if you want to write your own functions, to save time, and maybe use them in other programs? This is where the 'def' operator comes in. (An operator is just something that tells python what to do, e.g. the '+' operator tells python to add things, the 'if' operator tells python to do something if conditions are met.)</p>
143 <p>This is how the 'def' operator works:</p>
144 <code>
145 <l>def function_name(parameter_1,parameter_2):</l>
146 <l> {this is the code in the function}</l>
147 <l> {more code}</l>
148 <l> {more code}</l>
149 <l> return {value to return to the main program}</l>
150 <l>{this code isn't in the function}</l>
151 <l>{because it isn't indented}</l>
152 <l>#remember to put a colon ":" at the end</l>
153 <l>#of the line that starts with 'def'</l>
154 </code>
155 <p>function_name is the name of the function. You write the code that is in the function below that line, and have it indented. (We will worry about parameter_1 and parameter_2 later, for now imagine there is nothing between the parentheses.</p>
156 <p>Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:</p>
157 <p>Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:</p>
158 <p><i>To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running.</i></p>
159 <p>A function is like a miniture program that some parameters are given to - it then runs itself, and then returns a value. Your main program sees only the returned value. If that function flew to the moon and back, and then at the end had:</p>
160 <code title="return">
161 <l>return "Hello"</l>
162 </code>
163 <p>then all your program would see is the string "hello", where the name of the function was. It would have no idea what else the program did.</p>
164 <p>Because it is a seperate program, a function doesn't see any of the variables that are in your main program, and your main program doesn't see any of the variables that are in a function. For example, here is a function that prints the words "hello" onscreen, and then returns the number '1234' to the main program:</p>
165 <code title="using return">
166 <l># Below is the function</l>
167 <l>def hello():</l>
168 <l> print hello</l>
169 <l> return 1234</l>
170 <l></l>
171 <l># And here is the function being used</l>
172 <l>print hello()</l>
173 </code>
174 <p>Think about the last line of code above. What did it do? Type in the program (you can skip the comments), and see what it does. The output looks like this:</p>
175 <code title="the output">
176 <l>hello</l>
177 <l>1234</l>
178 </code>
179 <p>So what happened?</p>
180 <orderedList>
181 <entry>when 'def hello()' was run, a function called 'hello' was created</entry>
182 <entry>When the line 'print hello()' was run, the function 'hello' was executed (The code inside it was run)</entry>
183 <entry>The function 'hello' printed "hello" onscreen, then returned the number '1234' back to the main program</entry>
184 <entry>The main program now sees the line as 'print 1234' and as a result, printed '1234</entry>
185 </orderedList>
186 <p>That accounts for everything that happened. remember, that the main program had NO IDEA that the words "hello" were printed onscreen. All it saw was '1234', and printed that onscreen.</p>
187 </section>
188 <section title="Passing Parameters to functions">
189 <p>There is one more thing we will cover in this (monsterously huge) lesson - passing parameters to a function. Think back to how we defined functions:</p>
190 <code title="Defining functions with parameters">
191 <l>def function_name(parameter_1,parameter_2):</l>
192 <l> {this is the code in the function}</l>
193 <l> {more code}</l>
194 <l> {more code}</l>
195 <l> return {value (e.g. text or number) to return to the main program}</l>
196 </code>
197 <p>Where <tt>parameter_1</tt> and <tt>parameter_2</tt> are (between the parentheses), you put the names of variables that you want to put the parameters into. Put as many as you need, just have them seperated by commas. When you run a function, the first value you put inside the parentheses would go into the variable where parameter_1 is. The second one (after the first comma) would go to the variable where parameter_2 is. This goes on for however many parameters there are in the function (from zero, to the sky) For example:</p>
198 <code title="how parameters work">
199 <l>def funnyfunction(first_word,second_word,third_word):</l>
200 <l> print "The word created is: " + first_word + second_word + third_word</l>
201 <l> return first_word + second_word + third_word</l>
202 </code>
203 <p>When you run the function above, you would type in something like this: funnyfunction("meat","eater","man"). The first value (that is, "meat") would be put into the variable called first_word. The second value inside the brackets (that is, "eater") would be put into the variable called second_word, and so on. This is how values are passed from the main program to functions - inside the parentheses, after the function name.</p>
204 </section>
205 <section title="A final program">
206 <p>Think back to that calculator program. Did it look a bit messy to you? I think it did, so lets re-write it, with functions.</p>
207 <p>To design - First we will define all the functions we are going to use with the 'def' operator (still remember what an operator is ;) ). Then we will have the main program, with all that messy code replaced with nice, neat functions. This will make it so much easier to look at again in the future.</p>
208 <code title="Calculator program">
209 # calculator program
212 # Here we will define our functions
213 # this prints the main menu, and prompts for a choice
214 def menu():
215 #print what options you have
216 print "Welcome to"
217 print "your options are:"
219 print " "
220 print "1) Addition"
221 print "2) Subtraction"
222 print "3) Multiplication"
224 print "4) Division"
226 print "5) Quit"
227 print " "
228 return input ("Choose your option: ")
230 # this adds two numbers given
231 def add(a,b):
232 print a, "+", b, "=", a + b
234 # this subtracts two numbers given
235 def sub(a,b):
236 print b, "-", a, "=", b - a
238 # this multiplies two numbers given
239 def mul(a,b):
240 print a, "*", b, "=", a * b
242 # this divides two numbers given
243 def div(a,b):
244 print a, "/", b, "=", a / b
247 loop = 1
248 choice = 0
249 while loop == 1:
250 choice = menu()
251 if choice == 1:
252 add(input("Add this: "),input("to this: "))
253 elif choice == 2:
254 sub(input("Subtract this: "),input("from this: "))
255 elif choice == 3:
256 mul(input("Multiply this: "),input("by this: "))
257 elif choice == 4:
258 div(input("Divide this: "),input("by this: "))
259 elif choice == 5:
260 loop = 0
262 print "Thankyou for using!"
Something went wrong with that request. Please try again.