Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Basic Notes of Python

The document provides an overview of Python programming concepts, focusing on types of tokens, operators, variables, data types, control structures, and functions. It includes best practices for naming identifiers and variables, as well as examples of various data structures like lists and tuples. Additionally, it covers mathematical functions and sorting algorithms, specifically insertion sort.

Uploaded by

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

Basic Notes of Python

The document provides an overview of Python programming concepts, focusing on types of tokens, operators, variables, data types, control structures, and functions. It includes best practices for naming identifiers and variables, as well as examples of various data structures like lists and tuples. Additionally, it covers mathematical functions and sorting algorithms, specifically insertion sort.

Uploaded by

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

CLASS XII

COMPUTER SCIENCE

By
Amit Agarwal
Types of Tokens
They are the smallest individual units in a program
Keywords
Identifiers
Literals
Operators
Punctuators

By Amit Agarwal
Types of Tokens
Keywords
Identifiers
Literals
Operators
Punctuators

By Amit Agarwal
Keywords
Are special words that has special meaning to the
compiler
Like : for, if, else…

By Amit Agarwal
Types of Tokens
Keywords
Identifiers
Literals
Operators
Punctuators

By Amit Agarwal
IDENTIFIERS
Python Identifiers are user-defined names to represent a
variable, function, class, module or any other object. If you
assign some name to a programmable entity in Python,
then it is nothing but technically called an identifier.
Best Practices For Identifier Naming.
 It always start with an alphabet or an underscore (_).
 It will never start with a number
 No special symbols are allowed between identifiers
except underscore
 No spaces are allowed.

By Amit Agarwal
Some examples are :
Valid Identifiers
 Name
 name
 name_1
 Int
 INT
 _SUM
 sum_of_the_numbers
 firstName
Invalid identifiers
 int
 ceil
 num^2
 num 1
 2num

By Amit Agarwal
Types of Tokens
Keywords
Identifiers
Operators
Literals
Punctuators

By Amit Agarwal
OPERATORS
1. Arithmetic operators
2. Comparison operators
3. Logical operators
4. Identity operators
5. Assignment operators
6. Membership operators
7. Bitwise operators

By Amit Agarwal
Arithmetic

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

By Amit Agarwal
Comparison operators

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

By Amit Agarwal
Assignment Operators
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&=(AND) x &= 3 x=x&3
|=(OR) x |= 3 x= x|3
^=(XOR) x ^= 3 x=x^3
>>=(RIGHT SHIFT) x >>= 3 x = x >> 3
<<=(LEFT SHIFT) x <<= 3 x = x << 3

By Amit Agarwal
Logical operators

and Returns True if both x < 5 and x < 10


statements are true

or Returns True if one of x < 5 or x < 4


the statements is true

not Reverse the result, not(x < 5 and x < 10)


returns False if the
result is true

By Amit Agarwal
Identity operators

is Returns true if both x is y T


variables are the
same object
is not Returns true if both x is not y
variables are not the
same object

By Amit Agarwal
Membership operators

in Returns True if a sequence x in y


with the specified value is
present in the object

not in Returns True if a sequence x not in y


with the specified value is
not present in the object

By Amit Agarwal
VARIABLES
Are the memory location where values are actually stored
..
Num1 = 2
Num1 -> variable which is stored in memory
2 is the value that is stored in num1
Best Practices For Variable Naming.
 It always start with an alphabet or an underscore (_).
 It will never start with a number
 No special symbols are allowed between identifiers
except underscore
 No spaces are allowed.

By Amit Agarwal
Bitwise operators
& AND Sets each bit to 1 if both bits
are 1
| OR Sets each bit to 1 if one of
two bits is 1
^ XOR Sets each bit to 1 if only one
of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in
from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing copies
of the leftmost bit in from
the left, and let the rightmost
bits fall off

By Amit Agarwal
DATATYPES IN PYTHON
Text Type : string
Numeric Types : int, float, complex
Sequence Types : list, tuple, range
Mapping Type : dictionary
Set Types : set, frozenset
Boolean Type : bool

x=5
print(type(x))

By Amit Agarwal
Syntax of various datatypes
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 3 + 1j complex
x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple


x = range(6) range
x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = True bool

By Amit Agarwal
Taking input from user
input() function

Name = input(“enter any name”)


NUM1=int(input(“enter the number”))

By Amit Agarwal
Conditional Programming
if-else
if condition:
__
__ // statements to execute
__
else:
__
__ // statements to execute
__

