0% found this document useful (0 votes)
34 views

PYTHON

Uploaded by

jp7166588
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

PYTHON

Uploaded by

jp7166588
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

PYTHON

BCA-III

SOUNotes

SOUNotes
UNIT-01 Overview of
Python
Introduction
Python is a simple, easy to learn, high-level, interpretive, general-purpose, free and
open source, and Powerful programming language.
It has efficient high-level data structures and a simple but effective approach to
object-oriented programming.
Python was introduced in the late 1980s and its implementation was started in
December 1989 by Dutch programmer Guido van Rossum at CWI (Centrum
Wiskunde & Informatica) Research lab in the Netherlands.
Python based on ABC, C, Bourne Shell, Modula-3, Perl, Haskell, and Lisp
Named after Guido's favourite BBC comedy TV show "Monty Python's Flying Circus"

Key Features of Python


1. Easy to learn and Use:
It has a simple structure, a few keywords, and clearly straightforward defined
syntax.
There is no use of the semicolon or curly-brackets for defining scope in Python.
Its indentation (spaces or tabs) defines the block of code.
Therefore, Python programs are easy to read and understand.
2. Expressive Language:
Python (like Perl) is an expressive language. Its syntax is very easy.
We can perform complex tasks by writing a few lines of code in Python as
compared to other programming language.
3. Interpreted Language:
Python is an interpreted based language similar to Perl and PHP.
It means its script code is executed one line at a time and not all at once, like in
other programming languages. The line-by-line execution makes it easy to
debugging the Python code.
Python has also a built-in debugging feature.
Beside it, Python is not a fully compiled language.
The code is automatically compiled into the machine readable byte codes and
then executed.
4. Cross-platform Language:
Python is a cross-platform language, which means it is platform independent. We
can run the Python code equally on different platforms, such as Windows, Linux,
UNIX, and Macintosh, etc.
This is because the source code of python first is converted to a machine readable
byte code, which is then interpreted.
5. Free and Open Source:
Python is a free and open-source programming language. It is freely available for
everyone. We can install it on our computer free of cost on any operating system

3
with no copyright issues.
6. Object-Oriented Language:
Python supports object-oriented style of programming (OOP) that encapsulates
the code within objects.
OOP is a modern programming paradigm that is based on the concepts of classes
and objects.
It breaks up the code into several segments that messages back and forth using
classes.
Object-oriented programming supports inheritance, polymorphism, data
encapsulation, inheritance, polymorphism, etc.
Its procedure helps to programmer to write reusable code and develop powerful
applications in less code with a good level of abstraction.
7. Interactive:
Python is really interactive, so we can write a program directly on the Python
prompt.
The advantage of being Python interactive is we can interact directly with the
interpreter and get the immediate results.
We can also use the prompt to test out small bits of codes to see if they work
8. Easy to Maintain:
We can easily maintain the source code of Python programming language.
9. Extensible Feature:
We can integrate Python with other languages such as C, C++, and Java.
It allows us to execute the code written in other programming languages. This
implies that we can compile the code in other languages like C/C++, or Java, and
then can use that in our python code, which we can compile and run anywhere
10. High-Level Language:
Python is a high-level programming language, which means it enables the
programmer to write programs that are not specific to a particular type of
computer or designed for a specific task.
A high-level programming language is easier to write and understand.
Programmers can easily write and understand or interpret the code.
It is closer to human language and far to machine language.
For a computer to understand and run a program designed with a high-level
language, we must compile it into machine language.
11. Broad Standard Library:
One of the main reasons for Python's popularity is its large standard library for
the various fields such as machine learning, data science, web developer, and also
for the scripting.
Python contains a rich set of modules and functions that are cross-platform.
Web Development Libraries: Django, Flask, Bottle, Tornado, Pyramid, web2py,
CherryPy, CubicWeb
GUI Development Libraries: Tkinter, Libavg, PyGObject, PySimpleGUI, PyQt,
PySide, Kivy, wxPython, PyForms

4
Scientific and Numeric Libraries: SciPy, Numpy, Pandas, IPython, TensorFlow,
Seaborn, Matplotlib
12. Dynamic Typed Language:
Python is a dynamically typed language.
This means that the Python interpreter does type checking of variable at the
runtime.
Interpreter assigns the type of variable based on the value of variable at the
runtime.
We don't declare the data type of a variable explicitly in Python.
Interpreter decides the data type of variable and its memory allocation at
runtime.
Interpreter automatically allocates the memory to the variable at runtime when
we assign a value to the variable.
13. GUI Programming Support:
Python provides many graphical user interface (GUI) libraries that are used for
the developing Desktop web application.
14. Databases Support:
When we develop an application, we may need a database.
Python language provides Python Database API (DB-API) that provides an
interface to all major commercial databases.
MySQL, PostgreSQL, Microsoft SQL, Oracle, Informix, etc. are some databases
supported by standard python.
To use it, just import the interface for the particular database.
Using Python, we can work with both relational and non-relational databases.
15. Automation Tool:
Python is a great tool for the automation process.
We can write simple Python programs to automate routine tasks, such as
repetitive or time-consuming.
16. Scalable:
This feature of Python provides a better structure and supports for large
programs.

Limitations of Python
Python is an interpreter-based language. Therefore, it is slower in the terms of
execution of programs as compared to other programming languages
As we know python is a high-level language, it also uses several layers to
communicate with the operating system and computer hardware
Graphics applications such as video games make the program to run slower.

What is an Interpreter
An interpreter is simple software that executes the source code line by line

5
An interpreter is a program/software that converts a programming language into
Machine language that a computer can understand and execute.
While Interpreting a code, an interpreter will report any error it finds in the code. If it
does not find any error it will translate the code into Machine language.
The Python interpreter's name is CPython. It is written in C Language.

print() Function

The print() function prints the specified message to the screen, or other standard
output device.
The message can be a string, or any other object, the object will be converted into a
string before written to the screen.
Syntax: print(object(s), sep=separator, end=end, file=file, flush=flush)

print("Hello World!")

print(22+44)

