You are on page 1of 11

Function

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")

my_function()

Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is called,
we pass along a first name, which is used inside the function to print the full name:
def my_function(fname):
print(fname + " Hello")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
def sum(num1,num2):
total=num1+num2
print(total);
sum(5,9)

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed
into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and not
less.

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil")

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

my_function(“Email”, “Tobias”, “Linus”, “Mutax”)

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments, and can access the items
accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")

Default Parameter Value


The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

Return Values
To let a function return a value, use the return statement

Example
def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

The pass Statement


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid getting
an error.

Example
def myfunction():
pass

Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant
approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We
use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends
when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Exercises

1. Write a Python function to find the maximum of three


numbers.
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
2. Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20

def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))
3. Write a Python function to multiply all the numbers in a list.
Sample List : (8, 2, 3, -1, 7)
Expected Output : -336

def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))
4. Write a Python program to reverse a string.
Sample String : "1234abcd"
Expected Output : "dcba4321"

def string_reverse(str1):

rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('1234abcd'))
5. Write a Python function to calculate the factorial of a
number (a non-negative integer). The function accepts the
number as an argument.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

6. Write a Python function to check whether a number falls


within a given range.

def test_range(n):
if n in range(3,9):
print( " %s is in the range"%str(n))
else :
print("The number is outside the given range.")
test_range(5)
7. Write a Python function that accepts a string and counts the
number of upper and lower case letters.
Sample String : 'The quick Brow Fox'
Expected Output :
No. of Upper case characters : 3
No. of Lower case Characters : 12

def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"]+=1
elif c.islower():
d["LOWER_CASE"]+=1
else:
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ", d["LOWER_CASE"])

string_test('The quick Brown Fox')

8. Write a Python function that takes a list and returns a new


list with distinct elements from the first list.
Sample List : [1,2,3,3,3,3,4,5]
Unique List : [1, 2, 3, 4, 5]

def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x

print(unique_list([1,2,3,3,3,3,4,5]))
9. Write a Python function that takes a number as a parameter
and checks whether the number is prime or not.
Note : A prime number (or a prime) is a natural number
greater than 1 and that has no positive divisors other than 1
and itself.

def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))

10. Write a Python program to print the even numbers from a


given list.
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9]
Expected Result : [2, 4, 6, 8]

def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))

11. Write a Python function to check whether a number is


"Perfect" or not.
According to Wikipedia : In number theory, a perfect number
is a positive integer that is equal to the sum of its proper
positive divisors, that is, the sum of its positive divisors
excluding the number itself (also known as its aliquot sum).
Equivalently, a perfect number is a number that is half the
sum of all of its positive divisors (including itself).
Example : The first perfect number is 6, because 1, 2, and 3
are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently,
the number 6 is equal to half the sum of all its positive
divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28
= 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers
496 and 8128.

def perfect_number(n):

sum = 0

for x in range(1, n):

if n % x == 0:

sum += x

return sum == n

print(perfect_number(6))

12. Write a Python function to create and print a list where the
values are the squares of numbers between 1 and 30 (both
included).
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196,
225, 256, 289, 324, 361, 400]

def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l)

printValues()

You might also like