0% found this document useful (0 votes)
8 views38 pages

UNIT 3 & 4 - Merged Pps

The document contains a series of questions and answers related to Python programming, covering topics such as function definitions, good programming practices, types of function arguments, documentation strings, user-defined modules, and string methods. It includes examples of Python code for checking prime numbers, determining even or odd numbers, and checking leap years, among other tasks. Additionally, it discusses string operations, immutability, and formatting techniques in Python.

Uploaded by

kaisel12309
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)
8 views38 pages

UNIT 3 & 4 - Merged Pps

The document contains a series of questions and answers related to Python programming, covering topics such as function definitions, good programming practices, types of function arguments, documentation strings, user-defined modules, and string methods. It includes examples of Python code for checking prime numbers, determining even or odd numbers, and checking leap years, among other tasks. Additionally, it discusses string operations, immutability, and formatting techniques in Python.

Uploaded by

kaisel12309
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
You are on page 1/ 38

IMP Question:

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

4)What is documentation string in python ? Explain with suitable example.

5)Write a short note on user defined modules and packages in python

6) Explain different ways of importing modules in python


7)Write a python program to check whether a number is prime or not using a
function.
8)Write a python program using lambda function to find whether number is
even or odd.
9)Write a program to find square of a number using lambda function
10)Write a python program to check whether a year is leap year or not using
user defined function.

Solution

1)What are the good Python programming practices?

1) Use meaningful variable names in a program.

2) Use lowercase letters to write name of the name of a functions.

3) Instead of using 8 white space indentation use 4 space indentation.

4) Write comments in program to make program code more understandable.

5) Use spaces around operators like +,- , *, / etc.

6) Insert blank lines to separate functions which are written inside a program.

7) Use Documentation string to explain more about function written in a code.


Q.2)Define a function . Explain function definition and function call with suitable example.

1)Function blocks begin with the keyword def followed by the function name and parentheses(())

2) Any input parameters or arguments should be placed within these parentheses.

3)The code block within every function starts with a colon (:) and is indented.

4)The statement return [expression] exits a function .

Function definition

def - keyword used to declare a function

function_name - any name given to the function

parameters - any value passed to function

return (Optional) - returns value from a function

Function Call:

To use function, we need to call it.

To call a function, use the function name followed by parenthesis

Example:

def msg():

print(“Hello, Welcome to Python”)

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

Q.4) Explain the following types of function arguments with examples:


i) Required arguments
ii) Keyword arguments
iii)Variable length argument
iv)default argument
1)Required arguments:

The number of arguments in the function call should match exactly with the function definition.

Example:

def my_details( name, age ):

print("Name: ", name)

print("Age: ", age)

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:

def my_details( name, age ):

print ("Name: ", name)

print ("Age ", age)

return

my_details( age=20, name=“Aavnish “)

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:

 If we call the function without argument, it uses the default value


 A default argument is an argument that assumes a default value
Example:
def my_details( name, age=20 ):
print("Name: ", name)
print("Age:", age)
return
my_details(name=“Abhinav")

Output:
Name: Abhinav
Age: 20

Q.5) What is documentation string in python ? Explain with suitable example.?

1) When it comes to writing clean, well-documented code, Python developers use


docstrings.
2) Python docstrings are the string literals that appear right after the definition of a function,
method, class, or module.

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):

'''Takes in a number n, returns the sqaure of n'''

return n**2

print(square.__doc__)

• Output

Takes in a number n, returns the sqaure of n

Q.6)Write a short note on user defined modules and packages in python?

• A Python module is a file containing Python definitions and statements.

• A module can define functions, classes, and variables.

• A module can also include runnable code.

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.

• Package contain sub packages, modules and sub modules.

Creating Package:

• Create a folder named mypckg.

• Inside this folder create an empty Python file i.e. __init__.py

• with the help of IDLE create two modules mod1 and mod2 in this folder.

Q.7) Explain different ways of importing modules in python?

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")

2. from import statement:

A module may contain definition for many variables and functions.

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

from mypckg import Mod2

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):

# prime number is always greater than 1

if number > 1:

for i in range(2, number):

if (number % i) == 0:

print(number, "is not a prime number")

break

else:

print(number, "is a prime number")

# if the entered number is less than or equal to 1

# then it is not prime number

else:

print(number, "is not a prime number")

prime(7)
Q7) Write a python program using lambda function to find whether number is even or
odd.?

number = int(input("Enter a number "))

even_odd = lambda : "Even Number" if number % 2 == 0 else "Odd Number"

print(even_odd())

Q8) Write a program to find square of a number using lambda function

no=int(input("Enter a number "))

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.

# Python program to check if year is a leap year or not

year = int(input("Enter a year: "))

def leap(year):

# divided by 100 means century year (ending with 00)

# century year divided by 400 is leap year

if (year % 400 == 0) and (year % 100 == 0):

print("{0} is a leap year".format(year))

# not divided by 100 means not a century year

# year divided by 4 is a leap year

elif (year % 4 ==0) and (year % 100 != 0):

print("{0} is a leap year".format(year))

# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year

else:

print("{0} is not a leap year".format(year))

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.4) Justify strings are immutable with example?

