Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 420 lines (367 sloc) 22.01 kb
83567d0 @stoive directory restructure
authored
1 <html>
2 <head>
3 <title>Lesson 5 - Functions</title>
4 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
5 <meta name="keywords" content="civilization,civ2,civ3,civ4,civilization iii,civilization ii,civilization iv,mod,python,xml,script,install" />
6 <meta name="description" content="A Python and XML tutorial aimed at Civilization IV modding" />
7 </head><link rel="stylesheet" type="text/css" href="../../stylesheet.css" />
8
9 <body bgcolor="Teal">
10 <div align="center" class="SidePanel">
11 <div align="left" class="PaddingBig">
12 <div class="MenuSection">
13 <h1>Sthurlow.com</h1>
14 <h2>Civilization IV Python tutorial</h2><h3>The Python Tutorial</h3>
15 <p>The original sthurlow.com python tutorial</p>
16 <p>
17 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson01/">Installing Python</a></div>
18 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson02/">Very Simple Programs</a></div>
19 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson03/">Variables, Scripts</a></div>
20 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson04/">Loops, Conditionals</a></div>
21 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson05/">Functions</a></div>
22 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson06/">Tuples, Lists, Dictionaries</a></div>
23 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson07/">for Loop</a></div>
24 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson08/">Classes</a></div>
25 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson09/">Importing Modules</a></div>
26 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson10/">File I/O</a></div>
27 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/python/lesson11/">Error Handling</a></div>
28 </p>
29 <h3>The Civ4 Programming Tutorial</h3>
30 <p>All new Civ4 programming tutorial</p>
31 <p>
32 <div class="MenuItem">&nbsp;<a href="http://www.sthurlow.com/">Lesson 1 (not released)</a></div>
33 </p>
34 <br /><br /></div></div>
35 </div>
36
37 <div align="center" class="TextPanel">
38 <div align="left" class="Padding"><h2>Functions</h2>
39
40 <h3>Introduction</h3>
41 <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>
42 <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>
43
44 <h3>Using a function</h3>
45 <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>
46
47 <div align="center">
48 <div align="center" class="CodeTitle">Code Example 1 - How to call a function</div>
49 <div align="left" class="CodeBody">
50 <pre>
51 function_name(parameters)
52 </pre>
53 </div>
54 </div><p>See? Easy.</p>
55
56 <ul><li>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.</li>
57 <li>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.</li>
58
59 </ul>
60 <h3>Parameters and Returned Values - Communicating with Functions</h3>
61 <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>
62 <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>
63
64 <div align="center">
65 <div align="center" class="CodeTitle">Code Example 2 - Using a function</div>
66 <div align="left" class="CodeBody">
67 <pre>
68 a = multiply(70)
69 </pre>
70 </div>
71 </div><p>The computer would actually see this:</p>
72
73 <div align="center">
74 <div align="center" class="CodeTitle">Code Example 3 - What the computer sees</div>
75 <div align="left" class="CodeBody">
76 <pre>
77 a = 350
78 </pre>
79 </div>
80 </div><p>note: don't bother typing in this code - multiply() isn't a real function, unless you create it.</p>
81 <p>The function ran itself, then returned a number to the main program, based on what parameters it was given.</p>
82 <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>
83
84 <div align="center">
85 <div align="center" class="CodeTitle">Code Example 4 - Using raw_input</div>
86 <div align="left" class="CodeBody">
87 <pre>
88 # this line makes 'a' equal to whatever you type in
89 a = raw_input("Type in something, and it will be repeated on screen:")
90 # this line prints what 'a' is now worth
91 print a
92 </pre>
93 </div>
94 </div><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>
95
96 <div align="center">
97 <div align="center" class="CodeTitle">Code Example 5 - What the computer sees</div>
98 <div align="left" class="CodeBody">
99 <pre>
100 a = "hello"
101 print "hello"
102 </pre>
103 </div>
104 </div><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>
105
106 <h3>A Calculator Program</h3>
107 <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>
108 <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>
109 <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>
110 <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>
111 <p>Lets write it out in understandable English first:</p>
112
113 <div align="center">
114 <div align="center" class="CodeTitle">Code Example 6 - human-language example</div>
115 <div align="left" class="CodeBody">
116 <pre>
117 START PROGRAM
118 print opening message
119
120 while we let the program run, do this:
121 #Print what options you have
122 print Option 1 - add
123 print Option 2 - subtract
124 print Option 3 - multiply
125 print Option 4 - divide
126 print Option 5 - quit program
127
128 ask for which option is is you want
129 if it is option 1:
130 ask for first number
131 ask for second number
132 add them together
133 print the result onscreen
134 if it is option 2:
135 ask for first number
136 ask for second number
137 subtract one from the other
138 print the result onscreen
139 if it is option 3:
140 ask for first number
141 ask for second number
142 multiply!
143 print the result onscreen
144 if it is option 4:
145 ask for first number
146 ask for second number
147 divide one by the other
148 print the result onscreen
149 if it is option 5:
150 tell the loop to stop looping
151 Print onscreen a goodbye message
152 END PROGRAM
153 </pre>
154 </div>
155 </div><p>Lets put this in something that python can understand:</p>
156
157 <div align="center">
158 <div align="center" class="CodeTitle">Code Example 7 - Python verion of menu</div>
159 <div align="left" class="CodeBody">
160 <pre>
161 #calculator program
162
163 #this variable tells the loop whether it should loop or not.
164 # 1 means loop. anything else means don't loop.
165
166 loop = 1
167
168 #this variable holds the user's choice in the menu:
169
170 choice = 0
171
172 while loop == 1:
173 #print what options you have
174 print "Welcome to calculator.py"
175
176 print "your options are:"
177 print " "
178 print "1) Addition"
179 print "2) Subtraction"
180
181 print "3) Multiplication"
182
183 print "4) Division"
184 print "5) Quit calculator.py"
185 print " "
186
187 choice = input("Choose your option: ")
188 if choice == 1:
189 add1 = input("Add this: ")
190 add2 = input("to this: ")
191 print add1, "+", add2, "=", add1 + add2
192 elif choice == 2:
193 sub2 = input("Subtract this: ")
194 sub1 = input("from this: ")
195 print sub1, "-", sub2, "=", sub1 - sub2
196 elif choice == 3:
197 mul1 = input("Multiply this: ")
198 mul2 = input("with this: ")
199 print mul1, "*", mul2, "=", mul1 * mul2
200 elif choice == 4:
201 div1 = input("Divide this: ")
202 div2 = input("by this: ")
203 print div1, "/", div2, "=", div1 / div2
204 elif choice == 5:
205 loop = 0
206
207 print "Thankyou for using calculator.py!"
208 </pre>
209 </div>
210 </div><p>Wow! That is an impressive program! Paste it into python IDLE, save it as 'calculator.py' 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>
211
212 <h3>Define Your Own Functions</h3>
213 <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>
214 <p>This is how the 'def' operator works:</p>
215
216 <div align="center">
217 <div align="center" class="CodeTitle">Code Example 8 - The def operator</div>
218 <div align="left" class="CodeBody">
219 <pre>
220 def function_name(parameter_1,parameter_2):
221 {this is the code in the function}
222 {more code}
223 {more code}
224 return {value to return to the main program}
225 {this code isn't in the function}
226 {because it isn't indented}
227 #remember to put a colon ":" at the end
228 #of the line that starts with 'def'
229 </pre>
230 </div>
231 </div><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>
232 <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>
233 <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>
234 <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>
235 <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>
236
237 <div align="center">
238 <div align="center" class="CodeTitle">Code Example 9 - return</div>
239 <div align="left" class="CodeBody">
240 <pre>
241 return "Hello"
242 </pre>
243 </div>
244 </div><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>
245 <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>
246
247 <div align="center">
248 <div align="center" class="CodeTitle">Code Example 10 - using return</div>
249 <div align="left" class="CodeBody">
250 <pre>
251 # Below is the function
252 def hello():
253 print "hello"
254 return 1234
255
256 # And here is the function being used
257 print hello()
258 </pre>
259 </div>
260 </div><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>
261
262 <div align="center">
263 <div align="center" class="CodeTitle">Code Example 11 - the output</div>
264 <div align="left" class="CodeBody">
265 <pre>
266 hello
267 1234
268 </pre>
269 </div>
270 </div><p>So what happened?</p>
271 <ol>
272 <li>when 'def hello()' was run, a function called 'hello' was created</li>
273 <li>When the line 'print hello()' was run, the function 'hello' was executed (The code inside it was run)</li>
274 <li>The function 'hello' printed "hello" onscreen, then returned the number '1234' back to the main program</li>
275 <li>The main program now sees the line as 'print 1234' and as a result, printed '1234</li>
276 </ol>
277 <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>
278
279 <h3>Passing Parameters to functions</h3>
280 <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>
281
282 <div align="center">
283 <div align="center" class="CodeTitle">Code Example 12 - Defining functions with parameters</div>
284 <div align="left" class="CodeBody">
285 <pre>
286 def function_name(parameter_1,parameter_2):
287 {this is the code in the function}
288 {more code}
289 {more code}
290 return {value (e.g. text or number) to return to the main program}
291 </pre>
292 </div>
293 </div><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>
294
295 <div align="center">
296 <div align="center" class="CodeTitle">Code Example 13 - how parameters work</div>
297 <div align="left" class="CodeBody">
298 <pre>
299 def funnyfunction(first_word,second_word,third_word):
300 print "The word created is: " + first_word + second_word + third_word
301 return first_word + second_word + third_word
302 </pre>
303 </div>
304 </div><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>
305
306 <h3>A final program</h3>
307 <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>
308 <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>
309
310 <div align="center">
311 <div align="center" class="CodeTitle">Code Example 14 - Calculator program</div>
312 <div align="left" class="CodeBody">
313 <pre>
314 # calculator program
315
316 # NO CODE IS REALLY RUN HERE, IT IS ONLY TELLING US WHAT WE WILL DO LATER
317 # Here we will define our functions
318 # this prints the main menu, and prompts for a choice
319 def menu():
320 #print what options you have
321 print "Welcome to calculator.py"
322 print "your options are:"
323 print " "
324 print "1) Addition"
325 print "2) Subtraction"
326 print "3) Multiplication"
327 print "4) Division"
328 print "5) Quit calculator.py"
329 print " "
330 return input ("Choose your option: ")
331
332 # this adds two numbers given
333 def add(a,b):
334 print a, "+", b, "=", a + b
335
336 # this subtracts two numbers given
337 def sub(a,b):
338 print b, "-", a, "=", b - a
339
340 # this multiplies two numbers given
341 def mul(a,b):
342 print a, "*", b, "=", a * b
343
344 # this divides two numbers given
345 def div(a,b):
346 print a, "/", b, "=", a / b
347
348 # NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN
349 loop = 1
350 choice = 0
351 while loop == 1:
352 choice = menu()
353 if choice == 1:
354 add(input("Add this: "),input("to this: "))
355 elif choice == 2:
356 sub(input("Subtract this: "),input("from this: "))
357 elif choice == 3:
358 mul(input("Multiply this: "),input("by this: "))
359 elif choice == 4:
360 div(input("Divide this: "),input("by this: "))
361 elif choice == 5:
362 loop = 0
363
364 print "Thankyou for using calculator.py!"
365
366 # NOW THE PROGRAM REALLY FINISHES
367 </pre>
368 </div>
369 </div><p>The initial program had 34 lines of code. The new one actually had 35 lines of code! It is a little longer, but if you look at it the right way, it is actually simpler.</p>
370 <p>You defined all your functions at the top. This really isn't part of your main program - they are just lots of little programs, that you will call upon later. You could even re-use these in another program if you needed them, and didn't want to tell the computer how to add and subtract again.</p>
371 <p>If you look at the main part of the program (between the line 'loop = 1' and 'print "Thankyou for..."'), it is only 15 lines of code. That means that if you wanted to write this program differently, you would only have to write 15 or so lines, as opposed to the 34 lines you would normally have to without functions.</p>
372
373 <h3>Tricky Ways You Can Pass Parameters</h3>
374 <p>Finally, as a bit of an interlude, I will explain what the line <tt>add(input("Add this: "),input("to this: "))</tt> means.</p>
375 <p>I wanted to fit everything onto one line, with as few variables as possible. Remember what functions look like to the main program? Whatever value they return. If the numbers you passed to the add() function were 2 and 30, the main program would see this:</p>
376
377 <div align="center">
378 <div align="center" class="CodeTitle">Code Example 15 - The results of fancy parameter work</div>
379 <div align="left" class="CodeBody">
380 <pre>
381 add(2,30)
382 </pre>
383 </div>
384 </div><p>The add program would then run, adding 2 and 30, then printing the result. The add program has no 'return' operator - it doesn't return anything to the main program. It simply adds two numbers and prints them onscreen, and the main program doesn't see anything of it.</p>
385 <p>Instead of <tt>(input("Add this: "),input("to this: "))</tt> as the parameters for the add program you could have variables. E.g.</p>
386
387 <div align="center">
388 <div align="center" class="CodeTitle">Code Example 16 - variables as parameters</div>
389 <div align="left" class="CodeBody">
390 <pre>
391 num1 = 45
392 num2 = 7
393 add(num1,num2)
394 </pre>
395 </div>
396 </div><p>For the above, remember that the function you are passing the variables to cannot change the variables themselves - they are simply used as values. You could even put the values straight into the function:</p>
397
398 <div align="center">
399 <div align="center" class="CodeTitle">Code Example 17 - the end result</div>
400 <div align="left" class="CodeBody">
401 <pre>
402 add(45,7)
403 </pre>
404 </div>
405 </div><p>This is because the only thing the function sees are the values that are passed on as parameters. Those values are put into the variables that are mentioned when 'add' is defined (the line 'def add(a,b)' ). The function then uses those parameters to do it's job.</p>
406 <p>In short:</p>
407
408 <ul><li>The only thing functions see of the main program is the parameters that are passed to it</li>
409 <li>the only thing the main program seens of functions is the returned value that it passes back</li>
410
411 </ul>
412 <h3>Conclusion</h3>
413 <p>WHOA!!!! WHAT A KILLER LESSON!!! But we got through it, and I made minimal typos. Great!</p>
414 <p>I haven't decided what will happen in lesson 6. All I can say is I am having a BIG breather, because this lesson took me many hours to write.</p>
415 <p>Thanks to all,</p>
416 <p>sthurlow.com</p>
417
418 </div></div></body>
419 </html>
Something went wrong with that request. Please try again.