Parameter Values:

Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before
printed
sep = Specify how to separate the objects, if there is more than one. Default
'separator' is ' ' (Optional)
end='end' Specify what to print at the end. Default is '\n' (line feed) (Optional)
file An object with a write method. Default is sys.std out (Optional)
flush A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False (Optional)

Basic Structure of Python Program

6
1. Documentation section:
The documentation section consists of a set of comment lines giving the name of
the program, the author, and other details, which the programmer would like to
use later.
2. Imports:
The imports section provides instructions to the interpreter to link functions from
the module such as using the import statement.
3. Global variables section:
Some variables are used in more than one function.
Such variables and are declared in the global declaration section that is outside of
all the functions.
4. Class definitions:
Here, we can declare different classes.
Classes are a collection of data members and data functions.
5. User-defined functions:
This section also declares all the user-defined functions.
6. Executable part:
There is at least one statement in the executable part.

# Documentation Section
# Write a Program to show use of scope variable using function

# Import Section
import math

# Global Variables Section


x = 50

# Class Defination Section


class Person:

# User Defined Functions


def __init__(self, name, age):
self.name = name
self.age = age

# User Defined Functions


def greet(self):
print("Hello my name is "+self.name)
print("My age is "+self.age)

# Executable Part

p1 = Person("John", "19")
p2 = Person("Alex", "20")

7
p1.greet()
p2.greet()

Keywords
Keywords are reserved words that cannot be used as a variable name, function name, or
any other identifier.

Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if there
is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement

8
Keyword Description
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator

Identifiers
Identifier is a user-defined name given to a variable, function, class, module, etc.
They are case-sensitive
It is a good programming practice to give meaningful names to identifiers to make
the code understandable.
We can also use the isidentifier() method to check whether a string is a valid
identifier or not.

Rules for Naming Python Identifiers:

It cannot be a reserved python keyword.


It should not contain white space.
It can be a combination of A-Z, a-z, 0-9, or underscore.
It should start with an alphabet character or an underscore ( _ ).
It should not contain any special character other than an underscore ( _ ).

Variables
Variable is containers that store values.
Python is not statically typed.
We do not need to declare variables before using them or declare their type.
A variable is created the moment we first assign a value to it.

num = 12

name = "John Doe"

Variable names can be any length can have capitalized, lowercase (start to finish, a to
z), the digit (0-9), and highlight character( _ ).
Local Variable: The variables that are declared within the function and have scope
within the function are known as local variables.

# Local Variable Example

def add():
a = 15
b = 25
c = a+b
print(c)

9
add()
print(c)

# Output
40
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in <module>
NameError: name 'c' is not defined

Global Variables: The variables that are declared globally and have scope in entire
program known as Global variables.

# Global Variable Example


a = 15 # Global Variable
b = 25 # Global Variable

def add():
c = a+b
print(c) # Local Variable

print(c)

# Output: 40

Ways to Assign Variables

# 01. Declaring a varibale and assigning value

age = 19

# 02. Assigning Multiple Values

result = mark1, amrk2, mark3 = 78, 88, 84

# 03. Reassigning Values

temp = 10
temp = "Hello"
temp = False

# 04. Deleting a Vriable

del temp
print(temp) # ERROR: name 'temp' is not defined

User Input

10
By default input() takes values as String type.

name = input("Enter Your Name: ")


age = int(input("Enter Your Age: "))

print(name)
print(age)

Data Types

Int Data Type

In Python, the int data type is a numeric type used to represent whole integer
number as opposition with float number.
Creating a int is done by using the whole integer number without quotes or using
the int() constructor function

Float Data Type

In Python, the float data type is a numeric type that is used to represent number
with floating point values as opposition with whole int number.
Creating a float is done by using the number using the decimal point ( . ) without
quotes or using the float() constructor function.

Complex Data Type

In Python, the complex data type represents complex numbers that contain a real
part and an imaginary part. In complex numbers, the real part and the imaginary part
are floating-point numbers denoted by the suffix “j” or “J”.
Complex numbers are used often in mathematical and scientific calculations.

11
# int Type
i = 3
print(type(i)) # <class 'int'>

# float Type
f = 3.1
print(type(f)) # <class 'float'>

# complex Type
z = 2 + 5j # Real part: 2, imaginary part: 5
print(type(z)) # <class 'complex'>

Bool Data Type

In Python, the bool data type is used to represent Boolean values ( True , False ).
Booleans are used to evaluate expressions and return the
Boolean True or False based on the result of the expression.

# Boolean expression
x = 10
y = 5

result = x > y
print(result) # True
print(type(result)) # <class 'bool'>

Str Data Type

In Python, the str data type is used to define text component enclosing a sequence
of characters within single-quotes or double-quotes. Python strings can contain
letters, numbers or special characters.

# String data type


greet = "Hello"
print(type(greet)) # <class 'str'>

# Print string
print(greet)

List Data Type

In Python, the list data type is used to store ordered sequence of elements. Python
lists are ordered collections that can contain elements of various data types (str, list,
dicts, …). List elements can be accessed, iterated, and removed.
Slicing or accessing elements of a list is done using the square brackets ( [] ) notation.
Creating a list is done using the square brackets ( [] ) or the list() constructor
function

12
ls = ['hello', 1, True, [1, 2]]

print(ls) # ['hello', 1, True, [1, 2]]


print(type(ls)) # <class 'list'>

Tuple Data Type

In Python, Tuples are a data structure of the sequence type that store a collection of
data.
Python Tuples have these 5 characteristics.
ordered
unchangeable
immutable
allow duplicate value
allow values with multiple data types
Creating a tuple is done using the parentheses ( () ) or the tuple() constructor
function.

t = (1, 2, 3, 4, 5)

print(t) # (1, 2, 3, 4, 5)
print(type(t)) # <class 'tuple'>

Dict Data Type

In Python, dictionaries are an unordered collection of key-value pairs stored as


a dict data type. Python dictionaries are a mappings data type used to store
collections of data.
Creating a dictionary is done adding key, value pairs inside curly brackets ( {} ) or
using the dict() constructor function.
Values in dictionaries can be selected passing the key string inside the square
brackets ( [] ) of the dictionary object.

d = {
'name': 'John',
'last_name': 'Doe'
}

