Basic Notes of Python
Basic Notes of Python
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
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
By Amit Agarwal
Identity operators
By Amit Agarwal
Membership operators
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 = True bool
By Amit Agarwal
Taking input from user
input() function
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")
By Amit Agarwal
Method Description
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
By Amit Agarwal
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
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
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
==================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.
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.
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>
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
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")
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
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