Functions in Python
Subject: Python Programming
Functions are exactly what the sound like, they allow you to perform a particular task or function. In programming you call a function when you need to perform a task.
Since the beginning of this Python course we have been using functions that comes with the Python language i.e Built-in functions.
One of the great things about Python language is its extensive library of built-in functions that can make programming tasks easier and more efficient.
Examples of some Python built-in function
print()
list()
range()
int()
str()
input()
min()
max()
sum()
reversed()
sorted()
Python may have about 100 or more built-in functions but you may still want to perform a task that does not have a built-in function for, in this case you will have to create your own function. this is called a user defined function.
How to create your function (User defined functions)
You create a function when you need to extend the power of Python beyond the limit of it's built-in function in your program.
Creating your functions also allow you to easily manage our program. They allow large program to be broken down into smaller, manageable and reusable units.
Example 1
#create a function with empty bracket i.e no argument - no input
def welcome():
print ("Welcome to TEA Learn")
#call the function
welcome()
Example 2
#function with one argument and return
def welcome(name):
msg = "Welcome "+name+" to TEA Learn"
return (msg)
#call the function and string value supply to it's argument
display=welcome("Onuorah")
print (display)
Example 3
#function with two arguments
#function with two arguments
def power(number1, number2):
ans = number1**number2
return (ans)
#call the function and input values
val1=int(input("Enter first number "))
val2=int(input("Enter second number "))
result=power(val1,val2)
#concatenate or join number + to string will require converting the number to string
print (str(val1)+" raise to power "+str(val2)+" is "+str(result))
It is common to have your functions in a separate (source) file, so that it can be easily reference and use by all the (external) files that needs it's function this will prevent redundancy cause by rewriting the code in several files:
Example 4
my_arithmetic.py
def add(y, z):
return y + z
def multiply(y, z):
return y * z
Importing function from another file
Assuming the program in Example 4 is in a file name
my_arithmetic.py to import it's functions to this main program in example 5 with file name
calculate.py we will have reference it as follow:
Example 5
calculate.py
#from source file import function 1, function 2, function n
from my_arithmetic import add, multiply
num1=int(input ("Enter the first number "))
num2=int(input ("Enter the second number "))
ans1=add(num1, num2)
ans2=multiply(num1, num2)
print ("Result for addition is ", ans1)
print ("Result for multiplication is ", ans2)
By:
Benjamin Onuorah
Login to comment or ask question on this topic
Previous Topic Next Topic