PYTHON: Functions Common needs of a programmer can be turned into functions in Python.
A function saves the programmer having to repeatedly type out lines of code. Using a function shorten the coding document and makes it easier to understand, because the function's name can explicitly state what the code is doing - and when defining it at the head of your program, you can add 'comments' to explain that more fully. What does a function do?A function takes some data (the function's input) and returns some other data (the function's output). For example the 'sum function' can take a list of numbers as its input and return the sum of all of the numbers in the list as a single number as output.
To apply a function to some data (whether it's a variable, a number or a string), you just write the name of the function followed by the data in parenthesis. The computer will then calculate the function's output, which can be used in further calculations or assigned to a variable. Library of pre-written functions for Python 3There is a library of functions that are already written for you to call upon - 'sum' being one of them. There is a vast array - and some of them can prove very useful. They are listed here. Do take a look. If you scroll down you will see an explanation of what each one does. Functions that have a page of their own within this site: Making your own functionsA function is a block of code which only runs when it is called. A function must be written in the head of your program. It can then be called upon - as it has been defined. You can put anything you like into a function - but it only makes sense to write one if it will be used several times within your program. You pass data, known as parameters, into a function, then the function can return data as a result of its action upon that data. When coding in Basic in the 'olden days' I used subroutines to do a similar thing. For example.
|
|