By Amit Agarwal
if-elif-else
if condition:
__
__ // statements to execute
__
elif condition :
__
__ // statements to execute
__
else :
__
__ // statements to execute
__

By Amit Agarwal
Iteration in Python

Loops
for
while

By Amit Agarwal
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.
for x in range(6): // range function 0 to (n-1)
print(x)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3):
print(x)

By Amit Agarwal
while Loop
while loop can execute a set of statements as
long as a condition is true.
i=1
while i < 6:
print(i)
i += 1

By Amit Agarwal
Break and continue.
With the break statement we can jump out of the
loop:
i =1
while i <6:
print(i)
if i ==3:
break
i +=1
print("out of loop")
By Amit Agarwal
Continue statement
i =1
while i <6:
i+=1
if i ==3:
continue
print(i)

By Amit Agarwal
List in python
A list is a collection which is ordered and
changeable. In Python lists are written with
square brackets.
thislist = ["apple", "banana", "cherry"]
print(thislist)

By Amit Agarwal
List Length
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
append() method
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Remove Item
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

By Amit Agarwal
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")

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


x = fruits.index("cherry")

By Amit Agarwal
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


By Amit Agarwal
TUPLE
A tuple is a collection which is ordered
and unchangeable. In Python tuples are written
with round brackets.
thistuple = ("apple", "banana", "cherry")
print(thistuple)

By Amit Agarwal
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an error
print(thistuple)

By Amit Agarwal
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where
it was found

By Amit Agarwal
Strings in Python
Strings are the combination of characters.
String literals in python are surrounded by either
single quotation marks, or double quotation
marks.
x= “Amit” or
x=‘Amit’

By Amit Agarwal
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was
found
index() Searches the string for a specified value and returns the position of where it was
found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
lower() Converts a string into lower case
By Amit Agarwal
replace() Returns a string where a specified value is replaced with a specified value

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list


startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

upper() Converts a string into upper case

By Amit Agarwal
eval function
The eval() function evaluates the specified
expression, if the expression is a legal Python
statement, it will be executed.
Syntax: eval(“2 +3”)

By Amit Agarwal
Dynamic Typing
Assigning multiple values to the same variable
and variable takes the last updated value.
x=1
x=1.2
x=“amit”
print(x) //Amit

By Amit Agarwal
Functions in Python
• A function is a block of code which only runs
when it is called.
• You can pass data, known as parameters, into
a function.
• A function can return data as a result.
In Python a function is defined using
the def keyword:

By Amit Agarwal
def my_function():
print("Hello from a function")

my_function()

By Amit Agarwal
Use of parameters
def my_function(fname):
print(fname + " Python")

