Lesson 10: Functions
Defining a function
Python functions are defined using the keyword def:
The def keyword is followed by the function name and parenthesis ().
def basic_function():
print("I Love Python")
Try create your own function
Functions with a parameter
Parameter are values that can be passed through a function. Arguments are another term used instead of parameters. They are the same thing. Throughout the lesson, we will use the term parameter.
When a function is created, the parameters are defined inside the brackets, also known as parenthesis, which are found after the function name.
def my_function(firstname):
print("My name is and " + firstname)
my_function("Kevin")
Try pass a parameter through a function
Calling a function
Use the function name followed by parenthesis to call a function. When passing parameters through a function, you must pass the correct number of parameters back.
Functions with multiple parameters
Functions can pass multiple parameters.
When declaring multiple parameters, you must include a comma between parameters.
def fruit_function(firstFruit , secondFruit):
print("My favourite fruits are " + firstFruit + " & " + secondFruit)
fruit_function("Apple" , "Orange")
Try passing two parameters through a function
Calling functions with keyword parameters
def fruit_function(firstFruit , secondFruit):
print("My favorite fruit is "+ firstFruit + "& my least favorite fruit is " + secondFruit + ".")
fruit_function("Apples" , "Oranges")
favoriteFruit = "Orange"
leastFavoriteFruit= "Apple"
fruit_function(secondFruit = leastFavoriteFruit, firstFruit = favoriteFruit)
Try passing keyword parameters through a function
Functions that return values
Sometimes we will want a function to return a value to use later in our code rather than the function printing out the output. This is when we use the return keyword in our function. The return keyword returns the value of a given variable from the function.
def multiplier(x,y):
return x * y
print(multiplier(3,5))
print(multiplier(5,8))
print(multiplier(9,9))
Try returning values through a function
Resources