Q.5) Explain string format operators with suitable example.

Q.6) Write a python program to display reverse string without using slicing operator.

Q.7) Write a program to check whether a string is palindrome or not.?

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

Q.1) Explain following string methods with example :


1) split
2)Rindex
3)Zfill
4)ljust
5)find
6)join
7)lstrip

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:

['python', 'programming', 'Language']

2) rindex: (right index)

The rindex() method finds the last occurrence of the specified value.

The rindex() method raises an exception if the value is not found.

Example:

s = "Python is programming language"

print(s.rindex('o'))

O/p:

12

3)zfill(): (zero fill)

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():

It is opposite of split method. It Join list of string using specific sepretor

Example:

s= "python","programming","is","very","interesting"

seprator=' '

print(seprator.join(s))

o/p:

python programming is very interesting

6)lstrip():

Remove spaces to the left of the string:

Example:

str=" Python "

print(str.strip())

O/p:

Python

Q.2) Explain following string operations with example: 1)concateation 2)appending


3)string repetition

1)Concatination:

• The word concatenate means to join together.

• Concatenation is the operation of joining two strings together.

• Python Strings can join using the concatenation operator +.


Example:

str="Python"

str1="Programming"

str2="!!"

str3= str+" "+str1+".."+str2

print(str3)

o/p:

Python Programming..!!

2)appending:

Append means to add something at the end.

"append" adds another string to existing string.

Example:

s="Py"

s=s+"thon

print(s)

o/p:

Python

3)repetition():

• To write the same text multiple times, multiplication or repetition is used.

• Multiplication can be done using operator *.

Example:

str= “Welcome to Python..."

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 :

• A substring of a string is called slice.

• Slicing is a string operation.

• Slicing is used to extract a part of any string based on a start index and end index.

• The extracted portions of Python strings called substrings.

• In slicing colon : is used. An integer value will appear on either side of colon.

Syntax :

string_name[start_index : stop_index: step__index]

Example:
str="Python Programming is very interesting"

print("Characters from 3rd to 6 :",str[2:6])

print("Characters from 1st to 6 :",str[0:6])

O/p:

Characters from 3rd to 6 : thon

Characters from 1st to 6 : Python

Q.4) Justify strings are immutable with example?

• Immutable- Non Changeable.

• Whenever we try to modify an existing string variable, a new string is created.

Example:

s="Python"

id(s)

o/p:

2375308936240

s="Java"

id(s)

o/p:

2375312788528

Q.5) Explain string format operators with suitable example.?

String formatting is the process of infusing(fill) things in the string dynamically and presenting
the string.

Formatting with % Operator.

• The string Formatting Operator

• The syntax for the string formatting operator is.


"<Format>" %(<Values>)

Ex-

name= "ABC"

age= 8

print("Name=%s and Age=%d"%(name, age))

Formatting with format() string method.

• 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

Formatting with string literals, called f-strings.

To create an f-string, prefix the string with the letter “ f ”.

The string itself can be formatted in much the same way as str.format().

Example:

name="Avnit"

print(f"My name is {name}")

o/p:

My name is Avnit

Q.6) Write a python program to display reverse string without using slicing operator.

s= input("Enter a string: ")

rev=reversed(s)
for txt in rev:

print(txt,end="")

Output-

Enter a string: welcome to python

nohtyp ot emoclew

Q.7) Write a program to check whether a string is palindrome or not.?

s=input("Enter string to check palindome or not?")

if s==s[ : :-1]:

print("Yes, It is palindrome string")

else:

print("No, not palindrome string")

Output-

Enter string to check palindome or not? madam

Yes, It is palindrome string

Q.8) Write a python program that counts occurences of characters in a string. Do not use
built in methods.

s=input("Enter any string")

ch=input("Enter character to check")

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)):

print("Yes strings starts with",sw)

else:

print("No string not starts with")

O/p:

Enter string Welcome to Python

Enter string to check starts with Welcome

Yes strings starts with Welcome

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")

ch=input("Enter Character to check present in string or not?")

if ch in s:

print("yes",ch," character present in string")

else:

print("No",ch,"Not present in string")

index=0

for x in s:

if x==ch:

print("Index of character", index)

index= index+1

O/p:

Enter string python


Enter Character to check present in string or not?t

yes t character present in string

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.

2. They are defined inside the __init__() method of the class.

class_var=0

def __init__(self,x):

self.x=x #object variable

print("value of object variable is", 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

self.x=x #object variable

print("value of class variable is", abc.class_var)

obj1=abc(10)

Q.2) Explain the following programming paradigms:


1)Monolithic
2)Structured
3)Procedural
1. Monoloithic:

1. It is formed of a single block.

2. Here, complete program is written as a sequence.

3. There are no modules or functions used.

e.g. Assembly language.

Advantages:

1. It is good for small size programs.

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.

3. Too much lengthy code.

2. Structured:

1. This is advanced version of procedural language.

2. It contains top down moular approach,control structure,unction oriented programming.

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.

3. It is easy to find errors and especially logical errors.

Disadvantages:

1. Data can be modified by any procedure or part o program.

2. No security to data.

