[Go to site: main page, start]

0% found this document useful (0 votes)
2 views49 pages

User Defined Functions and Data Structures

The document provides an overview of user-defined functions in programming, including their definition, calling, and types. It also covers lists, tuples, and dictionaries, explaining their characteristics, operations, and how they can be utilized in functions. Additionally, it briefly discusses file operations and types of files.

Uploaded by

sw3yyy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views49 pages

User Defined Functions and Data Structures

The document provides an overview of user-defined functions in programming, including their definition, calling, and types. It also covers lists, tuples, and dictionaries, explaining their characteristics, operations, and how they can be utilized in functions. Additionally, it briefly discusses file operations and types of files.

Uploaded by

sw3yyy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

functions

User Defined Functions:


User defined functions are the functions that programmers create for
their requirement and use.
• These functions can then be combined to form module whichcan be
used in other programs by importing them.
• Programmers working on large project can divide the workload
bymaking different functions.
• If repeated code occurs in a program, function can be used to
include those codes and execute when needed by calling that
function.
Function definition
• def keyword is used to define a function.
• Give the function name after def keyword followed by parentheses in
which arguments are given
. • End with colon (:)
• Inside the function add the program statements to be executed
• End with or without return statement
Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2… statement n
return[expression]

def my_add(a,b):
c=a+b
return c
• Function Calling:
• 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
arguments
• x=5
• y=4
• my_add(x,y)
Function Prototypes:
Function without arguments and without return type
Function with arguments and without return type
Function without arguments and with return type
Function with arguments and with return type
• Function without arguments and without return type o
• In this type no argument is passed through the function call and no
output is return to main function
• o The sub function will read the input values perform the operation and
print the result in the same block
• def add():
• a=int(input("enter a”)
• b=int(input("enter b”)
• c=a+b
• print(c)
• add()
Function with arguments and without return type
o Arguments are passed through the function call but output is not
return to the main function.
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)
• Function without arguments and with return type o
• In this type no argument is passed through the function call but
output is return to the main function.
• def add():
• a=int(input("enter a"))
• b=int(input("enterb"))
• c=a+b
• return c
• c=add()
• Print(c)
• Parameters:
• Parameters are the value(s) provided in the parenthesis
• These are the values required by function to work. when we write function
header.
• If there is more than one value required, all of them will be listed in
parameter list separated by comma.
• Example: defmy_add(a,b):
Arguments :
• Arguments are the value(s) provided in function call/invoke statement.
• List of arguments should be supplied in same way as parameters are
listed.
• Bounding of parameters to arguments is done 1:1, and so there should be
same number and type of arguments as mentioned in parameter list.
• Example:my_add(x,y)
• RETURN STATEMENT:
• The return statement is used to exit a function and go back to the
place from where it was called.
• If the return statement has no arguments, then it will not return any
values. But exits from function.
Syntax:
return[expression]
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
• LIST
• List is a sequence of values, which can be of different types.
• The values in list are called "elements" or ''items‘’
• o Each elements in list is assigned a number called "position" or "index“
• o A list that contains no elements is called an empty list. They are created
with empty brackets[]
• o A list within another list is nested list
• LIST OPERATIONS:
• [Link] of list
• [Link] of list
Concatenation: the '+' operator concatenate list
>>> a =[1,2,3]
>>> b =[4,5,6]
>>> c = a+b
• Repetition: the '*' operator repeats a list a given number of times
>>> a = [1,2,3]
• >>> b = [4,5,6]
• >>> print (a*2)= [1,2,3,1,2,3]
• . List looping: (traversing a list) 1
• . Looping in a list is used to access every element in list 2."for loop"
is used to traverse the elements in list
• eg: mylist = ["python","problem",100,6.28]
• for i in range (len (mylist)):
• print (mylist [i])
• .List Slices:
• A subset of elements of list is called a slice of list.
• Eq: n = [1,2,3,4,5,6,7,8,9,10]
• print (n[2:5])
• print (n[-5])
• print (n[5: ])
• print (n[ : ])
Aliasing and cloning:
•when more than one variables refers to the same objects or list,
then it is called aliasing.
a= [5,10,50,100]
b=a b[0] = 80
print ("original list", a) = [5,10,50,100]
print ("Aliasing list", b) = [80,5,10,50,100]
•Here both a & b refers to the same list. Thus, any change made
with one object will affect other, since they are mutable objects.
•in general, it is safer to avoid aliasing when we are working with
mutable objects
• Cloning: •Cloning creates a new list with same values under another
name.
• Taking any slice of list create new list.
•Any change made with one object will not affect others. the easiest
way to clone a new list is to use "slice operators“
a = [5,10,50,100]
b= a[ : ]
b[0] = 80
Print (" original list", a) = [5,10,50,100]
Print (" cloning list", b) = [5,10,50,100]
• List parameter:
• •List can be passed as arguments to functions the list arguments are
always passed by reference only.
• •Hence, if the functions modifies the list the caller also changes.
• Eq: def head ():
• del t[ 0 ]
• >>> letters = ['a','b','c’]
• >>> head (letters)
• >>> letters ['b','c’]
the parameters 't' and the variable 'letters' or aliases for the same
objects
• TUPLES:
• A tuple is a sequence of value which can be of any type and they are indexed
by integers.
• Values in tuple are enclosed in parentheses and separated by comma. The
elements in the tuple cannot be modified as in list
• tuple are immutable objects
• Creating tuple: Tuple can be created by enclosing the element in
parentheses separated by comma t = ('a','b','c','d’)
• To create a tuple with a single element we have to include a final comma
• >>> t = 'a’,
• >>> type (t)
• < class 'tuple’>
• Alternative way to create a tuple is the built-in function tuple which mean, it
creates an empty tuple
• >>> t = tuple ()
• Accessing element in tuple: If the argument in sequence, the result is a
tuple with the elements of sequence.
• >>>t= tuple('python’)
• >>> t ('p','y','t','h','o','n’)
• t = ('a','b',100,8.02)
• print (t[0]) = 'a’
• print (t[1:3]) = ('b', 100 , 8.02)
Deleting and updating tuple:
Tuple are immutable, hence the elements in tuple cannot be updated /
modified
But we can delete the entire tuple by using keyword 'del’
a = ('a','b','c','d')
del (a) :-------- delete entire tuple
del a [1] <--------- error,deleting one element in tuple not possible
• replacing one tuple with another
• a = ('a','b','c','d')
• t = ('A',) + a[1: ]
• print (t) <------ ('a','b','c','d')
Tuple Assignment:
•Tuple assignment is often useful to swap any number of values
•the number of variables in left and right of assignment operators must
be equal
•A single assignment to paralleling assign value to all elements of tuple
is the major benefit of tuple assignment
• Tuple swapping in python
• A= 100
• B= 345
• C= 450
• print (" A & B:", A,"&",B)
• # Tuple assignments for two
• variables A,B = B,A
• print (" A&B after tuple assignment : ",A,"&",B)
• # Tuple assignment can be done for no of
• variables A,B,C = C,A,B
• print (" Tuple assignment for more variables:",
• A,"&",B,"&",C) Output
• A & B: 100 & 345
• A&B after tuple assignment : 345 & 100
• Tuple assignment for more variables: 450 & 345 & 100
Tuple as return value:
• •Generally, function can only return one value but if the value is tuple
the same as returning the
• multiple value
• •Function can return tuple as return value
• Eg: # the value of quotient & remainder are returned as tuple
• def mod_div
• (x,y): quotient
• = x/y remainder
• = x%y
• Dictionary
• A dictionary is an unordered set of key: value pair. In a list, the indices
have to be integers; in a dictionary they can be any type.
• A dictionary contains a collection of indices, which are called keys, and
a collection of values.
• Each key is associated with a single value. The association of a key and
a value is called a key-value pair. Dictionary is created by enclosing with
curly braces {}
• dictionary={"RollNo":101,2:(1,2,3),"Name":"Ramesh",20:20.50,Loc":['Ch
ennai']}
• >>> dictionary
• {'Name':'Ramesh', 'Loc':['Chennai'], 2:(1,2.3), 20: 20.0, 'RollNo': 101}
FILE AND ITS OPERATION
• File is a collection of record.
• A file stores related data, information, settings or commands in
secondary storage device like magnetic disk, magnetic tape, optical
disk, flash memory.
File Type
1. Text file
2. Binary file

You might also like