Python Functions
Python Functions
Syntax of a function
def function_name(parameters):
statement(s)
Once we have defined a function, we can call it from another function, program or even the Python
prompt. To call a function we simply type the function name with appropriate parameters.
my_function() #call
Arguments
def my_function(fname):
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments
By default, a function must be called with the correct number of arguments. That means if a
function expects 2 arguments, it has to be called with 2 arguments, not more, and not less.
Example : Function with two arguments:
my_function("Emil", "Refsnes")
my_function("Emil")
The above program when run gives an error indicating mismatch in the number of arguments
passed.
If the number of arguments passed into a function is unknown, a * is added before the parameter
name in the function definition. This way the function will receive a tuple of arguments, and can
access the items accordingly:
def my_function(*kids):
The function my_function in the above example is called with 3 arguments and 4 arguments
(Arguments of variable length) .
Keyword arguments
Arguments with the key = value syntax is also allowed in python. This way the order of the
arguments does not matter.
If the number of keyword arguments that will be passed into the function is not known, add two
asterisk: ** before the parameter name in the function definition.
def my_function(**kid):
If we call the function without argument, it uses the default value. The default value has to be
specified in the function definition.
my_function("Sweden")
my_function("India")
my_function("Brazil")
Any data type can be sent as an argument to a function (string, number, list, dictionary etc.), and it
will be treated as the same data type inside the function.
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Return values
def my_function(x):
return 5 * x
print(my_function(3)) #15
print(my_function(5)) #25
print(my_function(9)) #45
Programs on functions
1. Write a python function that accepts a string and checks of it is a palindrome or not.
def palindrome(str):
if str == str[::-1]:
else:
palindrome('racecar')
palindrome('palindrome')
2. Write a python function that accepts a list and returns a new list of unique elements only.
unique_list = set(l)
unique_list = list(unique_list)
print (unique_list)
unique ([1,1,1,2,3,2])
3. Using a function calculate the number of upper case and lower case letters in string.
def upperlowercount(string):
u=0
l=0
for i in string:
if i.isupper():
u+=1
if i.islower():
l+=1
upperlowercount("STring")
a=0
for i in string2:
if i == 'A':
a+=1
occur_A("AbcAd")
5. Calculate the average marks of 3 students. Student 1 has taken 2 subjects, Student 2 has taken 5
subjects and Student 3 has taken 3 subjects.
def avgMarks(*marks):
s=0
for i in marks:
s += i
print (s/len(marks))
avgMarks(30,40) # Student 1
avgMarks(30,40,40,30,40) # Student 2
avgMarks(30,40,40) # Student 3
6. Accept user input to take in the values for name, company and location. If the user does not enter
a location default it with the value "Bangalore"
def info(name,company,location="Bangalore"):
print (name,company,location)
n = input("name ")
c = input("company ")
if q == 1:
info (n,c)
if q== 2:
info (n,c,loc)
7. Write a python program to accept user's first name middle name and last name. The user may or
may not enter all the names. Print them from within the function.
def names(**kwargs):
8. Using functions Calculate area of circle if 1 parameter is passed. Calculate area of rectangle if 2
parameter are passed.
def area(*args):
if len(args) == 1:
if len (args) == 2:
area(2,3)
area(3)