Unit2 Python
Unit2 Python
FUNCTIONS
A function is a block of reusable code that performs a specific task. It helps
reduce code duplication and improves modularity.
DECLARING AND CALLING USER DEFINED FUNCTIONS
A user-defined function (UDF) is a function created by the user to perform
specific tasks in a program.
Unlike built-in functions provided by a programming language, udfs allow
for customization and code reusability, improving program structure and
efficiency.
Declaring and calling user-defined functions in Python involves two main steps:
defining the function and then invoking it.
1. Declaring (Defining) a User-Defined Function:
A function definition begins with the def keyword, followed by the function
name, a set of parentheses (), and a colon :.
Parameters, if any, are listed inside the parentheses.
The function body, containing the code to be executed when the function
is called, is indented below the def line.
An optional return statement can be used to send a value back to the
caller.
If return is omitted, the function implicitly returns None.
# function definition
def fun( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")
fun(2) # function calling
Output:
Hello Alice, welcome to Python!
1. Positional Parameters
• Arguments are matched to parameters by their position in the function call.
• Order matters.
EXAMPLE:
def student_info(name, age):
print(f"Name: {name}, Age: {age}")
student_info(“Andrew", 20) # Position: name → " Andrew ", age → 20
OUTPUT
Name: Andrew, Age: 20
2. Keyword Parameters
• Arguments are matched to parameters by name.
• Order does not matter when using keywords.
EXAMPLE:
def student_info(name, age):
print(f"name: {name}, age: {age}")
student_info(age=20, name=“Andrew")
OUTPUT
name: Andrew, age: 20
3. Default Parameters
• Parameters with a pre-defined value in the function definition.
• If no argument is provided, the default is used.
EXAMPLE:
def student_info(name, age=18):
print(f"Name: {name}, Age: {age}")
student_info(“bob") # Uses default age
student_info("John", 21) # Overrides default age
OUTPUT:
Name: bob, Age: 18
Name: John, Age: 21
4. Variable-length Parameters
Used when you don’t know the number of arguments in advance.
a) *args → non-keyword arguments
Collects extra positional arguments into a tuple.
EXAMPLE:
def display_numbers(*args):
print("Numbers:", args)
display_numbers(1, 2, 3, 4)
OUTPUT:
Numbers: (1, 2, 3, 4)
LAMBDA-FUNCTIONS AS OBJECTS
A lambda function is a small, anonymous function in python.
Created using the lambda keyword instead of def.
A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
EXAMPLE
square = lambda x: x * x
print(square(5))
OUTPUT
25
When the same program is rewritten using lambda function, it becomes more
elegant. This is done in program 34.
it is possible to use map() function on more than one list if the lists are of same
length. in this case, map() function takes the lists as arguments of the lambda
function and does the operation. for example,
map(lambda x, y: x*y, lst1, lst2)
here, lambda function has two arguments ‘x' and y'. hence, ‘x' represents ‘lst1' and
‘y’ represents ‘lst2’. since lambda is showing x*y, the respective elements from lst1
and lst2 are multiplied and the product is returned.
A Python program to find the products of elements of two different lists
using lambda function.
# Lambda that returns products of elements of two lists
lst1 = [1, 2, 3, 4, 5]
lst2 = [10, 20, 30, 40, 50]
lst3 = list(map(lambda x, y: x*y, lst1, lst2))
print(lst3)
Output:
[10, 40, 90, 160, 250]
STRINGS
A string is a sequence of characters.
Python treats anything inside quotes as a string.
This includes letters, numbers, and symbols. Python has no character data
type so single character is a string of length 1.
We can create a string in python by assigning a group of characters to a
variable
Creating a String
• Strings can be created using either single (') or double (") quotes.
A string is a sequence
• A string is a sequence of characters. You can access the characters one at a
time with the bracket operator:
• The expression in brackets is called an index. The index indicates which
character in the Sequence you want.
• But for computer scientists, the index is an offset from the beginning of the
string, and the offset of the first letter is zero.
example
>>>fruit = 'banana'
>>> letter = fruit[1]
>>>letter
‘a’ //output
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 11
example
>>> letter = fruit[0]
>>> letter
‘b’
example
As an index you can use an expression that contains variables and operators:
>>> i = 1
>>> fruit[i]
'a'
>>> fruit[i+1]
'n'
but the value of the index has to be an integer. otherwise you get:
>>> letter = fruit[1.5]
typeerror: string indices must be integers
len
len is a built-in function that returns the number of characters in a string:
>>> fruit = 'banana'
>>> len(fruit)
6
To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length]
Indexerror: string index out of range
The reason for the Indexerror is that there is no letter in 'banana' with the index 6.
since
we started counting at zero, the six letters are numbered 0 to 5. to get the last
character,
you have to subtract 1 from length:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 12
• This is the first example we have seen of a return statement inside a loop.
• If word[index] == Letter, the function breaks out of the loop and returns
immediately.
• If the character doesn’t appear in the string, the program exits the loop
normally and returns -1.
• This pattern of computation—traversing a sequence and returning when we
find what we Are looking for—is called a search.
Looping and counting
the following program counts the number of times the letter a appears in a
string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a’:
count = count + 1
print(count)
• this program demonstrates another pattern of computation called a counter.
the variable
• count is initialized to 0 and then incremented each time an a is found. when
the loop exits,
• count contains the result—the total number of a’s.
String methods
• strings provide methods that perform a variety of useful operations. a
method is similar to a function—it takes arguments and returns a value—but
the syntax is different.
• for example, the method upper takes a string and returns a new string with
all uppercase letters. instead of the function syntax upper(word), it uses the
method syntax [Link]().
>>> word = 'banana'
>>> new_word = [Link]()
>>> new_word
'BANANA'
• This form of dot notation specifies the name of the method, upper, and the
name of the String to apply the method to, word. the empty parentheses
indicate that this method takes no arguments.
• A method call is called an invocation; in this case, we would say that we
are invoking upper on word. as it turns out, there is a string method named
find that is remarkably similar to the function we wrote:
>>> word = 'banana'
>>> index = [Link]('a')
>>> index
1
In this example, we invoke find on word and pass the letter we are looking
for as a parameter.
Actually, the find method is more general than our function; it can find
substrings, not just characters:
>>> [Link]('na’)
2
By default, find starts at the beginning of the string, but it can take a second
argument, the index where it should start:
>>> [Link]('na', 3)
4
find() searches for the substring 'na' inside the string word
• the second argument 3 means start searching from index 3 (not from the
beginning).
• if it finds 'na', it returns the index of the first character of the match.
• if it doesn’t find it, it returns -1.
• this is an example of an optional argument; find can also take a third
argument, the index where it should stop:
>>> name = 'bob'
>>> [Link]('b', 1, 2)
-1
• this search fails because b does not appear in the index range from 1 to 2,
not including 2. searching up to, but not including, the second index makes
find consistent with the slice operator.
The in operator
The word in is a boolean operator that takes two strings and returns true if the
first appears as a substring in the second:
>>> 'a' in 'banana’
true
>>> 'seed' in 'banana’
false
String comparison
• the relational operators work on strings. to see if two strings are equal:
if word == 'banana’:
print('all right, bananas.')
• other relational operations are useful for putting words in alphabetical order:
if word < 'banana’:
print('your word, ' + word + ', comes before banana.')
elif word > 'banana’:
print('your word, ' + word + ', comes after banana.')
else:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 18
• Python does not handle uppercase and lowercase letters the same way
people do. All the Uppercase letters come before all the lowercase letters,
so:
Your word, pineapple, comes before banana.
• A common way to address this problem is to convert strings to a standard
format, such asAll lowercase, before performing the comparison. Keep that
in mind in case you have toDefend yourself against a man armed with a
pineapple.
indexing
Index represents the position number. Index is written using square braces []. by
specifying the position number through an index, we can refer to the individual
elements (or characters) of a string, starting from 0. we can access characters in a
string in two ways :
1. Accessing characters by positive index number
2. Accessing characters by negative index number (reverse order)
print(s[6])
# accessing the character of str at 10th index
print(s[10])
OUTPUT
c
y
n
Accessing by Negative Index Number
In this type of indexing, we pass the negative index(which we want to access) in
square brackets. Here the index number starts from index number -1 (which
denotes the last character of a string).
s = “core python!"
# accessing the character of str at 0th index
print(s[-1])
# accessing the character of str at 6th index
print(s[-5])
# accessing the character of str at 10th index
print(s[-10])
OUTPUT
n
y
o
SLICING
String slicing allows us to extract a part of the string. we can specify a start index,
end index, and step size. the general format for slicing is
string[start : end : step]
• start : we provide the starting index.
• end : we provide the end index(this is not included in substring).
• step : it is an optional argument that determines the increment between
each index for slicing.
str = ‘Core Python’
1)str[0:9:1]
Core Pyth
2) str[0:9:2]
Cr yh
3) str[::]
Core Python
4) str[2:4:1]
re
5) str[::2]
Cr yhn
6) str[2::]
re Python
7) str[:4:]
Core
8) str[-4:-1]
tho
9)str[-6: :]
Python
10)str[-1:-4:-1]
noh
11)str[-1::-1]
nohtyp eroC
12)str[-2:2:-1]
ohtyP e
LIST
A list is built-in data structure used to store different collection of items. Lists are:
• Ordered – the items have a defined order.
• Mutable- You can change, add or remove items.
• Indexed- Items can be accessed by their position(index).
• Allow duplicates- the same value can appear more than once.
A LIST IS A SEQUENCE
• Like a string, a list is a sequence of values. In a string, the values are
characters; in a list,They can be any type.
The values in a list are called elements or sometimes items.
• There are several ways to create a new list; the simplest is to enclose the
elements in square brackets ([ and ]):
• []
• [10, 20, 30, 40]
• [‘apple’, ‘orange’, ‘banana’]
• ['spam', 2.0, 5, [10, 20]]
• First example a list that contains no elements is called an empty list; you can
create one with empty brackets, [].The second example is a list of four
integers. the third list of three strings. the elements of a list don’t have to be
the same type. the fourth example list contains a string, a float, an integer,
and another list,a list within another list is nested.
Traversing a list
• the most common way to traverse the elements of a list is with a for loop.
the syntax is the same as for strings:
for cheese in cheeses:
print(cheese)
This works well if you only need to read the elements of the list. But if you want to
write or update the elements, you need the indices. A common way to do that is to
combine the built-in functions range and len:
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
This loop traverses the list and updates each element. len returns the number of
elements in the list. range returns a list of indices from 0 to n-1, where n is the
length of the list.
Each time through the loop i gets the index of the next element. The assignment
statement in the body uses i to read the old value of the element and to assign the
new value.
LIST OPERATIONS
• the + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
• the * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
the first example repeats [0] four times. the second example repeats the list [1, 2,
3] three times.
List slices
• the slice operator also works on lists:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f’]
>>> t[:]
['a', 'b', 'c', 'd', 'e', ‘f’]
if you omit the first index, the slice starts at the beginning. if you omit the second,
the slice goes to the end. so if you omit both, the slice is a copy of the whole list.
• since lists are mutable, it is often useful to make a copy before performing
operations that modify lists.
• a slice operator on the left side of an assignment can update multiple
elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> t
['a', 'x', 'y', 'd', 'e', ‘f’]
List methods
python provides methods that operate on lists. for example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> [Link]('d')
>>> t
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 25
filter()
• filters elements of a list based on a condition (true/false).
Example: keep only even numbers
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
Output
[2, 4, 6]
reduce()
repeatedly applies a function to the list elements and reduces them to a single
value. must import from functools:
Example: sum of all numbers
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)
Output
15
Deleting elements
There are several ways to delete elements from a list. If you know the index of the
element you want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = [Link](1)
>>> t
Output
['a', 'c']
>>> x
Output
'b’
• Pop modifies the list and returns the element that was removed.
• If you don’t provide an index, it deletes and returns the last element.
if you don’t need the removed value, you can use the del operator:
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> t
Output
['a', 'c’]
if you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>> [Link]('b')
>>> t
Output
['a', 'c']
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 28
to remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
Output
['a', 'f’]
Lists and strings
• A string is a sequence of characters and a list is a sequence of values, but a
list of characters is not the same as a string.
• To convert from a string to a list of characters, you can use list:
Example:
>>> s = 'spam'
>>> t = list(s)
>>> t
Output
['s', 'p', 'a', 'm']
• List is the name of a built-in function, you should avoid using it as a variable
name.
• Avoid l because it looks too much like 1.
• The list function breaks a string into individual letters. if you want to break a
string into words, you can use the split method:
Example:
>>> s = 'pining for the fjords'
>>> t = [Link]()
>>> t
Output:
['pining', 'for', 'the', 'fjords’]
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 29
• we know that a and b both refer to a string, but we don’t know whether they
refer to the same string.
• there are two possible states, shown in figure
• In one case, a and b refer to two different objects that have the same value.
• In the second case, they refer to the same object.
• To check whether two variables refer to the same object, you can use the is
operator.
Example:
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
Output:
true
• strings (immutable) → python often reuses the same object for identical
values.
• lists (mutable) → python always creates new objects, even if the contents
are the same.
• String interning in Python
• python optimizes memory by storing only one copy of some immutable
objects (like small strings, numbers, etc.).
• if two variables contain the same string literal, python may reuse the same
object in memory.
• In this example, python only created one string object, and both a and b
refer to it. But when you create two lists, you get two objects:
Example:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
Output:
False
• In this case we would say that the two lists are equivalent, because they
have the same elements, but not identical, because they are not the same
object.
• if two objects are identical, they are also equivalent, but if they are
equivalent, they are not necessarily identical.
• Until now, we have been using “object” and “value” interchangeably, but it is
more precise to say that an object has a value.
• If you evaluate [1, 2, 3], you get a list object whose value is a sequence of
integers.
• If another list has the same elements, we say it has the same value, but it is
not the same object.
Aliasing
• It refers to an object and you assign b = a, then both variables refer to the
same object:
Example:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
Output:
True
• The association of a variable with an object is called a reference. in this
example, there are two references to the same object.
• An object with more than one reference has more than one name, so we say
that the object is aliased.
• if the aliased object is mutable, changes made with one alias affect the
other:
>>> b[0] = 42
>>> a
[42, 2, 3]
• although this behavior can be useful, it is error-prone. in general, it is safer
to avoid
aliasing when you are working with mutable objects.
• for immutable objects like strings, aliasing is not as much of a problem. in
this example:
a = 'banana'
b = 'banana'
it almost never makes a difference whether a and b refer to the same string or not.
List arguments
when you pass a list to a function, the function gets a reference to the list. if the
function
modifies the list, the caller sees the change. for example, delete_head removes
the first
element from a list:
Example:
def delete_head(t):
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 33
del t[0]
here’s how it is used:
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> letters
['b', 'c']
the parameter t and the variable letters are aliases for the same object. the stack
diagram
looks like figure 10.5.
>>> t1 = [1, 2]
>>> t2 = [Link](3)
>>> t1
[1, 2, 3]
>>> t2
None
The return value from append is none.
[Link](3) adds 3 to t1.
But append() returns None, So t2 becomes None.
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 34
<class 'tuple'>
• A value in parentheses is not a tuple:
>>> t2 = ('a')
>>> type(t2)
<class 'str’>
• Another way to create a tuple is the built-in function tuple. with no argument,
it creates an empty tuple:
>>> t = tuple()
>>> t
()
If the argument is a sequence (string, list or tuple), the result is a tuple with the
elements of the sequence:
>>> t = tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', ‘s’)
• each character of the string becomes a separate element in the tuple.
• if you want the whole word "lupins" as one element, you should write:
• t = ('lupins',)
• print(t)
• Because tuple is the name of a built-in function, you should avoid using it as
a variable name.
• most list operators also work on tuples. the bracket operator indexes an
element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> t[0]
'a'
• The slice operator selects a range of elements.
>>> t[1:3]
('b', ‘c’)
• But if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'a'
typeerror: object doesn't support item assignment
• Because tuples are immutable, you can’t modify the elements. but you can
replace one tuple with another:
>>> t = ('a',) + t[1:]
>>> t
('a', 'b', 'c', 'd', 'e')
this statement makes a new tuple and then makes t refer to it.
• the relational operators work with tuples and other sequences; python starts
by comparing the first element from each sequence.
• if they are equal, it goes on to the next elements, and so on, until it finds
elements that differ. subsequent elements are not considered (even if they
are really big).
• 1st element same, moves further compares 2nd if finds true further will not be
moved.
>>> (0, 1, 2) < (0, 3, 4)
true
>>> (0, 1, 2000000) < (0, 3, 4)
true
Tuple assignment
• It is often useful to swap the values of two variables. with conventional
assignments, you have to use a temporary variable.
• For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 37
>>> t = divmod(7, 3)
>>> t
(2, 1)
zip pairs elements from two (or more) sequences. a zip object is a kind of
iterator, which is any object that iterates through a sequence.
If you want to use list operators and methods, you can use a zip object to make a
list:
EXAMPLE:
list(zip(s, t))
Output:
[('a', 0), ('b', 1), ('c', 2)]
If the sequences are not the same length, the result has the length of the shorter
one. Zip stops when the shortest sequence ends:
EXAMPLE:
list(zip('Anne', 'Elk’))
Output:
[('A', 'E'), ('n', 'l'), ('n', 'k')]
• you can use tuple assignment in a for loop to traverse a list of tuples:
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print(number, letter)
• each time through the loop, python selects the next tuple in the list and
assigns the elements
to letter and number. the output of this loop is:
OUTPUT
0a
1b
2c
DICTIONARY
• A dictionary is a built-in python data structure that stores data in key-value
pairs.
• It is like a real-life dictionary: a word (key) maps to its meaning (value).
Properties of Dictionary
• Stores data as key: value pairs.
• Keys must be unique.
• Keys must be immutable (string, number, tuple ).
• Dictionaries are unordered.
• Values can be any type (string, list, number, another dict, etc.).
In mathematical language, a dictionary represents a mapping from keys to
values, so you Can also say that each key “maps to” a value.
Creating An Empty Dictionary
student = dict()
print(student)
Output:
{}
Adding Items
student['one'] = “Alice”
print(student)
Output:
[Link] College of Commerce (Autonomous), Vijayapur BCA
Programme
UNIT2 FUNCTIONS 44
{'one': ‘Alice'}
Length:
len(student) # 3
>>> [Link]('a', 0)
1
>>> [Link]('c', 0)
0
FILES
• Till now, we were taking the input from the console and writing it back to the
console to interact with the user. Instead of that we can able use files as
input or output.
• File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.G. Hard disk).
• When we want to read from or write to a file we need to open it first. When
we are done, it needs to be closed, so that resources that are tied with the
file are freed.
• Hence, in python, a file operation takes place in the following order.
Open a file
Read or write (perform operation)
Close the file
OUTPUT
File content:
python program
Create file with named as [Link] , select file type as text file
WRITE MODE
# Open file in write mode
f = open("[Link]", "w")
# Write some data into the file
[Link]("Hello, this file is opened in write mode.\n")
[Link]("It will overwrite existing content.\n")
# Close the file
[Link]()
print("Data written successfully in write mode.")
OUTPUT
Data written successfully in write mode
• If the file does not exist, it will be created.
• If the file already exists, the old content will be erased/overwritten.
APPEND MODE
# Open file in append mode
f = open("[Link]", "a")
# Append some data
[Link]("This line is added using append mode.\n")
# Close the file
[Link]()
print("Data appended successfully.")
OUTPUT
Data appended successfully
CLOSING FILE
In python, after finishing file operations, we should close the file to
free up system resources.
It ensures all data is written (flushed) from memory to the file.
It frees the file object and resources.
DELETING FILE
import os
# File name
filename = "[Link]"
# Check if file exists before deleting
if [Link](filename):
[Link](filename)
print(f"{filename} deleted successfully.")
else:
OUTPUT:
[Link] deleted successfully
[Link]() checks if the file is present.
[Link]() deletes the file.
if you try to delete a file that doesn’t exist, python will throw an
error → that’s why checking is useful.