Functions¶
A function is a sequence of instructions that has been given a name. Functions usually (but not always) take some number of inputs, called parameters, and usually (but not always) give an output, called the return value. When we use a function in our code, we say that we are calling the function.
Once a function has been defined, it can be called from anywhere within your program. If you find that there is a task that you are repeating often and that requires several lines of codes, it might be a good idea to group those lines of code together into a function.
Most functions we write will accept one or more inputs and will generate an output. However, We will start by considering functions that do not accept inputs, and that do not provide outputs. The syntax for defining such a function is as follows:
def function_name(): Code to be executed by the function.
We start by defining a (very) simple function below.
def greeting():
print("Hello, world!")
Notice that nothing was printed when we defined the function. This cell defined the function, but it did not call it. Thus, the code inside of the function was not executed.
greeting()
Hello, world!
for i in range(0,5):
greeting()
Hello, world!
Hello, world!
Hello, world!
Hello, world!
Hello, world!