my_function(“Amit")

By Amit Agarwal
Return values
def my_function(x):
return 5 * x

print(my_function(3))

By Amit Agarwal
Mathematical Functions
The math module is used to access mathematical functions in
the Python.
import math
x=math.sqrt(25)
x

By Amit Agarwal
Sr.No. Constants & Description
1 pi
Return the value of pi: 3.141592
.
2 E
Return the value of natural base e. e is 0.718282
3 tau
Returns the value of tau. tau = 6.283185
4 inf
Returns the infinite
5 nan
Not a number type.

By Amit Agarwal
Sr.No. Function & Description
1 ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number x.

2 copysign(x, y)
It returns the number x and copy the sign of y to x.
3 fabs(x)
Returns the absolute value of x.
4 factorial(x)
Returns factorial of x. where x ≥ 0
5 floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.

6 fsum(iterable)
Find sum of the elements in an iterable object
7 gcd(x, y)
Returns the Greatest Common Divisor of x and y
8 isfinite(x)
Checks whether x is neither an infinity nor nan.
9 isinf(x)
Checks whether x is infinity
10 isnan(x)
Checks whether x is not a number.
11 remainder(x, y)
Find remainder after dividing x by y.

By Amit Agarwal
Sr.No. Function & Description

1 pow(x, y)
Return the x to the power y value.

2 sqrt(x)
Finds the square root of x

3 exp(x)
Finds xe, where e = 2.718281

4 log(x[, base])
Returns the Log of x, where base is given. The default base is e

5 log2(x)
Returns the Log of x, where base is 2

6 log10(x)
Returns the Log of x, where base is 10

By Amit Agarwal
Sr.No. Function & Description

1 sin(x)
Return the sine of x in radians

2 cos(x)
Return the cosine of x in radians

3 tan(x)
Return the tangent of x in radians

4 asin(x)
This is the inverse operation of the sine, there are acos, atan also.

5 degrees(x)
Convert angle x from radian to degrees

6 radians(x)
Convert angle x from degrees to radian

By Amit Agarwal
Insertion Sort
Insertion sort is a simple sorting algorithm that
works the way we sort playing cards in our hands.
for step in range(1, len(array)):
key = array[step]
j = step - 1
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1
array[j + 1] = key

By Amit Agarwal
steps in a nutshell

for i in range(1, len(array)):


key = array[i]
j=i-1
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1
array[j + 1] = key
Let’s say the list is 16, 19,11, 15, 10

step 1 --> i=1 , key = 19 j=0 no swapping


step 2 --> i=2 , key = 11 j=1 swapping 11 16 19 15 10
step 3 --> i=3 , key = 15 j=2 swapping 11 15 16 19 10
step 4 --> i=4 , key = 10 j=3 swapping 10 11 15 16 19

==================end of iteration==================

By Amit Agarwal
Bubble Sort
Starting from the first index, compare the first
and the second elements. If the first element is
greater than the second element, they are
swapped.

Now, compare the second and the third


elements. Swap them if they are not in order.

The above process goes on until the last


element.
By Amit Agarwal
Bubble Sort
The same process goes on for the remaining
iterations. After each iteration, the largest element
among the unsorted elements is placed at the end.

In each iteration, the comparison takes place up to


the last unsorted element.

The array is sorted when all the unsorted elements


are placed at their correct positions.

By Amit Agarwal
Code
a = [16, 19, 11, 15, 10, 12, 14]
#repeating loop len(a)(number of elements) number of times
for j in range(len(a)):
#initially swapped is false
swapped = False
i=0
while i<len(a)-1:
#comparing the adjacent elements
if a[i]>a[i+1]:
#swapping
a[i],a[i+1] = a[i+1],a[i]
#Changing the value of swapped
swapped = True
i = i+1
#if swapped is false then the list is sorted
#we can stop the loop
if swapped == False:
break
print (a)
By Amit Agarwal
By Amit Agarwal
By Amit Agarwal
By Amit Agarwal
Lambda Functions
A lambda function is a small anonymous
function.
A lambda function can take any number of
arguments, but can only have one expression.
Syntax:
lambda arguments : expression

By Amit Agarwal
File Handling in Python
File is a collection of bits and bytes
Two types:
 text and binary
Mode:
r
w
a
open()

By Amit Agarwal
Arrays in Python
An array is a collection of similar elements of
same type. Following are the important terms to
understand the concept of Array.
• Element− Each item stored in an array is called
an element.
• Index − Each location of an element in an
array has a numerical index, which is used to
identify the element.

By Amit Agarwal
• Array Representation
• Arrays can be declared in various ways in
different languages. Below is an illustration.

As per the above illustration, following are the important points


to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
Each element can be accessed via its index. For example, we can
fetch an element at index 6 as 9.

By Amit Agarwal
• Basic Operations
• Following are the basic operations supported by
an array.
• Traverse − print all the array elements one by
one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given
index or by the value.
• Update − Updates an element at the given index.

By Amit Agarwal
Syntax
from array import *
arrayName = array(typecode, [Initializers])
Typecode are the codes that are used to define the type of value
the array will hold. Some common typecodes used are:
Typecode Value
b Represents signed integer of size 1 byte/td>

B Represents unsigned integer of size 1 byte


c Represents character of size 1 byte

i Represents signed integer of size 2 bytes

I Represents unsigned integer of size 2 bytes

f Represents floating point of size 4 bytes

d Represents floating point of size 8 bytes


By Amit Agarwal
from array import *
array1 = array('i', [10,20,30,40,50])
for x in array1:
print(x)

By Amit Agarwal
Insertion
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(1,60)
for x in array1:
print(x)

By Amit Agarwal
Delete Operation
from array import *
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)

By Amit Agarwal
Search Operation
from array import *
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))

By Amit Agarwal
Update Operation
from array import *
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x)

By Amit Agarwal
DATA STRUCTURES
IN PYTHON

By Amit Agarwal
By Amit Agarwal
STACK
A data structure that is based on LIFO policy .
L-> LAST
I -> IN
F-> FAST
O-> OUT

By Amit Agarwal
Operations on STACK
 Creating a stack
 PUSH: insertion in stack
 POP: deletion in stack
 Displaying a stack
Creating an empty stack
STACK= list()
STACK= [ ]

By Amit Agarwal
Algorithm for PUSH operation
1. START
2. Initialize top = -1
3. Element= input(“element to be inserted)
4. Stack.append(element)
5. END