print(d) # {'name': 'John', 'last_name': 'Doe'}


print(type(d)) # <class 'dict'>

Set Data Type

In Python, sets are an unordered collection unique elements (no duplicate values). A
Python set is a mutable object where you can add, remove, or modify elements after
creating it.

13
Creating a set is done adding comma-separated values inside curly brackets ( {} ) or
using the set() constructor function.
Python Sets have a multiple characteristics:
Duplicates are not allowed
They can have Multiple data Types
Sets Can’t Be Accessed with the Index
Not Subscriptable

s = {1,2,3}

print(s) # {1, 2, 3}
print(type(s)) # <class 'set'>

Frozenset Data Type

In Python, the frozenset data type represents an immutable set.


Creating a frozenset is done using the frozenset() constructor function. Once
created, you cannot add, remove, or modify elements to the frozenset .
The difference between a set and a frozenset in Python is that the set is mutable
and the frozenset is not. You can change a set by adding, removing or modifying its
elements, but doing so with a frozenset would result in an error.

# set
my_set = {1, 2, 3, 4}
my_set.add(5)
my_set.remove(2)
print(my_set) # {1, 3, 4, 5}

# frozenset
my_frozenset = frozenset([1, 2, 3, 4])

# Adding or removing elements from frozenset returns an error


my_frozenset.add(5) # AttributeError
my_frozenset.remove(2) # AttributeError

Operators
Arithmetic Operators

Operator Meaning Example


+ Add two operands or unary plus x + y +2
– Subtract right operand from the left or unary minus x – y -2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into x/y
float)

14
Operator Meaning Example
% Modulus – remainder of the division of left operand by x % y (remainder
the right of x/y)
// Floor division – division that results into whole number x // y
adjusted to the left in the number line
** Exponent – left operand raised to the power of right x**y (x to the
power y)

Assignment Operator

Operator Meaning Example


= Assign the value of the right side of the expression to the left side c=a+b
operand
+= Add right side operand with left side operand and then assign the a += b
result to left operand
-= Subtract right side operand from left side operand and then a -= b
assign the result to left operand
*= Multiply right operand with left operand and then assign the a *= b
result to the left operand
/= Divide left operand with right operand and then assign the result a /= b
to the left operand
%= Divides the left operand with the right operand and then assign a %= b
the remainder to the left operand
//= Divide left operand with right operand and then assign the a //= b
value(floor) to left operand
**= Calculate exponent(raise power) value using operands and then a **= b
assign the result to left operand
&= Performs Bitwise AND on operands and assign the result to left a &= b
operand
|= Performs Bitwise OR on operands and assign the value to left a |= b
operand
^= Performs Bitwise XOR on operands and assign the value to left a ^= b
operand
>>= Performs Bitwise right shift on operands and assign the result to a >>= b
left operand
<<= Performs Bitwise left shift on operands and assign the result to a <<= b
left operand
:= Assign a value to a variable within an expression a := exp

Comparison Operator

15
Operator Meaning Example
> Greater that – True if left operand is greater than the right x>y
< Less that – True if left operand is less than the right x<y
== Equal to – True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to – True if left operand is greater than or x >= y
equal to the right
<= Less than or equal to – True if left operand is less than or equal to x <= y
the right

Logical Operators

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x

Bitwise Operator

Operator Meaning Example


& Bitwise AND x& y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>2
<< Bitwise left shift x<<2

Membership Operator

Operator Meaning
in Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
not in Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise.

Identity Operator

16
Operator Meaning
is Evaluates to true if the variables on either side of the operator point to the
same object and false otherwise.
not is Evaluates to false if the variables on either side of the operator point to the
same object and true otherwise.

Operator Precedence

Operators Description
() Parentheses (grouping)
** Exponentiation (raise to the power)
~+ – Complement, unary plus and minus (method names for the last
two are +@ and -@)
*/ % // Multiply, divide, modulo and floor division
+– Addition and subtraction
>> << Right and left bitwise shift
& Bitwise ‘AND’
^| Bitwise exclusive OR’ and regular OR’
<= < > >= Comparison operators
< > == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is, is not Identity operators
in, not in Membership operators
not or and Logical operators

Type Conversion
The act of changing an object's data type is known as type conversion.
The Python interpreter automatically performs Implicit Type Conversion.
Python prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type
conversion, sometimes referred to as type casting.
When type casting, data loss could happen if the object is forced to conform to a
particular data type.
Implicit Type Conversion: In Implicit type conversion of data types in Python, the
Python interpreter automatically converts one data type to another without any user
involvement.
Explicit Type Conversion: The data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are

17
forcing an expression to be changed in some specific data type.

# Implicit Type Conversion

celcius = 25
fahrenheit = (celcius*9/5)+32 # int -> float
print(fahrenheit) # 77.0

# Explicit Type Conversion

num = 15
number = str(num) # int -> string
print(number) # 15

Conditional Statements
if Statement

The if statement is the most simple decision-making statement.


It is used to decide whether a certain statement or block of statements will be
executed or not.

num = 15

