Functions
A function is like a piece of code that we can run over and over again. It lets us repeat tasks without having to write the same code everywhere. A function is created by using the def
keyword followed by the name of the function and parentheses.
def greeting():
print("Hello there")
We just defined a function called greeting
that will run the code inside every time we call it.
To call the function just type the name with the parentheses after, functions can be called multiple times
and can be called from anywhere.
def greeting():
print("Hello there")
greeting() # Hello world
greeting() # Hello world
Arguments and returning
Function can have an input, called arguments, and an output, called a return. We can pass data into the function, called an argument, and optionally return data as well. To add an argument to the function specify its name inside the parentheses.
def greet_user(username):
print(f"Hello {username}")
greet_user("CatLover89")
A function can have any number of arguments, which are separated by commas, the order of arguments in the definition is the same order as the call site.
def multiply(left,right):
print(left * right)
multiply(10,5)
We can return a value from a function as well, using the return
keyword.
def multiply(left,right):
return left * right
answer = multiply(10,50)
print(f"The answer is {answer}")
The answer
variable now contains the output of the multiply
function which would be 5000
.
These types of arguments are called positional arguments, they are also keyword arguments which let you specify the name of the argument.
def multiply(left,right):
return left * right
multiply(right=10,left=100)
Keyword arguments always have to come after the positional arguments. info
Scopes
Everything declared in a function will be in that functions scope, and only be usable inside that function.
# Global scope
status = "Active"
def print_status(status):
# Function scope
print(status)
print_status("Done") # Done
Default parameters
Functions can have default parameters, which means the parameter can be left out and the default will be used, but if it’s included then the default will be over written.
def greeting(name, greeting="hello"):
print(f"{greeting} {name}")
greeting("Alice")
greeting("Rob", "HI")