By Amit Agarwal
By Amit Agarwal
Algorithm for POP operation
1. START
2. St_len=len(stack)
3. If st_len=[]
print(“Stack empty”)
go to step 5
4. Element=stack.pop()
5. END

By Amit Agarwal
By Amit Agarwal
# Python program to
# demonstrate stack implementation
# using list
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)

By Amit Agarwal
To add an item to the top of the list, i.e., to push an item,
we use append() function and to pop out an element we
use pop() function..
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
By Amit Agarwal
# Python program to
# demonstrate stack implementation
# using list
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
# pop() fucntion to pop
# element from stack in
# LIFO order
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
By Amit Agarwal
QUEUE
A data structure based on FIFO policy.
F -> First
I -> In
F -> First
O -> Out
Enqueue: Adds an item to the queue. If the queue is
full, then it is said to be an Overflow condition
Dequeue: Removes an item from the queue. The
items are popped in the same order in which they
are pushed. If the queue is empty, then it is said to
be an Underflow condition
Front: Get the front item from queue
Rear: Get the last item from queue

By Amit Agarwal
Diagrammatic Representation

By Amit Agarwal
Creating empty queue
Queue= list() OR
Queue = [ ]

By Amit Agarwal
Algorithm for insertion in queue
1. START
2. element= input(“enter the element”)
3. queue= append(element)
4. STOP

By Amit Agarwal
queue = [ ]
# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)

By Amit Agarwal
Algorithm for deletion in queue
START
if queue==[ ]
print(“queue is empty”)
go to step 4
element=queue.pop(0)
STOP

By Amit Agarwal
queue = [ ]
# Adding elements to the queue
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
# Removing elements from the queue
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
By Amit Agarwal
Dictionary
A dictionary is a collection which is unordered,
changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and
values. Can be regarded as key-value mapping.
syntax
data = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(data)
By Amit Agarwal
Some Operations
Adding elements
del()
zip()
dict()

By Amit Agarwal
Some more methods
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 value

get() Returns the value of the specified key


items() Returns a list containing 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
setdefault() Returns the value of the specified key. If the key does not exist: insert 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

By Amit Agarwal
By Amit Agarwal
By Amit Agarwal
File Handling in Python
File handling is an important part of any web
application.
Python has several functions for creating,
reading, updating, and deleting files.
Why file??
Types:
• Text
• Binary
By Amit Agarwal
File Handling
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename,
and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if
the file does not exist
"a" - Append - Opens a file for appending, creates the file if
it does not exist
"w" - Write - Opens a file for writing, creates the file if it
does not exist
"x" - Create - Creates the specified file, returns an error if
the file exists

By Amit Agarwal
f = open("demofile.txt", "r")
f = open("demofile.txt", “w")

To open the file, use the built-in open() function.


The open() function returns a file object, which has
a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())

By Amit Agarwal
Read Lines
You can return one line by using
the readline() method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())

By Amit Agarwal
Close Files
It is a good practice to always close the file when
you are done with it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
By Amit Agarwal
Write to an Existing File
To write to an existing file, you must add a
parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
By Amit Agarwal
By Amit Agarwal
By Amit Agarwal
The write() Method

It writes the contents to the file in the form of string. It does


not return value. Due to buffering, the string may not actually
show up in the file until the flush() or close() method is called.

The read() Method

It reads the entire file and returns it contents in the form of a


string. Reads at most size bytes or less if end of file occurs.if
size not mentioned then read the entire file contents.

By Amit Agarwal
Binary File
"Binary" files are any files where the format
isn't made up of readable characters. Binary
files can range from image files like JPEGs or
GIFs, audio files like MP3s or binary document
formats like Word or PDF.