if (num%2 == 0):
print("Number is Even)

if-else Statement

We can use the else statement with the if statement Python to execute a block of
code when the Python if condition is false

num = 15

if (num%2 == 0):
print("Number is Even)
else:
print("number is Odd)

elif Statement

As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final “else” statement will be executed.

mark = 87

if mark>=90:

18
print("Grade: A")
elif mark >= 75:
print("Grade: B")
elif mark >= 60:
print("Grade: C")
elif mark >= 40:
print("Grade: D")
else:
print("Fail)

Nested if-else Statement

# Example of nested if-else


x = 10
y = 5

if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
if x == y:
print("x is equal to y")
else:
print("This should never happen")

Loop
for Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc

# Multiplication Table using For Loop

num = 5

for i in range(1, 11):


print(num, "x", i, " = ", num*i)

# Iterating over a list

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)

19
while Loop

While loops are used in Python to iterate until a specified condition is met.
However, the statement in the program that follows the while loop is executed once
the condition changes to false

# Multiplication Table Using While Loop

num = 5
i = 1

while(i<=10):
print(num, "x", i, " = ", num*i)
i += 1

for Loop while Loop


It is used when the number of It is used when the number of iterations is not
iterations is known. known
In case of no condition, the loop is In case of no condition, an error will be shown
repeated infinite times
Initialization is not repeated. Initialization is repeated if carried out during
the stage of checking.
Statement of Iteration is written after It can be written at any place.
running.
Initialization can be in or out of the loop Initialization is always out of the loop
The nature of the increment is simple. The nature of the increment is complex.
Used when initialization is simple Used when initialization is complex.

Loop Control Statements


continue Statement

This command skips the current iteration of the loop. The statements following the
continue statement are not executed once the Python interpreter reaches the continue
statement.

# Skip printing when i equals 2


for i in range(5):
if i == 2:
continue
print(i)

break Statement

20
This command terminates the loop's execution and transfers the program's control to
the statement next to the loop.

# Break the loop when i equals 3


for i in range(5):
if i == 3:
break
print(i)

pass Statement

The pass statement is used when a statement is syntactically necessary, but no code
is to be executed.

for i in range(5):
pass # Loop does nothing

21
UNIT-02 String, Lists &
Functions
String
Creating and Storing Strings
In Python, strings can be created using single quotes ( ' ) or double quotes ( " ). They
are immutable sequences of characters.

# Example of creating strings


str1 = 'Hello, '
str2 = "world!"

Basic String Operations


Python supports various operations on strings, such as concatenation ( + ), repetition
( * ), and membership ( in operator).

# Example of basic string operations


str1 = 'Hello, '
str2 = 'world!'
concatenated_str = str1 + str2
repeated_str = str1 * 3
print(concatenated_str) # Output: Hello, world!
print(repeated_str) # Output: Hello, Hello, Hello,

Accessing Characters in String by Index Number


Individual characters in a string can be accessed using indexing. Indexing starts at 0
in Python.

# Example of accessing characters in a string


my_string = 'Python'
print(my_string[0]) # Output: 'P'
print(my_string[3]) # Output: 'h'

String Slicing and Joining


String slicing allows you to extract a substring from a string. It uses the syntax
string[start:end:step] .

# Example of string slicing


my_string = 'Python Programming'
print(my_string[7:]) # Output: 'Programming'
print(my_string[:6]) # Output: 'Python'
print(my_string[::2]) # Output: 'Pto rgamn'

String Methods
23
Python provides many built-in methods for manipulating strings, such as upper() ,
lower() , strip() , replace() , split() , etc.

# Example of string methods


my_string = ' Hello, World! '
print(my_string.strip()) # Output: 'Hello, World!'
print(my_string.lower()) # Output: ' hello, world! '
print(my_string.replace('Hello', 'Hi')) # Output: ' Hi, World! '

Formatting Strings
String formatting allows you to interpolate variables and expressions within strings.
Python supports multiple ways of string formatting, including f-strings, str.format() ,
and % formatting.

# Example of string formatting


name = 'Alice'
age = 25
print(f'My name is {name} and I am {age} years old.')
# Output: 'My name is Alice and I am 25 years old.'

Lists
Creating Lists
Lists are one of Python's built-in data types used to store multiple items in a single
variable. Lists are ordered, mutable, and can contain items of different data types.

# Example of creating lists


empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True]

Basic List Operations


Lists support a variety of basic operations like concatenation ( + ), repetition ( * ), and
membership ( in ).

# Example of basic list operations


list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
repeated_list = list1 * 3
print(concatenated_list) # Output: [1, 2, 3, 4, 5, 6]
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Indexing and Slicing in Lists

24
You can access individual elements or slices of a list using indexing and slicing.
Indexing starts at 0, and slicing uses the list[start:end:step] syntax.

# Example of indexing and slicing in lists


my_list = [10, 20, 30, 40, 50]

# Accessing individual elements


print(my_list[0]) # Output: 10
print(my_list[2]) # Output: 30

# Slicing
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[::2]) # Output: [10, 30, 50]

Built-In Functions Used on Lists


Python provides several built-in functions that can be applied to lists, such as len() ,
max() , min() , sum() , and sorted() .

# Example of built-in functions used on lists


numbers = [10, 5, 8, 3, 7]

print(len(numbers)) # Output: 5 (length of the list)


print(max(numbers)) # Output: 10 (maximum element)
print(min(numbers)) # Output: 3 (minimum element)
print(sum(numbers)) # Output: 33 (sum of elements)
print(sorted(numbers)) # Output: [3, 5, 7, 8, 10] (sorted list)

List Methods
Python provides several useful methods for lists, such as append() , extend() ,
insert() , remove() , pop() , reverse() , and sort() .

# Example of list methods


my_list = [10, 20, 30]

my_list.append(40) # Adds 40 to the end of the list


print(my_list) # Output: [10, 20, 30, 40]

my_list.insert(1, 15) # Inserts 15 at index 1


print(my_list) # Output: [10, 15, 20, 30, 40]

my_list.remove(20) # Removes the first occurrence of 20


print(my_list) # Output: [10, 15, 30, 40]

popped_item = my_list.pop() # Removes and returns the last item


print(popped_item) # Output: 40
print(my_list) # Output: [10, 15, 30]

25
my_list.reverse() # Reverses the list
print(my_list) # Output: [30, 15, 10]

my_list.sort() # Sorts the list in ascending order


print(my_list) # Output: [10, 15, 30]

The del Statement


The del statement is used to delete elements from a list or even delete the entire list.
You can delete a specific element by its index or slice.

# Example of del statement


my_list = [10, 20, 30, 40, 50]

del my_list[1] # Deletes the element at index 1


print(my_list) # Output: [10, 30, 40, 50]

del my_list[1:3] # Deletes elements from index 1 to 2 (slice)


print(my_list) # Output: [10, 50]

del my_list # Deletes the entire list

Functions
Built-in Functions
Python comes with several built-in functions for various operations, such as print() ,
len() , type() , range() , input() , etc. These functions are always available and don't
require any imports.

# Example of built-in functions


print("Hello, World!") # Output: Hello, World!
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
print(type(numbers)) # Output: <class 'list'>

Commonly Used Modules


Python provides a vast standard library with built-in modules that you can import for
extended functionality. Some commonly used modules are:
math : Mathematical operations.
random : Generating random numbers.
datetime : Working with dates and times.
os : Interfacing with the operating system.

# Example of using commonly used modules


import math
import random

26
import datetime

print(math.sqrt(16)) # Output: 4.0


print(random.randint(1, 10)) # Output: A random number between 1 and 10
print(datetime.datetime.now()) # Output: Current date and time

Definition and Calling the Function


A function is defined using the def keyword, followed by the function name and
parentheses. A function can be called by using its name followed by parentheses.

# Example of defining and calling a function


def greet(name):
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!

Return Statement and Void Function


A function can return a value using the return statement. If no return statement is
present, or the function returns None , it's considered a "void function".

# Example of function with return statement


def add(a, b):
return a + b

result = add(5, 3)
print(result) # Output: 8

# Example of a void function


def print_message():
print("This is a void function")

print_message() # Output: This is a void function

Scope and Lifetime of Variables


Variables defined inside a function are local to that function and cannot be accessed
outside. Variables defined outside any function are global, but you cannot modify
global variables inside a function unless explicitly stated using the global keyword.

# Example of variable scope and lifetime


def my_function():
local_var = 10 # Local variable
print(local_var)

global_var = 20 # Global variable

my_function() # Output: 10

27
print(global_var) # Output: 20

# Modifying a global variable inside a function


def modify_global():
global global_var
global_var = 50

modify_global()
print(global_var) # Output: 50

Default Parameters
You can provide default values to function parameters. If the caller doesn't pass a
value, the default will be used.

# Example of default parameters


def greet(name="User"):
print(f"Hello, {name}!")

greet() # Output: Hello, User!


greet("Alice") # Output: Hello, Alice!

Keyword Arguments
Python allows you to call functions using keyword arguments, where the name of the
argument is explicitly mentioned, making the function calls more readable.

# Example of keyword arguments


def display_info(name, age):
print(f"Name: {name}, Age: {age}")

display_info(age=25, name="Bob") # Output: Name: Bob, Age: 25

Command Line Arguments


Python allows you to pass arguments to your script from the command line using the
sys module. The sys.argv list stores these arguments.

# Example of command-line arguments


import sys

def print_arguments():
print("Command Line Arguments:", sys.argv)

# To run this, you would typically use a command like:


# python script.py arg1 arg2 arg3

Questions

28
1. What is a string in Python? Explain string operations with an example.
2. What is string slicing? Provide an example and explain how slicing can be used to
reverse a string.
3. List five methods of string manipulation in Python.
4. What is a list in Python? Explain list operations with examples.
5. Describe the list method in Python with an example.
6. Differentiate between a list and a string in Python.
7. What is a function in Python? Explain any five built-in functions in Python.
8. Explain the concept of scope and lifetime of variables within a function.
9. What is the purpose of a function? How do you declare a function in Python? explain it
with an example.

29
UNIT-03 Dictionaries,
Tuples & Sets
Dictionaries
Creating Dictionary
A dictionary in Python is a collection of key-value pairs. Each key is associated with a
value, and dictionaries are unordered, mutable, and indexed by keys.

# Example of creating dictionaries


empty_dict = {} # Empty dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}

Accessing and Modifying Key-Value Pairs in Dictionaries


You can access dictionary values by referencing their keys. You can also modify the
value associated with a key or add a new key-value pair.

# Example of accessing and modifying key-value pairs


person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

# Accessing values
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 25

# Modifying values
person["age"] = 26
print(person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}

# Adding new key-value pair


person["job"] = "Engineer"
print(person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'job': 'Engineer'}

Built-In Functions Used on Dictionaries


Python provides several built-in functions that can be used on dictionaries. Common
ones include len() , max() , min() , and sorted() .
31
# Example of built-in functions used on dictionaries
my_dict = {"a": 10, "b": 20, "c": 30}

print(len(my_dict)) # Output: 3 (number of key-value pairs)


print(max(my_dict)) # Output: 'c' (maximum key based on alphabetical order)
print(min(my_dict)) # Output: 'a' (minimum key based on alphabetical order)
print(sorted(my_dict)) # Output: ['a', 'b', 'c'] (sorted keys)

Dictionary Methods
Dictionaries come with various methods for performing operations, such as get() ,
keys() , values() , items() , pop() , update() , and more.

# Example of dictionary methods


person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

# get() method
print(person.get("name")) # Output: Alice
print(person.get("job", "Not available")) # Output: Not available

# keys(), values(), items() methods


print(person.keys()) # Output: dict_keys(['name', 'age', 'city'])
print(person.values()) # Output: dict_values(['Alice', 25, 'New York'])
print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 25),
('city', 'New York')])

