Im not sure i get the whole function thing with 'def' could anyone help me?
Sure. There are all these built-in functions that Python has defined for us. For example, if we want to turn the number 4 into the string '4', we can type str(4). If we have the list [1,2,3,4,5] and want to know the sum of all the numbers, we can type sum([1,2,3,4,5]) and we'll get 15. All these built in functions are wonderful. They take in some input and return some output. For example, the sum function took a list and returned a single number that was the sum of all the elements in the list. As great as all these built-in functions are, what if we want to create our own? For example, what if I want to take a list of numbers and find the PRODUCT of the numbers in the list? I would have to write it myself. The "def" keyword allows us to define our own functions. I follow it with the name of of my new function, followed by a '(' and then the names of all the pieces of input that I want to give the function, and finally a ')' and a ':'. In the indented body of the function, I tell the function what I want it to do, and the very last thing I do is I tell the function what I want it to return as output using the "return" keyword. Our product function might go something like this: def product(num_list): # I've called the function "product" and input "num_list" prod = 1 # I start my product off at 1 for element in num_list: prod = prod * element #I take each element and multiply it to the running prod. return prod #Once I have the final product, I return it. Now, I can run my new function by typing product([1,2,3,4,5]). In the interpreter, it will return the value 120, which is 1*2*3*4*5.
functions let you encapsulate bits of code in their own little functional unit. One advantage is that once you write a function you can call it many times without having to rewrite your code. Another advantage is that they make large programs more readable - instead of having those 5 or ten or twenty lines of code clutter up your program, you can encapsulate it in a function, give it a meaningful name then use it just by calling it by name - if you give functions meaningful names, the code that uses can sometimes read like a sentence... http://dpaste.com/764084/
Try working in functions in even the small programs. It's a good way to learn the basics of how they work - like the product function that shandelman wrote for example. Things don't have to be complicated to qualify to be made into a function.
Join our real-time social learning platform and learn together with your friends!