Understanding Python Function
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.Using a function
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:
Code Example 1 - How to call a function
function_name(parameters)
- 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.
- 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.
Parameters and Returned Values - Communicating with Functions
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?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:
Code Example 2 - Using a function
a = multiply(70)
Code Example 3 - What the computer sees
a = 350
The function ran itself, then returned a number to the main program, based on what parameters it was given.
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:
Code Example 4 - Using raw_input
# this line makes 'a' equal to whatever you type in a = raw_input("Type in something, and it will be repeated on screen:") # this line prints what 'a' is now worth print a
Code Example 5 - What the computer sees
a = "hello" print "hello"
A Calculator Program
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.).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.
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.
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.
Lets write it out in understandable English first:
Code Example 6 - human-language example
START PROGRAM print opening message while we let the program run, do this: #Print what options you have print Option 1 - add print Option 2 - subtract print Option 3 - multiply print Option 4 - divide print Option 5 - quit program ask for which option is is you want if it is option 1: ask for first number ask for second number add them together print the result onscreen if it is option 2: ask for first number ask for second number subtract one from the other print the result onscreen if it is option 3: ask for first number ask for second number multiply! print the result onscreen if it is option 4: ask for first number ask for second number divide one by the other print the result onscreen if it is option 5: tell the loop to stop looping Print onscreen a goodbye message END PROGRAM
Code Example 7 - Python verion of menu
#calculator program #this variable tells the loop whether it should loop or not. # 1 means loop. anything else means don't loop. loop = 1 #this variable holds the user's choice in the menu: choice = 0 while loop == 1: #print what options you have print "Welcome to calculator.py" print "your options are:" print " " print "1) Addition" print "2) Subtraction" print "3) Multiplication" print "4) Division" print "5) Quit calculator.py" print " " choice = input("Choose your option: ") if choice == 1: add1 = input("Add this: ") add2 = input("to this: ") print add1, "+", add2, "=", add1 + add2 elif choice == 2: sub2 = input("Subtract this: ") sub1 = input("from this: ") print sub1, "-", sub2, "=", sub1 - sub2 elif choice == 3: mul1 = input("Multiply this: ") mul2 = input("with this: ") print mul1, "*", mul2, "=", mul1 * mul2 elif choice == 4: div1 = input("Divide this: ") div2 = input("by this: ") print div1, "/", div2, "=", div1 / div2 elif choice == 5: loop = 0 print "Thankyou for using calculator.py!"
Define Your Own Functions
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.)This is how the 'def' operator works:
Code Example 8 - The def operator
def function_name(parameter_1,parameter_2): {this is the code in the function} {more code} {more code} return {value to return to the main program} {this code isn't in the function} {because it isn't indented} #remember to put a colon ":" at the end #of the line that starts with 'def'
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:
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:
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.
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:
Code Example 9 - return
return "Hello"
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:
Code Example 10 - using return
# Below is the function def hello(): print "hello" return 1234 # And here is the function being used print hello()
Code Example 11 - the output
hello 1234
- when 'def hello()' was run, a function called 'hello' was created
- When the line 'print hello()' was run, the function 'hello' was executed (The code inside it was run)
- The function 'hello' printed "hello" onscreen, then returned the number '1234' back to the main program
- The main program now sees the line as 'print 1234' and as a result, printed '1234
Passing Parameters to functions
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:
Code Example 12 - Defining functions with parameters
def function_name(parameter_1,parameter_2): {this is the code in the function} {more code} {more code} return {value (e.g. text or number) to return to the main program}
Code Example 13 - how parameters work
def funnyfunction(first_word,second_word,third_word): print "The word created is: " + first_word + second_word + third_word return first_word + second_word + third_word
A final program
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.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.
Code Example 14 - Calculator program
# calculator program # NO CODE IS REALLY RUN HERE, IT IS ONLY TELLING US WHAT WE WILL DO LATER # Here we will define our functions # this prints the main menu, and prompts for a choice def menu(): #print what options you have print "Welcome to calculator.py" print "your options are:" print " " print "1) Addition" print "2) Subtraction" print "3) Multiplication" print "4) Division" print "5) Quit calculator.py" print " " return input ("Choose your option: ") # this adds two numbers given def add(a,b): print a, "+", b, "=", a + b # this subtracts two numbers given def sub(a,b): print b, "-", a, "=", b - a # this multiplies two numbers given def mul(a,b): print a, "*", b, "=", a * b # this divides two numbers given def div(a,b): print a, "/", b, "=", a / b # NOW THE PROGRAM REALLY STARTS, AS CODE IS RUN loop = 1 choice = 0 while loop == 1: choice = menu() if choice == 1: add(input("Add this: "),input("to this: ")) elif choice == 2: sub(input("Subtract this: "),input("from this: ")) elif choice == 3: mul(input("Multiply this: "),input("by this: ")) elif choice == 4: div(input("Divide this: "),input("by this: ")) elif choice == 5: loop = 0 print "Thankyou for using calculator.py!" # NOW THE PROGRAM REALLY FINISHES
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.
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.
Tricky Ways You Can Pass Parameters
Finally, as a bit of an interlude, I will explain what the line add(input("Add this: "),input("to this: ")) means.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:
Code Example 15 - The results of fancy parameter work
add(2,30)
Instead of (input("Add this: "),input("to this: ")) as the parameters for the add program you could have variables. E.g.
Code Example 16 - variables as parameters
num1 = 45 num2 = 7 add(num1,num2)
Code Example 17 - the end result
add(45,7)
In short:
- The only thing functions see of the main program is the parameters that are passed to it
- the only thing the main program seens of functions is the returned value that it passes back
Conclusion
WHOA!!!! WHAT A KILLER LESSON!!! But we got through it, and I made minimal typos. Great!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.
Thanks to all,
sthurlow.com
0 comments :