# pop() method
age = person.pop("age")
print(age) # Output: 25
print(person) # Output: {'name': 'Alice', 'city': 'New York'}

# update() method
person.update({"age": 26, "job": "Engineer"})
print(person) # Output: {'name': 'Alice', 'city': 'New York', 'age':
26, 'job': 'Engineer'}

The del Statement


The del statement is used to delete a key-value pair from a dictionary or to delete
the entire dictionary.

# Example of using the del statement


person = {
"name": "Alice",
"age": 25,
"city": "New York"

32
}

# Delete a specific key-value pair


del person["city"]
print(person) # Output: {'name': 'Alice', 'age': 25}

# Delete the entire dictionary


del person

Tuples
Creating Tuples
A tuple is an immutable sequence of items. Tuples are created using parentheses ()
and can store different types of data.

# Example of creating tuples


empty_tuple = ()
single_element_tuple = (42,)
mixed_tuple = (1, "apple", 3.14)

print(mixed_tuple) # Output: (1, 'apple', 3.14)

Basic Tuple Operations


Tuples support operations similar to lists, like concatenation ( + ), repetition ( * ), and
membership checking ( in ).

# Example of basic tuple operations


tuple1 = (1, 2, 3)
tuple2 = (4, 5)

# Concatenation
new_tuple = tuple1 + tuple2
print(new_tuple) # Output: (1, 2, 3, 4, 5)

