UNIT 3 & 4 - Merged Pps
UNIT 3 & 4 - Merged Pps
Unit 3
1) Define a function . Explain function definition and function call with suitable example.
2) What are the good Python programming practices?
3) Explain the following types of function arguments with examples:
i) Required arguments ii) Keyword arguments iii)Variable length argument iv)default
argument
Solution
6) Insert blank lines to separate functions which are written inside a program.
1)Function blocks begin with the keyword def followed by the function name and parentheses(())
3)The code block within every function starts with a colon (:) and is indented.
Function definition
Function Call:
Example:
def msg():
msg()
Q.3) Expain local and global variables with respect to scope and lifetime with suitable
example
• Local Variable:
local variables can be accessed only inside the function in which they are declared.
Example
def sum(x,y):
sum= x + y
return sum
print(sum(10,20))
• Global Variable:
Global variable is any variable created outside a function can be accessed within any
function.
Example:
x=5
y = 10
def sum():
sum = x + y
return sum
print(sum())
Output:
15
The number of arguments in the function call should match exactly with the function definition.
Example:
return
my_details(“Ninad",20)
Output:
Name: Ninad
Age: 20
2)Keyword Arguments:
When we use keyword arguments in a function call, the caller identifies the arguments by the
parameter name.
Example:
return
Output:
Name: Aavnish
Age: 20
3) Variable-length arguments:
• In some situations, it is not known in advance how many arguments will be passed to a
function.
• In such cases, Python allows programmers to make function calls with arbitrary (or any)
number of arguments.
• When we use arbitrary arguments or variable length arguments, then the function
definition use an asterisk (*) before the parameter name.
4) default Arguments:
Output:
Name: Abhinav
Age: 20
Declaring Docstrings:
The docstrings are declared using ”’triple single quotes”’ or “”” triple double quotes
“”” just below the class, method, or function declaration. All functions should have a docstring.
Accessing Docstrings:
The docstrings can be accessed using the __doc__ method of the object or using the help
function.
• Example
def square(n):
return n**2
print(square.__doc__)
• Output
Create a Module
• To create a module just save the code you want in a file with the file extension ”.py”
• Example.-Mod1.py
def My_details(name):
print("Hello," + name)
Use a Module
• Now we can use the module we just created, by using the “import” statement:
import Mod1
Mod1. My_details(“vandana")
Package:
• A packages is a hierarchical file directory structure that has modules and other packages
within it.
• Package is nothing but folders/directory.
Creating Package:
• with the help of IDLE create two modules mod1 and mod2 in this folder.
1. “import” statement:
we can use the module we just created, by using the “import” statement:
• Example.-Mod1.py
def My_details(name):
print("Hello," + name)
Use a Module
• Now we can use the module we just created, by using the “import” statement:
import Mod1
Mod1. My_details(“vandana")
When you import a module, you can use any variable or function defined in that module.
But if you want to use only selected variables or functions, then you can use the from...import
statement
• Example:
Mod2.py
def sum(a,b):
return a+b
def avg(a,b):
return(a+b)/2
def power(a,b):
return a**b
Mod2.sum(10,20)
o/p:
30
Q.6) Write a python program to check whether a number is prime or not using a function.?
def prime(number):
if number > 1:
if (number % i) == 0:
break
else:
else:
prime(7)
Q7) Write a python program using lambda function to find whether number is even or
odd.?
print(even_odd())
sqr=lambda : no**2
print(sqr())
Q.9) Write a python program to check whether a year is leap year or not using user defined
function.
def leap(year):
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
leap(year)
UNIT 4
String
Q.1) Explain following string methods with example :
1) split
2)Rindex
3)Zfill
4)ljust
5)find
6)join
7)lstrip
Q.2) Explain following string operations with example: 1)concateation 2)appending 3)string
repetition
Q.3) Explain indexing and slicing operation on string with suitable example.
Q.6) Write a python program to display reverse string without using slicing operator.
Q.8) Write a python program that counts occurences of characters in a string. Do not use built in
methods.
Q.9) Write a python program to check whether a given string starts with specified character.?
Q.10) Write a python program to find whether a given character is present in a string or not. In
case it is present print the index at which it is present. Do not use built in method.?
Solution
1) split :
The split() method splits a string into a list by specify the separator, default separator is
any whitespace.
s = "python-programming-Language"
print(s.split('-'))
o/p:
The rindex() method finds the last occurrence of the specified value.
Example:
print(s.rindex('o'))
O/p:
12
The zfill() method adds zeros (0) at the beginning of the string, until it reaches the
specified length.
Example-
s = '123'
print(s.zfill(5))
o/p:
00123
4)ljust:
Left Justification:
The rjust() method will right align the string, using a specified character (space is
default) as the fill character.
Syntax:
string.rjust(length, character)
Example:
s = "hello"
print(s.rjust(10,'*'))
O/p:
*****hello
4) find():
It takes an argument and searches for it in the string on which it is applied. It then
returns the index of the substring.
If the string doesn’t exist in the main string, then the index it returns is -1.
Example:
s = "Python Programming"
print(s.find('Py'))
print(s.find("Java"))
o/p:
-1
5)join():
Example:
s= "python","programming","is","very","interesting"
seprator=' '
print(seprator.join(s))
o/p:
6)lstrip():
Example:
print(str.strip())
O/p:
Python
1)Concatination:
str="Python"
str1="Programming"
str2="!!"
print(str3)
o/p:
Python Programming..!!
2)appending:
Example:
s="Py"
s=s+"thon
print(s)
o/p:
Python
3)repetition():
Example:
print(str*3)
Output :
Welcome to Python...
Welcome to Python...
Welcome to Python...
Q.3) Explain indexing and slicing operation on string with suitable example.
String indexing:
• Indexing is the process of accessing an element in a sequence using its position in the
sequence (its index).
• In Python, indexing starts from 0, which means the first element in a sequence is at
position 0, the second element is at position 1, and so on.
• To access an element in a sequence, we use square brackets [] with the index of the
element we want to access.
Example:
• my_list = ['apple', 'banana', 'cherry']
print(my_list[0])
output: 'apple'
print(my_list[1])
output: 'banana'
String Slicing :
• Slicing is used to extract a part of any string based on a start index and end index.
• In slicing colon : is used. An integer value will appear on either side of colon.
Syntax :
Example:
str="Python Programming is very interesting"
O/p:
Example:
s="Python"
id(s)
o/p:
2375308936240
s="Java"
id(s)
o/p:
2375312788528
String formatting is the process of infusing(fill) things in the string dynamically and presenting
the string.
Ex-
name= "ABC"
age= 8
• The Format() formats the specified values and insert them inside the string placeholder.
The placeholder define using curly bracket {}.
• It has the variables as arguments separated by commas. In the string, use curly braces to
position the variables.
Example
print("Welcome to {}".format("Python"))
o/p:
Welcome to Python
The string itself can be formatted in much the same way as str.format().
Example:
name="Avnit"
o/p:
My name is Avnit
Q.6) Write a python program to display reverse string without using slicing operator.
rev=reversed(s)
for txt in rev:
print(txt,end="")
Output-
nohtyp ot emoclew
if s==s[ : :-1]:
else:
Output-
Q.8) Write a python program that counts occurences of characters in a string. Do not use
built in methods.
count=0
for tx in s:
if tx=='e':
count=count+1
Q.9) Write a python program to check whether a given string starts with specified
character.?
s=input("Enter string")
sw=input("Enter string to check starts with")
if (s.startswith(sw)):
else:
O/p:
Q.10) Write a python program to find whether a given character is present in a string or
not. In case it is present print the index at which it is present. Do not use built in method.?
s=input("Enter string")
if ch in s:
else:
index=0
for x in s:
if x==ch:
index= index+1
O/p:
Index of character 3
Unit 5:
Q.1) Explain following concepts with example: 1)object variable 2)class variable
1. Object Variable:
1. Object variables or instance variables are the variables that are unique to each object of a
class.
class_var=0
def __init__(self,x):
obj1=abc(10)
2. Class Variable:
1. Class variables are variables that are shared by all the objects of a class.
2. They are defined inside the class definition, but outside of any method.
3. To access the class variable, we can either use the class name or object name of that class.
e.g
class_var=0
def __init__(self,x):
abc.class_var+=1
obj1=abc(10)
Advantages:
Disavantages:
1.Its problem is there can be lot of repetition of coe when same operation has to be done
many times.
2. No security to data.
2. Structured:
3. Here program is written in a structured format compulsarily and each task has separate
function. e.g. C and pascal.
Advantages:
1. No duplication of data
2. We can pass data to other function and take data from other function.
Disadvantages:
2. No security to data.
Advatages:
2. Some functions can be used multiple times in one program whenever the operation is needed.
Disadvatages:
1. No security to data.
Public Variables:
1. A public member is accessible from anywhere outside the class but within a program.
2. The members of a class that are declared public are easily accessible from any part of the
program.
3. All data members and member functions of a class are public by default.
Example:
class encap:
def display(self):
obj=encap()
print(obj.a)
obj.display()
Private Variables:
1. A private member variable or function cannot be accessed, or even viewed from outside the
class. Only the class and friend functions can access private members.
2. The members of a class that are declared private are accessible within the class only, private
access modifier is the most secure access modifier.
3. Data members of a class are declared private by adding a double underscore ‘__’ symbol
before the data member of that class.
Example:
class abc:
__year= 2018;
def __privateMethod(self):
def display(self):
self.__privateMethod()
obj = abc()
obj.display()
1. Containership:
1. In Containership, when an object of one class is created in to another class then that object will
be a member of that class, this type of relationship between the classes is known as containership
or has-a relationship as one class contains the object of another class.
class component:
def __init__(self):
print("component class")
def m1(self):
class composite:
def __init__(self):
self.obj1=component()
print("Composite class")
def m2(self):
print("m2()method executed")
self.obj1.m1()
obj2=composite()
obj2.m2()
2. Reusablility:
2. It means developing codes that can be reused either in the same program or in different
programs.
3. Data Encapsulation:
1. The technique of packing data and function into single component to hide implementation
details of a class from user.
3. There are three access specifiers which will specify the access level of data variable and
member function: public, protected and private.
lass encap():
a=10 #public
_b=30 #protected
__c=20 #orivate
def display(self):
def _display(self):
def __display(self):
obj=encap()
print(obj.a)
obj.display()
4. Data Abstraction:
1. It hides complex implentation details while exposing only essential information and
functionalities to users.
2. In python, we can achieve data abstraction by using abstract classes and abstract classes can
be created using abc module and abstractmethod of abc module.
class sample(ABC):
@abstractmethod
def ac_details(self):
pass
class demo(sample):
def ac_details(self):
c=demo()
c.ac_details()
5. Polymorphism:
2. In programming, it refers to methods/functions with same name that can be executed on many
objects.
6. Delegation:
1. Delegation is a design pattern in which an object, called the delegate, is responsible for
performing certain task on behalf of another object, called the delegator.
class A:
print(len("python"))
#len() used for list
class A:
def m1(self,x):
pass
def m2(self):
pass
class B:
def __init__(self):
self.a=A()
def m1(seld,x):
return self.a.m1(x)
def m2(self):
return self.a.m2()
Q.5)Write a python program to create a class student with attributes name,roll no,and age.
Display the details of four students.
lass student:
def __init__(self,name,roll_no,age):
self.name=name
self.roll_no=roll_no
self.age=age
def display(self):
obj1=student(""Ninad"",101,20)
obj1.display()
obj2=student(""Abhinav"",102,20)
obj2.display()
obj3=student(""john"",103,19)
obj3.display()
obj4=student(""avnit"",104,20)
class Circle():
self.radius = r
def area(self):
return self.radius**2*3.14
NewCircle = Circle(8)
print(NewCircle.area())
Q.7) Write a python program to create a class Employee with two attributes . Display the
details of two emploees.
class employee:
def __init__(self,n,salary):
self.name=n
self.sal=salary
def display(self):
obj1=employee(""ninad"",10000)
obj1.display()
obj2=employee(""Abhinav"",20000)
obj2.display()
Q.8) Write a python program to create class car with two attributes name and cost. Create
two objects and display information.
class car:
def __init__(self,name,cost):
self.name=name
self.cost=cost
def display(self):
obj1=car(""i20"",100000)
obj1.display()
obj2=car(""i10"",200000)
obj2.display()
Unit 6
1 Why do we need files? Explain relative and absolute path in files
A file is a collection of data stored on a secondary storage device like hard disks,
pen-drives, DVD or CDs. Files are essential components of computing systems
used to store and organize data in a structured manner.
Writing in file:
1. Fileobj.write(String)f.write(string)
2. Fileobj.writelines()f.writelines(list of lines)
Ex- write()
f=open("Sample.txt",“w")
f.write("Hello")
f.close()
2) writelines()
f=open("Sample.txt","w")
l=["Hello\n","how\n","are\n","you?"]
f.writelines(l)
f.close()
3. read()
. f.read()-> To read total data
Ex-
f=open("Sample.txt")
a=f.read()
print(a)
Following file opening modes are used for handling text files.
1) "r" : read
• It is a read mode. Here file is opened for reading ONLY.
• Here file reference points to start of the file.
• If the specified file does not exist then we will get FileNotFoundError
2) "w" : write
• Open an existing file for write operation.
• If the file already contains some data then it will be overwrites.
• If the specified file is not already available then this mode will create
that file.
3) "a" :append
• Open an existing file for append operation.
• It does not overwrite existing data.
• If the specified file is not available then this mode will create a new file
4) "r+":read+write
• This mode allows reading and writing. Here also reference is placed at
start of the file. Previous data in file will not be deleted.
5) "w+":write+read
• This mode allows both writing and reading.
• It will overwrite existing data.
6) "a+": append+read
• Here appending and reading both are allowed.
• Don’t overwrite existing data.
• File reference is always at end of the file.
7) "x": Exclusive creation mode
• To open file in exclusive creation mode for write operation.
• If file already exist then we will get FileExistError.
Ex-
dic={1:"abc",2:"XYZ"}
a=dic.copy()
a={1: 'abc', 2: 'XYZ’}
Ex- k=(1,2,3)
v=0
di=dict.fromkeys(k,v)
di={1: 0, 2: 0, 3: 0}
Ex-a={1:"One",2:"Two"}
a.items()
dict_items([(1, 'One'), (2, 'Two’)])
Ex-a.pop(1)
'One’
Ex- a.popitem()
(2, 'Two')
Ex- a.setdefault(4,"Four")
'Four’
Ex- a.update({4:"Fourrrrr"})
7 Write a python program that reads data from one file and write into
another file such that small leters converted to capital letter and vice versa.
8 Write a python program that reads data from one file and write into
another file in reverse.