Functions¶
What are Functions?¶
Functions are callable portions of code that can be used to perform some sort of task. They are useful breaking programs into steps and creating efficient and reusable code.
We have been using many functions throughout the term so far. Python has some built-in functions, like len() and range(), to name a few. The packages we import, like numpy and matplotlib, have their own sets of functions as well, like plt.plot() and np.mean().
Now, we will learn how to make our own functions!
Creating a Function¶
A function is defined using the def keyword, followed by the name of the function, as well as any parameters it should accept, if any.
# A function with no parameters
def no_param_func():
pass
# A function with parameters
def multiply_nums(num1, num2):
pass
After defining the function, you can create the function body, which is the code in the function that is executed when the function is called.
# Adding the function body
def multiply_nums(num1, num2):
result = num1 * num2
In the function above, we defined the variable result to hold the value of the multiplied numbers. However, this variable can only be accessed within the function, so if you tried to access result outside it, you would receive an error. If we want to access the result, then we need to return the value.
Functions can return values using a return statement. The value or variable after the return statement in the function can then be "caught" by a variable or print statement outside the function and used elsewhere in your code.
# Returning the result
def multiply_nums(num1, num2):
result = num1 * num2
return result
To test how this work, let's call the function. To call the function, you use the defined name and provide the required arguments, then it will execute the code within your function.
# Calling the function
total = multiply_nums(2, 3)
print(total)
6
As you can see, we call multiply_nums(2, 3), which executes the function with the numbers 2 and 3. The function call multiplies the numbers, then returns the result, 6, which is then caught by the variable total, and finally printed.
Here's what the entire process looks like, all together.
def multiply_nums(num1, num2):
result = num1 * num2
return result
total = multiply_nums(2, 3)
print(total)
6
Below are some various functions examples:
# A function to count the vowels in a provided word
def count_vowels(word):
vowel_count = 0
for letter in word:
if letter == 'a':
vowel_count += 1
elif letter == 'e':
vowel_count += 1
elif letter == 'i':
vowel_count += 1
elif letter == "o":
vowel_count += 1
elif letter == "u":
vowel_count += 1
return vowel_count
# Calling the function
print(f"onomatopoeia has {count_vowels("onomatopoeia")} vowels.")
print(f"eutopia has {count_vowels("eutopia")} vowels.")
onomatopoeia has 8 vowels. eutopia has 5 vowels.
# A function to return the divisors of a number
def determine_divisors(number):
divisors = []
for num in range(1, number):
if number % num == 0:
divisors.append(num)
divisors.append(number)
return divisors
# Calling the function
print(f"The divisors of 20 are {determine_divisors(20)}")
The divisors of 20 are [1, 2, 4, 5, 10, 20]
# A function to convert inches to centimeters
def inch_to_cm(i_num):
return i_num * 2.54
# Calling the function
print(f"3 inches is {inch_to_cm(3)} centimeters.")
print(f"7.8 inches is {inch_to_cm(7.8)} centimeters.")
3 inches is 7.62 centimeters. 7.8 inches is 19.812 centimeters.
Function Calls within Functions¶
Within a function, you can call another function that you've defined.
# A function to convert centimeters to millimeters
def cm_to_mm(cm_num):
return cm_num * 10
# Calling the function
print(f"3.65 centimeters is {cm_to_mm(3.65)} millimeters.")
3.65 centimeters is 36.5 millimeters.
# A function to convert inches to millimeters, usually previously defined functions
def inch_to_mm(i_num):
centimeters = inch_to_cm(i_num)
millimeters = cm_to_mm(centimeters)
return millimeters
print(f"1 inch is {inch_to_mm(1)} millimeters.")
1 inch is 25.4 millimeters.