# Repetition
repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

# Membership
print(2 in tuple1) # Output: True
print(6 in tuple1) # Output: False

Indexing and Slicing in Tuples


You can access tuple elements using indexing and slicing, just like with lists.

33
# Example of indexing and slicing
my_tuple = (10, 20, 30, 40, 50)

# Indexing
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 50

# Slicing
print(my_tuple[1:4]) # Output: (20, 30, 40)
print(my_tuple[:3]) # Output: (10, 20, 30)

Built-In Functions Used on Tuples


Some built-in functions like len() , max() , min() , and sum() work with tuples.

# Example of built-in functions


numbers = (10, 20, 30, 40)

print(len(numbers)) # Output: 4
print(max(numbers)) # Output: 40
print(min(numbers)) # Output: 10
print(sum(numbers)) # Output: 100

Relation Between Tuples and Lists


Tuples and lists are both sequence types in Python. The key difference is that tuples
are immutable, meaning once created, they cannot be modified, while lists are
mutable.

# Example of converting between tuples and lists


my_tuple = (1, 2, 3)
my_list = list(my_tuple) # Convert tuple to list
my_list.append(4)
new_tuple = tuple(my_list) # Convert list back to tuple
print(new_tuple) # Output: (1, 2, 3, 4)

Relation Between Tuples and Dictionaries


Tuples are often used as keys in dictionaries because they are immutable. Lists cannot
be used as dictionary keys.

# Example of using a tuple as a key in a dictionary


location_coordinates = {
(40.7128, -74.0060): "New York",
(34.0522, -118.2437): "Los Angeles"
}

34
print(location_coordinates[(40.7128, -74.0060)])
# Output: New York

Tuple Methods
Tuples have only two methods: count() and index() .

# Example of tuple methods


my_tuple = (10, 20, 20, 30)

# count() method
print(my_tuple.count(20)) # Output: 2

# index() method
print(my_tuple.index(30)) # Output: 3

Using zip() Function


The zip() function can be used to combine multiple iterables (e.g., lists or tuples) into
tuples.

# Example of using zip() function


names = ("Alice", "Bob", "Charlie")
scores = (85, 90, 95)

zipped = zip(names, scores)


print(list(zipped)) # Output: [('Alice', 85), ('Bob', 90), ('Charlie', 95)]

Sets
Creating Sets
Sets are unordered collections of unique elements. Sets are created using curly braces
{} or the set() constructor.

# Example of creating sets


empty_set = set() # Empty set
numbers_set = {1, 2, 3, 4, 5}
mixed_set = {1, "apple", 3.14}

print(mixed_set) # Output: {1, 3.14, 'apple'}

Set Methods
Sets have several built-in methods like add() , remove() , union() , intersection() ,
and difference() .

35
# Example of set methods
fruits = {"apple", "banana", "cherry"}

# add() method
fruits.add("orange")
print(fruits) # Output: {'apple', 'orange', 'cherry', 'banana'}

# remove() method
fruits.remove("banana")
print(fruits) # Output: {'apple', 'orange', 'cherry'}

# union() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}

# intersection() method
print(set1.intersection(set2)) # Output: {3}

# difference() method
print(set1.difference(set2)) # Output: {1, 2}

Traversing of Sets
You can iterate through a set using a for loop, but remember that sets are unordered,
so the elements will not follow any particular sequence.

# Example of traversing a set


my_set = {"apple", "banana", "cherry"}

for fruit in my_set:


print(fruit)

# Output (order may vary):


# apple
# banana
# cherry

Questions
1. How to create a dictionary in python? Explain operations of dictionary with example.
2. what is dictionary ? explain any 5 methods of dictionary in python.
3. difference between tuple and set.
4. What is the difference between tuples and lists in Python? Can a tuple be converted
into a list?
5. what is tuple? Explain any three methods of tuple with example.
6. what is set? Explain any three methods of set with example.
7. Discuss the advantages and disadvantages of dictionaries in Python.

36
8. explain list, tuple, set, and dictionary with example.
9. write down any five built in method of dictioanry. Explain each method with example.

37
UNIT-04 File Handling
Introduction
File is a collection of related data stored on a secondary storage device, such as a
hard disk, CD, DVD, pen-drive, etc. A file has a name and extension that indicates its
type.
Files are used to store data permanently and to transfer data between different
programs or devices.
The file handling plays an important role when the data needs to be stored
permanently into the file.
A file is a named location on disk to store related information.
We can access the stored information (non-volatile) after the program termination.

Python File Handling


Python supports file handling and allows users to handle files i.e., to read and write
files, along with many other file handling options, to operate on files.
File handling in Python is a powerful and versatile tool that can be used to perform a
wide range of operations.
However, it is important to carefully consider the advantages and disadvantages of
file handling when writing Python programs, to ensure that the code is secure, reliable,
and performs well.
In Python, files are treated in two modes as text or binary. The file may be in the text
or binary format, and each line of a file is ended with the special character like a
comma (,) or a newline character.
Python executes the code line by line. So, it works in one line and then asks the
interpreter to start the new line again.
This is a continuous process in Python.

Types of Python Files


Binary Files
Most of the files that we see in our computer system are called binary files.

Document files: .pdf, .doc, .xls etc.


Image files: .png, .jpg, .gif, .bmp etc.
Video files: .mp4, .3gp, .mkv, .avi etc.
Audio files: .mp3, .wav, .mka, .aac etc.
Database files: .mdb, .accde, .frm, .sqlite etc.
Archive files: .zip, .rar, .iso, .7z etc.
Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal
text editor but we can’t read the content present inside the file.

39
That’s because all the binary files will be encoded in the binary format, which can be
understood only by a computer or machine.
For handling such binary files we need a specific type of software to open it.

Text Files
Text files don’t have any specific encoding and it can be opened in normal text editor
itself.

Web standards: html, XML, CSS, JSON etc.


Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc

Difference between Text Files & Binary Files

Text File Binary File


