-
Notifications
You must be signed in to change notification settings - Fork 1
Functions
So far, we've been coding python in small fragments. This can be useful for very small programs or minor tasks, however, we can quickly realize that this has some limitations.
For larger programs, we want to increase the efficiency of our program by allowing parts of our code to be reusable. This can be done by the usage of Functions
Function : A named piece of code, separate from all others.
A Function can take any number and type of input parameters and return any number and type of output results.
You can do two things with functions:
- Define it
- Call it
Here is how you define a function in python:
def test(): The def signals the computer that you're defining a function.
The following word is the name of the function "test". Followed by parentheses "()". Then a colon ":".
Whatever follows the ":" would be the function body or what is executed whenever you call the function.
Here is an intuitive example:
def uglyShoes():
print('what are those???')
In this case, the print('what are those???')
will be executed if you call the function as follows:
uglyShoes()
Most of the time, you will want your functions to take in some values to do something. You can do this by define parameters in your function. For example:
def plus(a,b):
print(a+b)
plus(5,6) #this will return 11
In Python, a function can return any value that you want. For example:
def plus(a,b):
return a+b
c = plus(4,5)
print(c) #9
A function can also return no value.
global Statement