3. Main focus is on function and then on data.


3. Procrdural:

1. Here, program is divided in procedures or modules or functions.

2. Function is a small unit of programming logic.

e,g. FORTRAN (Formula Translation), COBOL (Common Business Language)

Advatages:

1. Duplication of code is avoided.

2. Some functions can be used multiple times in one program whenever the operation is needed.

Disadvatages:

1. No security to data.

2. Data can be modified by any procedure.

3. It may include "goto" like statements which makes program unstructured.

Q.3) Differentiate between public and private variables.

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:

a=10 #public variable

def display(self):

print("welcome to public method")

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):

print("I'm inside the class abc in which this is private method")

def display(self):

print("Private Variable: ",abc.__year)

self.__privateMethod()

obj = abc()

obj.display()

Q.4) Explain following features of OOP:


1)Containership
2)reusability
3)Data Encapsulation
4)Data abstraction
5)Polymorphism
6)Delegation

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):

print("Component class m1() method executed")

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:

1. Most important application of OOP is reusability.

2. It means developing codes that can be reused either in the same program or in different
programs.

3. It is attained through inheritance, Polymorphism, containership.

3. Data Encapsulation:

1. The technique of packing data and function into single component to hide implementation
details of a class from user.

2. It is a mechanism of wrapping data and methods together as a single unit.

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):

print("welcome to public method")

def _display(self):

print("welcome to protected method")

def __display(self):

print("welcome to private method")

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.

from abc import ABC,abstractmethod

class sample(ABC):

@abstractmethod

def ac_details(self):

pass

class demo(sample):

def ac_details(self):

print("demo class ac_etails methos")

c=demo()
c.ac_details()

5. Polymorphism:

1. The word polymorphism means many forms.

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):

print(""Name of student : "",self.name)

print(""Roll no of stuent : "",self.roll_no)

print(""Age of student : "",self.age)

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)

Q.6)Write a pyhton program to calculate area of circle using a class.

class Circle():

def __init__(self, r):

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):

print(""Name of employee :"",self.name)

print(""salary of employee :"",self.sal)

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):

print(""Name of car :"",self.name)

print(""cost of car :"",self.cost)

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.

1.Absolute path- always contain root and complete directory.


Ex- C:\Students\Under Graduate\Btech_cs.docx
2. Relative path- describe path from current working directory.
Ex- If current working directory is C:\Students then relative path is Under
Graduate\Btech_CS.docx

2 Differentiate between text and binary files.


3 Explain any three methods for reading and writing files

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)

4 What is file? Explain different access modes for opening files.


A file is a collection of data stored on a secondary storage device like hard disks,
pen-drives, DVD or CDs.

Syntax for file open-


File_ref = open( file_name, access_mode)
Ex- f=open(abc.txt,r)
File opening mode for Text and Binary files
1. Text (ASCII) Files –mode- r, w, a, r+, w+, a+, x
2. Binary Files.- mode- rb, wb, ab, r+b, w+b, a+b, xb

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.

5 Explain following file handling methods:


1)write()
Fileobj.write(String)f.write(string)
f=open("Sample.txt",“w")
f.write("Hello")
f.close()
2)read()
f.read()-> To read total data
f=open("Sample.txt")
a=f.read()
print(a)
3)readlines()
f.readlines()--> to read all lines into a list
f=open("Sample.txt")
lines=f.readlines()
print(lines)
4)writelines()
Fileobj.writelines()f.writelines(list of lines)
Ex-
f=open("Sample.txt","w")
l=["Hello\n","how\n","are\n","you?"]
f.writelines(l)
f.close()
5)close()
Close function is used to close the file.
File_ref.close()
f.close()
6)seek()
5 Explain different directory methods with example.
• getcwd()-To know current working directory.
Ex- import os
cwd= os.getcwd()
print("Current working directory",cwd)
• chdir()- change current directory. Method take name of directory which
you want to make the current directory.
Ex- import os
os.chdir("FE")
cwd=os.getcwd()
print(cwd)
• mkdir()-To create a new directory(create subdirectory in current working
directory)
Ex- importos
os.mkdir("FE\PPS Program")
print("Created")
• makedirs()- To create both parent and child directory
Ex-
import os
os.makedirs("FE\PPS\Practicals")
• rmdir() - To remove directory. (remove empty directory)
Ex- import os
os.rmdir("FE/PPS/Practicals")
• removedirs()- All directory remove.
Ex- import os
os.removedirs("FE\PPS\Practicals")
• rename()
Ex- import os
os.rename("FE","First Year")
• listdir()- To know content of directory.
Ex- import os
l=os.listdir("FE")
print(l)

6 Explain different dictionary methods with example.


• Creating Dictionary-
di={}, d={1:"One",2:"Two",4:"Four"}
• Accessing element-
• di={1:"One",2:"Two",3:"Three"}
• di.keys()
dict_keys([1, 2, 3])
• di.values()
dict_values(['One', 'Two', 'Three'])
• di.get(1)
'One’
• di[2]
'Two'
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing the a tuple for each key value pair

keys() Returns a list containing the dictionary's keys


pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist: insert
setdefault()
the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

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.

You might also like