By Amit Agarwal
Binary File
Sr. No Mode & Description
. r - reading only. Sets file pointer at beginning of the file . This is the default mode.
rb – same as r mode but with binary file
r+ - both reading and writing. The file pointer placed at the beginning of the file.
rb+ - same as r+ mode but with binary file
w - writing only. Overwrites the file if the file exists. If not, creates a new file for
writing.
wb – same as w mode but with binary file.
w+ - both writing and reading. Overwrites . If no file exist, creates a new file for R
& W.
wb+ - same as w+ mode but with binary file.
a -for appending. Move file pointer at end of the file.Creates new file for writing,if
not exist.
ab – same as a but with binary file.
a+ - for both appending and reading. Move file pointer at end. If the file does not
exist, it creates a new file for reading and writing.
By Amit Agarwal
ab+ - same as a+ mode but with binary mode.
Getting & Resetting the Files Position
The tell() method of python tells us the current position within the file,where as The seek(offset[,
from]) method changes the current file position. If from is 0, the beginning of the file to seek. If it is
set to 1, the current position is used . If it is set to 2 then the end of the file would be taken as seek
position. The offset argument indicates the number of bytes to be moved.
e.g.program
f = open("a.txt", 'w')
line = 'Welcome to python.mykvs.in\nRegularly visit python.mykvs.in'
f.write(line)
f.close()
f = open("a.txt", 'rb+')
print(f.tell())
print(f.read(7)) # read seven characters
print(f.tell())
print(f.read())
print(f.tell())
f.seek(9,0) # moves to 9 position from begining print(f.read(5))
f.seek(4, 1) # moves to 4 position from current location print(f.read(5))
f.seek(-5, 2) # Go to the 5th byte before the end
print(f.read(5))
By Amit Agarwal
f.close()
Methods of os module
The rename() method used to rename the file. syntax
os.rename(current_file_name, new_file_name)
The remove() method to delete file.
syntax
os.remove(file_name)
3.The mkdir() method of the os module to create directories in the current directory.
syntax
os.mkdir("newdir")
4.The chdir() method to change the current directory.
syntax
os.chdir("newdir")
5.The getcwd() method displays the current directory. syntax
os.getcwd()
The rmdir() method deletes the directory. syntax
os.rmdir('dirname')

By Amit Agarwal
e.g.program
import os
os print(os.getcwd())
os.mkdir("newdir")
os.chdir("newdir")
print(os.getcwd())

By Amit Agarwal
PICKLING AND UNPICKLING
Python pickle module is used for serializing and
de-serializing python object structures. The
process to converts any kind of python objects
(list, dict, etc.) into byte streams (0s and 1s) is
called pickling or serialization or flattening or
marshalling. We can converts the byte stream
(generated through pickling) back into python
objects by a process called as unpickling.

By Amit Agarwal
By Amit Agarwal
Pickle a simple list:
import pickle mylist = ['a', 'b', 'c', 'd']
with open('datafile.txt', 'wb') as fh:
pickle.dump(mylist, fh)
In the above code, list – “mylist” contains four
elements (‘a’, ‘b’, ‘c’, ‘d’). We open the file in “wb”
mode instead of “w” as all the operations are done
using bytes in the current working directory. A new
file named “datafile.txt” is created, which converts
the mylist data in the byte stream.
By Amit Agarwal
Unpickle a simple list:
import pickle
pickle_off = open ("datafile.txt", "rb")
emp = pickle.load(pickle_off)
print(emp)

By Amit Agarwal
Working on CSV files
A CSV file (Comma Separated Values file) is a
type of plain text file that uses specific
structuring to arrange tabular data. Because it’s
a plain text file, it can contain only actual text
data—in other words,
printable ASCII or Unicode characters.

By Amit Agarwal
delimiter specifies the character used to separate
each field. The default is the comma (',').
import csv
with open('test.csv','w',newline="") as fp:
a=csv.writer(fp,delimiter=',')
data=[['name','age'],
['Amit','30']]
a.writerows(data)

print("success")

By Amit Agarwal
Writing CSV File From a Dictionary
With csv
Since you can read our data into a dictionary, it’s
only fair that you should be able to write it out
from a dictionary as well:
import csv
with open('employee_file2.csv', mode='w') as csv_file: fieldnames = ['emp_name', 'dept',
'birth_month']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader()
writer.writerow({'emp_name': 'John Smith', 'dept': 'Accounting', 'birth_month': 'November'})
writer.writerow({'emp_name': 'Erica Meyers', 'dept': 'IT', 'birth_month': 'March'})

By Amit Agarwal
Writing CSV Files With csv
You can also write to a CSV file using
a writer object and the .write_row() method:
import csv
with open('employee_file.csv', mode='w') as employee_file:
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
employee_writer.writerow(['John Smith', 'Accounting', 'November'])
employee_writer.writerow(['Erica Meyers', 'IT', 'March'])

By Amit Agarwal
Random function in python
Description
Python number method random() returns a
random float r, such that 0 is less than or equal
to r and r is less than 1.
Syntax
Following is the syntax for random() method −
random ( )

By Amit Agarwal
Thanks
Amit Agarwal
DR MPS WORLD SCHOOL,
Agra

By Amit Agarwal

You might also like