The bits represent characters. The bits represent custom data.
Contains alphabets, numbers, Typically contains a sequence of bytes or ordered
etc. groupings of eight bits.
Less prone to corruption with More prone to corruption.
changes.
Can only store plain text. Can store text, images, audio, etc.
Can be opened in any basic Requires specific applications to open (e.g., music
text editor. players for audio files).
Common extensions include Many different extensions (e.g., .jpg, .zip, .mp4).
.txt or .rtf.
Occupies less memory. Occupies more memory.
Stores data in a human- Not in a human-readable format.
readable format.

File Handling Operations


Create and Open a File
Python has an in-built function called open() to open a file.
It takes a minimum of one argument as mentioned in the below syntax.
The open method returns a file object which is used to access the write, read and
other in-built methods.
The mode in the open function syntax will tell Python as what operation you want to
do on a file.

40
file_object = open(file_name, mode)
# File name should also include file's extension

Modes

Parameter Mode Description


r Read Mode Used only to read data from the file.
w Write Mode Used to write data into the file or modify it;
overwrites existing data in the file.
a Append Mode Used to append data to the file; data is added at the
end of the file pointer.
r+ Read/Write Used to read from and write to the same file.
a+ Append/Read Used to read data from the file or append data to the
same file.
wb Write (Binary) Opens a file for write-only mode in binary format.
rb Read (Binary) Opens a file for read-only mode in binary format.
ab Append (Binary) Opens a file for appending only in binary format.
rb+ Read/Write Opens a file for read and write only in binary format.
(Binary)
ab+ Append/Read Opens a file for appending and read-only in binary
(Binary) format.

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

f = open("demofile.txt", "a")

f.write("Now the file has more content!")


f.close()

#open and read the file after the appending:


f = open("demofile.txt", "r")
print(f.read())

Overwrite to an Existing File


To overwrite to an existing file, you must add w parameter to the open() function:

f = open("demofile.txt", "w")

f.write("Now the file has this content!")


f.close()

# open and read the file after the overwriting:

41
f = open("demofile.txt", "r")
print(f.read())

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters

Parameter Mode Description


x Create Will create a file; returns an error if the file already exists.
a Append Will create a file if the specified file does not exist.
w Write Will create a file if the specified file does not exist.

# Create a file called "myfile.txt":


f = open("myfile.txt", "x")

# Create a new file if it does not exist:


f = open("myfile.txt", "w")

Advantages & Disadvantages

Advantages Disadvantages
Versatility: Allows a wide range of Error-prone: Operations can lead to errors if
operations (creating, reading, writing, not carefully written or due to file system
appending, renaming, deleting files). issues (e.g., permissions, locks).
Flexibility: Supports different file types Security risks: Can pose security risks if
(text, binary, CSV, etc.) and various user input allows access to sensitive files.
operations (read, write, append).
User-friendly: Provides an easy-to-use Complexity: Can become complex with
interface for creating, reading, and advanced file formats or operations,
manipulating files. requiring careful coding.
Cross-platform: Functions work across Performance: Can be slower than other
different platforms (Windows, Mac, programming languages, especially with
Linux) for seamless integration. large files or complex operations.

Binary Files
A binary file is a file that contains data in the form of bytes, which can represent any
type of data, such as images, audio, video, executable code, etc.
A binary file cannot be read or edited using a text editor, but requires a specific
program or application that can understand its format.
To open binary files are similar to the text file open modes, except that they use the
“b” character to indicate binary mode.

42
Parameter Mode Description
rb Read Open a binary file for reading only; the file pointer is
placed at the beginning of the file.
rb+ Read/Write Open a binary file for both reading and writing; the file
pointer is placed at the beginning.
wb Write Open a binary file for writing only; overwrites the file if it
exists, creates a new file if it doesn't.
wb+ Write/Read Open a binary file for both writing and reading; overwrites
the file if it exists, creates a new file if it doesn't.
ab Append Open a binary file for appending; the file pointer is at the
end of the file if it exists; creates a new file if it doesn't.
ab+ Append/Read Open a binary file for both appending and reading; the file
pointer is at the end of the file if it exists; creates a new file
if it doesn't.

Pickle Module
The pickle module is a built-in module that provides functions for serializing and
deserializing python objects.
Serialization is the process of converting an object into a stream of bytes that can be
stored in a file or transmitted over network.
Deserialization is the reverse process of converting a stream of bytes back into an
object.
The pickle module can handle most python objects, such as lists, dictionaries, classes,
functions, ets. But not all.
The pickle module provides two methods to work with binary files for pickling and
unpickling, respectively:
The dump() method:
The dump() takes an object and a file object as arguments and writes the
serialized bytes of the object to the file.
The file in which data are to be dumped, needs to be opened in binary write mode
( wb ).

import pickle

list_values = [1, "SOUNotes", "A", 3]


file_object = open("mybinary.dat", "wb")

pickle.dump(list_values, file_object)

file_object.close()

The load() method

43
The laod() method takes a file object as an argument and returns the
deserialized object from the bytes read from the file.
The file to be loaded is opened in binary read ( rb ) mode.

import pickle

print("The data that were stored in file is: ")

file_object = open("mybinary.dat", "rb")

object_var = pickle.load(file_object)

file_object.close()

print(object_var)

The data that were stored in file is:


[1, "SOUNotes", "A", 3]

File Operations
Read
To read data from binary file, we can use methods like read() , readline() , or
readlines() .
However these methods will return bytes objects instead of strings. We can also use
struct.unpack() to convert bytes into other data types, such as integers, floats, etc.

# EXAMPLE: read an integer from a binary file


import struct

f = open("numbers.bin", "rb")
data = f.read(4)

number = struct.unpack("i", data)[0]

f.close()

print(number)

Write or Create
To write or create data in a binary file, we can use methods like write() or
writelines , just like in text files.
However, these methods will take bytes objects instead of strings. We can also use
struct.pack() to convert other data types into bytes, such as integers, floats, etc.

44
import struct

f = open("number.bin", "wb")

data = struct.pack("i", 42)


f.write(data)

f.close()

CSV File
A CSV file is a file that contains data in the form of characters separated by commas.
CSV files are often used to store and exchange data between different applications
that can handle tabular data, such as spreadsheets, databases, contact managers,
etc.
The CSV module is a built-in module that provides functions and classes for reading
and writing data in CSV format.
CSV stands for comma-separated values, which is a common format for storing and
exchanging tabular data, such as spreadsheets and databases.

