Python, like most programming languages, makes extensive use of functions. Functions act as containers for code. When a function is called, the code it contains is executed. Sometimes a function is defined as having one or more parameters. Parameters allow the programmer to pass in values which are processed by the function's code.
A function name should clearly indicate what the code inside will do. For example, here's a statement which calls a function with a single text string parameter:
>>> len("Hello")
The 'len'
function returns the length of the input parameter. In this case the returned value is five. Let's try another example. This statement will ask the user for their name using a prompt string:
>>> name = raw_input("What is your name? ")
Here we're using the function 'raw_input'
to capture the user's name. The text string we supplied as parameter will be printed as an input prompt. Whatever you type in response to this prompt is stored in the variable 'name'
.
Now we can use the 'name'
variable in other Python statements, like this:
>>> print("Hello " + name)
Throughout this series we'll use dozens of Python's functions, and later I'll show how to define our own functions.
A post from my Learn Python on the Raspberry Pi tutorial.