Opening a CSV File


To open a CSV file in python, we use the same open() function that we use for text
files.
However, we need to specify the newline parameter as an empty string to avoid any
extra newlines in the data.

import csv
f = open(“people.csv”,”r”,newline=””)

Closing a CSV File


To close a CSV file in python, we use the same close() method that we use for text
files.
The close() method releases the resources associated with file and ensure that any
changes made to the file is saved.
It is important to close a file after using it to avoid errors or data loss.

import csv
f = open(“people.csv”,”r”,newline=””)

f.close()

Writing to a CSV File

45
To write data into a CSV file in python, we use csv.writer() function to create a
writer object that data to the file.
The writer object has methods like writerow() and writerows() that can write one or
more rows of data to the file.

import csv

# Data to be written to the CSV file


data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Los Angeles"],
["Charlie", 35, "Chicago"]
]

# Open the CSV file for writing


csvfile = open("output.csv", "w", newline='')

# Create a CSV writer object


writer = csv.writer(csvfile)

# Write the header


writer.writerow(data[0])

# Write the data rows


writer.writerows(data[1:]) # Writes multiple rows

# Manually close the file


csvfile.close()

Reading from a CSV File


To read data from a csv file in a python, we use the csv.reader() function to create a
reader object object that can iterate over the lines in the file.
The reader object returns each line as a list of strings.

import csv

# Open the CSV file for reading


csvfile = open("data.csv", "r", newline='')

# Create a CSV reader object


reader = csv.reader(csvfile)

# Read and print each row


for row in reader:
print(row)

46
# Manually close the file
csvfile.close()

Reading CSV Files with Headers

If your CSV file has a header row, you might want to use DictReader to read each row
as a dictionary

import csv

# Open the CSV file for reading


csvfile = open("data.csv", "r", newline='')

# Create a CSV reader object


reader = csv.DictReader(csvfile)

# Read and print each row as a dictionary


for row in reader:
print(row) # Each row is a dictionary with column headers as keys

# Manually close the file


csvfile.close()

OS Modules
Python has a built-in OS module with methods for interacting with the operating
system, like creating files and directories, management of files and directories, input,
output, environment variables, process management, etc.
OS Path module contains some useful functions on pathnames. The path parameters
are either strings or bytes.
These functions here are used for different purposes such as for merging, normalizing,
and retrieving path names in Python.
All of these functions accept either only bytes or only string objects as their
parameters.
The result is an object of the same type if a path or file name is returned.
As there are different versions of the operating system there are several versions of
this module in the standard library
The os and os.path modules include many functions to interact with the file system

Handling the Current Working Directory


Consider Current Working Directory(CWD) as a folder, where Python is operating.
Whenever the files are called only by their name, Python assumes that it starts in the
CWD which means that name-only reference will be successful only if the file is in the
Python’s CWD.
To get the location of the current working directory os.getcwd() is used

47
import os

cwd = os.getcwd()
print("Current Working Directory: ", cwd)

Changing the Current working directory


To change the current working directory (CWD) os.chdir() method is used.
This method changes the CWD to a specified path. It only takes a single argument as
a new directory path.

import os

def current_path():
print("Current Working Directory: ")
print(os.getcwd())
print()

current_path()
os.chdir('../')

current_path()

Creating a Directory
Using os.mkdir()

By using os.mkdir() method in Python is used to create a directory named path with
the specified numeric mode.
This method raises FileExistsError if the directory to be created already exists

import os

directory = "SOUNotes"
parent_dir = "D:/Projects/"
path = os.path.join(parent_dir, directory)

os.mkdir(path)
print("Directory '%s' created" %directory)

directory = "Notes"
parent_dir = "D:/Projects/"
mode = 0o666

path = os.path.join(parent_dir, directory)


os.mkdir(path, mode)
print("Directory '%s' created" %directory)

48
Using os.makedirs()

os.makedirs() method in Python is used to create a directory recursively.


That means while making leaf directory if any intermediate-level directory is missing,
os.makedirs() method will create them all.

import os

directory = "SOUNotes"
parent_dir = "D:/Projects/"
path = os.path.join(parent_dir, directory)

os.makedirs(path)
print("Directory '%s' created" %directory)

directory = "Notes"
parent_dir = "D:/Projects/"
mode = 0o666

path = os.path.join(parent_dir, directory)


os.mkdir(path, mode)
print("Directory '%s' created" %directory)

Listing out Files and Directories


There is os.listdir() method in Python is used to get the list of all files and
directories in the specified directory.
If we don’t specify any directory, then the list of files and directories in the current
working directory will be returned.

import os

path = "/"
dir_list = os.listdir(path)

print("Files and Directories in ", path, ": ")


print(dir_list)

Deleting Directory or Files


Using os.remove()

os.remove() method in Python is used to remove or delete a file path. This method
can not remove or delete a directory.
If the specified path is a directory then OSError will be raised by the method

import os
file = "demo.txt"

49
location = "D:/Projects/"
path = os.path.join(location, file)

os.remove(path)

Using os.rmdir()

os.rmdir() method in Python is used to remove or delete an empty directory.


OSError will be raised if the specified path is not an empty directory.

import os
directory = "SOUNotes"

parent = "D:/Projects/"
path = os.path.join(parent, directory)

os.rmdir(path)

Questions
1. Explain file types detail in python.
2. Explain file handling function in python.
3. Write a function in python to read the content from a text file Demo.txt line by line
and display the same on screen.
4. Explain pickle Module with an example.
5. How can you join two path components using the os.path module? Provide an
example.
6. What is the purpose of the open() function in Python, and what are the common
modes you can use to open a file? List at least three modes.
7. Why is the Pickle module needed? Discuss the advantages and disadvantages of the
Pickle module.
8. Differentiate Python Binary file and Python Text file.
9. What is File? Write a Python program to read a CSV file, and write data into CSV file.
10. List out Python OS module functions. Explain current working directory with an
example

50
SOUNotes

SOUNotes

SOUNotes

You might also like