Python Notes
Python Notes
Python Notes
Course Notes
Gaurav Singh
Department of Computer Science,
Microtek College of Management & Technology
12-Jan-2023
PYTHON
Guido van Rossum did not develop and evolve all the python components
himself. Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc.).
• Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
Data science
Web development
Computer graphics
Literal / Constant
● Literal is a fixed data element or values of program like - 25, 3.5,
"Hello"
Character Set
Identifier
Python Installation
To check if you have python installed on a Windows PC, search in the start
bar for Python or run the following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open
the command line or on Mac open the Terminal and type:
python --version
If you find that you do not have python installed on your computer, then you
can download it for free from the following website:
https://www.python.org
Example
if 5 > 2:
Getting The Data Type :You can get the data type of any object By Using
The type() Function:
Example
x=5
print(type(x))
Variable declaration
Example
x=5
print(x)
Output
Here x = 5 i.e, is integer value and to confirm the integer variable, in python
allows type function
print(type(x))
Output:
<class 'int'>
a=5.5
Here a = 5.5 i.e, is float value and to confirm the float variable, in python
allows type function
print(type(a))
Output:
<class 'float'>
a=’2.6’
Here a = ‘2.6’ i.e, s String value because it is written with coat (‘ ‘). And to
confirm the String variable, in python allows type function
print(type(a))
Output:
<class 'str'>
Example
a="17"
b="26"
c=a+b
print(c)
Output
1726
In above given variable a and b both are string data type which is assigned
the value with double quotes (" ") when the value is added it into c=a+b
then result comes as concatenation
Example
print(type(c))
Output:
<class 'str'>
int() Function
Example
a="17"
b="26"
c=int(a)+int(b)
print(c)
Output:
43
Python Indentation
Example
if 5 > 2:
if 5 > 2:
Creating a Comment
Python does not really have a syntax for multi line comments. To add a
multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
print("Hello, World!" Or, not quite as intended, you can use a multiline
string.
Variable Names A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume). Rules for Python variables:
• Variable names are case-sensitive (age, Age and AGE are three different
variables)
Example
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
2myvar = "John"
my-var = "John"
my var = "John"
print(x)
print(y)
print(z)
And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange
print(x)
print(y)
print(z)
Output Variables
The Python print statement is often used to output variables. To combine
both text and a variable, Python uses the + character:
Example
You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome"
z=x+y
print(z)
Global Variables
that are created outside of a function (as in all of the examples above) are
known as global variables. Global variables can be used by everyone, both
inside of functions and outside.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Python List :
x = [3,1,4,2]
print(x)
output :
[3,1,4,2]
Here x = [3,1,4,2] i.e, is list value in integer format. And to confirm the
integer variable into list data type, in python
print(type(x))
output :
<class 'list'>
List Methods
Python has a set of built-in methods that you can use on lists.
Lists are mutable, and hence, they can be altered even after their creation.
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
Python Tuples
Tuple
Example
Create a Tuple:
print(m)
You can access tuple items by referring to the index number, inside square
brackets:
Example
print(m[1])
output :
banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item,
-2 refers to the second last item etc.
Example
print(x[-1])
output :
cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where
to end the range. When specifying a range, the return value will be a new
tuple with the specified items.
Example
print(x[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not
included).
Specify negative indexes if you want to start the search from the end of the
tuple:
Example
-7 -6 -5 -4 -3 -2 -1
print(x[-4:-1])
Set Declaration
print(set1)
output :
The update() method updates the current set, by adding items from
another set (or any other iterable).
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Output:
{'a', 'b', 1, 2, 3, 'c'}
Return a set that contains all items from both sets, duplicates are excluded:
set2 = {"z","y","x"}
set3=set1.union(set2)
print(set3)
Output :
issubset() method
The issubset() method returns True if set A is the subset of B, i.e. if all the
elements of set A are present
a={1,2,5,4,8}
b={2,4,3,6,9}
c=a.issubset(b)
print(c)
output:
False
issuperset() Method
z = x.issuperset(y)
print(z)
Output :
True
Return a set that contains the items that exist in both set x, and set y:
z = x.intersection(y)
print(z)
Output :
{'apple'}
t = x.intersection(y, z)
print(t)
Output :
{‘c’}
Algorithm
Algorithm is a step-by-step procedure, which defines a set of instructions to
be executed in a certain order to get the desired output.
From the data structure point of view, following are some important
categories of algorithms −
Characteristics of an Algorithm
steps (or phases), and their inputs/outputs should be clear and must lead to
Example 1
Step 1: Start
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 6: Stop
Example 2
Step 1: Start
Step 4: If a > b
If a > c
Else
Else
If b > c
Display b is the largest number.
Else
Step 5: Stop
largest = 0
largest = a
largest = b
largest = c
Range Function
We can also define the start, stop and step size as range(start,
stop,step_size). step_size defaults to 1 if not provided.
To force this function to output all the items, we can use the function list()
Example :
>>>print(range(10))
range(0,10)
>>>print(list(range(10)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>print(list(range(2,10)))
[2, 3, 4, 5, 6, 7, 8, 9]
Len Function
print(len(x))
Output :
List Slicing :
print(thislist[2:])
Output
print(thislist[-3:-1])
Output:
['kiwi', 'melon']
print(thislist[-7:-1:2])
Output:
Example
m = range(10)
print(list(m[2::2]))
m= 0 1 2 3 4 5 6 7 8 9 10
0 1 2 1 2 1 2 1 2
0 2 4 6
Output :
[2, 4, 6, 8]
Example
m=range(1,14,2)
print(list(m[3::-2]))
here in range function start value is 1 and stop value is 14 and step value is
2
so stop will be -1 hence elements will be from 1 to 13 with 2 step value.
m= 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 1 2 3 4 5 6 7 8 9 10 11 12 13
1 3 5 7 9 11 13
0 1 2 3 4 5 6
-2 -1 0
So in question m[3::-2] which means it’ll start from 3 rd position and i.e, 7
and -2 which is negative value and start from reverse order
Output:
[7, 3]
Example
s="MICROTEK COLLEGE"
z=len(s)
m=range(3,z,2)
print(list(m[2::-2]))
Solution
S= M I C R O T E K C O L L E G E
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
In eq1. Range starts from 3 position and z=16 which is stop-1 i.e., 15 and
step value is 2 so m will be in Eq2.
Eq2.
m= 3 5 7 9 11 13 15
0 1 2 3 4 5 6
Eq3. list(m[2::-2])
Here in Eq. 3 start value 2 position of Eq2. and stop value is -2 position
means reverser order.
m= 3 5 7 9 11 13 15
0 1 2 3 4 5 6
-2 -1 0
Output :
[7,3]
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).
This is less like the for keyword in other programming languages, and
works more like an iterator method as found in other object-orientated
programming languages.
The for loop in Python is used to iterate over a sequence (list, tuple, string)
or other Iterate objects. Iterating over a sequence is called traversal.
Example
x=0
for i in range(6):
x=x+i
print(x,end=” “)
Solution
x is printing loop
1 : step > x = x + i = 0 + 0
2 : step > x = x + i = 0 + 1
0, 1
3 : step > x = x + i = 1 + 2
0, 1, 3
4 : step > x = x + i = 3 + 3
0, 1, 3, 6
5 : step > x = x + i = 6 + 4
0, 1, 3, 6, 10
6 : step > x = x + i = 10 + 5
0, 1, 3, 6, 10, 15
Output:
0, 1, 3, 6, 10, 15
Example
for i in range(10):
print(i,end=” “)
Output:
0123456789
Example
x=[4,5,1,7,9,12,8]
z=len(x)
for i in range(z):
print(x[i],end=” “)
Output:
4 5 1 7 9 12 8
Example
for i in range(1,11):
x = i*num
print(x)
#in above program num will store input value suppose num = 2
Output:
Enter number:2
10
12
14
16
18
20
Example
fact = 1
for i in range(1,6):
fact = fact * i
print(fact,end=" ")
#Here fact variable storing the multiply with fact * I into the loopi = 1
Output:
1 2 6 24 120
x=[4,5,1,7,9,12,8]
z=len(x)
c=0
for i in range(z):
c+=x[i]
print(c)
Output :
46
x=[4,5,1,7,9,12,8]
z=len(x)
for i in range(z-1,-1,-1):
print(x[i],end=" ")
Output:
8 12 9 7 1 5 4
x=[4,5,1,7,9,12,8]
z=len(x)
for i in range(z,0,-1):
print(x[i-1],end=" ")
Output
8 12 9 7 1 5 4
Example
for i in range(len(genre)):
print("I like",genre[i])
Output:
I like pop
I like rock
I like jazz
Example
x = [4,1,7,9,3]
z=len(x)
for i in range(z-1,-1,-1):
print(i,"=","x[",i,"]","=",x[i])
Output:
4 = x[ 4 ] = 3
3 = x[ 3 ] = 9
2 = x[ 2 ] = 7
1 = x[ 1 ] = 1
0 = x[ 0 ] = 4
Example
x = [4,1,7,9,3]
z=len(x)
for i in range(z+1-2,1-2,-1):
print(i,"=","x[",i,"]","=",x[i])
Output:
4 = x[ 4 ] = 3
3 = x[ 3 ] = 9
2 = x[ 2 ] = 7
1 = x[ 1 ] = 1
0 = x[ 0 ] = 4
Add Function
To add an item to the end of the list, use the append() method:
Example
thislist.append("orange")
print(thislist)
Output:
Example
b = [[9,6],[4,5],[7,7]]
x = b[:2]
x.append(10)
print(x)
Output:
Example
b = [[9,6],[4,8],[7,7]]
x = b[:2]
x[1].append(10)
print(x)
Output
Insert Function
Example
thislist.insert(1, "orange")
print(thislist)
Output:
Remove Function
Example
thislist.remove("banana")
print(thislist)
Output:
['apple', 'cherry']
pop function
The pop() method removes the specified index, (or the last item if index is
not specified):
thislist.pop()
print(thislist)
Output:
['apple', 'banana']
del Keyword
del thislist[0]
print(thislist)
Output:
['banana', 'cherry']
Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only
be
There are ways to make a copy, one way is to use the built-in List method
copy().
thislist[1] = "blackcurrant"
print(thislist)
Output:
Enumerate allows you to loop through a list, tuple, dictionary, string, and
gives the values along with the index.
To get index value using for-loop, you can make use of list.index(n).
However, list.index(n) is very expensive as
it will traverse the for-loop twice. Enumerate is very helpful in such a case
as it gives the index and items at one go.
Example
>>>mylist = ["a","b","c","d"]
>>>urlist = enumerate(mylist)
>>>print(list(urlist))
Output:
Example
print (ele,end=” “)
Output:
(0, 'eat') (1, 'sleep') (2, 'repeat')
Format function
The format() method formats the specified value(s) and insert them inside
the string's placeholder.
The placeholder is defined using curly brackets: {}. Read more about the
placeholders in the Placeholder section below.
Example
print(txt.format(price = 49))
Output:
Example
Output:
President 1: Washington
President 2: Adams
President 3: Jefferson
President 4: Madison
President 5: Monroe
President 6: Adams
President 7: Jackson
sleep function
The sleep() function suspends (waits) execution of the current thread for a
given number of seconds.
Python has a module named time which provides several useful functions
to handle time-related tasks. One of the popular functions among them is
sleep().
Example
import time
time.sleep( 1 )
Output:
Example
import time
list1=[1,2,3,4,5,6,7,8,9,10]
for i in list1:
print(i,end=", ")
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Example
import time
x="Gaurav"
for i in x:
time.sleep(1)
print(i,end=" ")
#In above loop x will transfer each character to i i.e, and i value will display
in every one second : G a u r a v
Equals: a == b
Not Equals: a != b
Example:
Equals: a == b
Not Equals: a != b
Example
x=5
if x > 0:
print("Microtek") #True
else:
print("College") #False
Output:
Microtek
Example
if condition with elif
x=5
if x < 0:
print("Microtek")
elif x > 0:
print("College")
else:
print("Gaurav")
Output:
College
Example
a=5
b=17
c=11
else:
Output:
Example
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Output:
Enter a number: 15
15 is Odd
Or
Example
a = 200
b = 33
c = 500
if a > b or a > c:
Example
At least one of the conditions is True
extend() Function
print(list1)
Output:
['a', 'b', 'c', 1, 2, 3]
split() Function
Split a string into a list where each word is a list item and converts into list:
Example
string = "one,two,three"
words = string.split(',')
print(words)
Output:
['one', 'two', 'three']
Example
web_addr = ["address1.com", "address2.org", None, "address3.in"]
for addr in web_addr:
if addr is not None:
print(addr.split("."))
Output:
['address1', 'com']
['address2', 'org']
['address3', 'in']
Example
if condition with conditional statement for Even and Odd Value into list.
x=[4,8,13,15,9,2]
z=len(x)
for m in x:
if m%2==False:
print("Even",m)
elif m%2!=False:
print("odd",m)
Output:
Even 4
Even 8
odd 13
odd 15
odd 9
Even 2
Example
Fibonacci series
a=0
b=1
print(a,b,end=" ")
num = int(input("Enter any No.:"))
for i in range(1,num):
c=a+b
a=b
b=c
print(c,end=" ")
Solution :
Suppose num = 6:
i start at 1
1 : step > c = 0 + 1 = 1
a=1
b=1
print c --> 1
i start at 2
2 : step > c = 1 + 1 = 2
a=1
b=2
print c --> 1 2
i start at 3
3 : step > c = 1 + 2 = 3
a=2
b=3
print c --> 1 2 3
i start at 4
4 : step > c = 2 + 3 = 5
a=3
b=5
i start at 5
5: step > c = 3 + 5 = 8
a=5
b=8
print c --> 1 2 3 5 8
Output:
0 1 Enter any No.:6
12358
String Slicing
fruit = "banana"
print(fruit[:3])
print(fruit[3:])
Solution
b a n a n a
0 1 2 3 4 5
When we write [:3] means starting value start is null means by default it’ll
start from index position 0 here stop-1 is 3-1=2 position value print
ban
When we write [3:] means starting value start is null means by default it’ll
start from index position 3 here stop value is not assign
ana
Output:
ban
ana
While Loop
A while loop will always first check the condition before running. in
programming language some time needs to repeat statement
so the repetition will allow with loop or without loop means copy & paste
If the condition evaluates to True then the loop will run the code within the
loop's body.
So, suppose u want to print "Hello world" 5 times
Example
i=1
while i<=5:
print("Hello World:")
i +=1
Output:
Hello World:
Hello World:
Hello World:
Hello World:
Hello World:
Example
i=1
while i < 6:
print(i,end=" ")
i = i+1
Output:
12345
Example
n=5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('Loop ended.')
Output:
4
3
Loop ended.
Example to display string through while loop
x="MICROTEK COLLEGE"
i=0
while i < len(x):
print(x[i],end=" ")
i += 1
Output:
MICROTEK COLLEGE
Example
While loop using pop method
a = [1, 2, 3, 4]
while a:
print(a.pop(),end=" ")
print(a)
Output:
4 3 2 1 []
Example
x="MICROTEK"
z=len(x)
while z > 0:
print(x[z-1],end=" ")
z-=1
Solution:
M I C R O T E K
1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7
Output:
KETORCIM
s=list()
i=1
while i < 5:
val=int(input("enter the value :"))
s.append(val)
i +=1
print(s,end=" ")
Output:
enter the value :5
enter the value :2
enter the value :3
enter the value :7
[5, 2, 3, 7]
Example
Write a program to take input value and from input value display table.
a=int(input("enter table number"))
i=1
num = 0
while i<=10:
num = a * i
print(a,"x",i,"=",num)
i=i+1
Output
enter table number2
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
Example
Write a program which takes three input and display into list and display
total and average value
c=[]
i=0
m=0
sum=0
avg=0
while i < 3:
val=int(input("Enter the Value.."))
c.append(val)
i +=1
print(c)
z=len(c)
i=0
while i < z:
sum +=c[i]
avg=sum/z
i+=1
print("Total Value :",sum)
print("Average :",avg)
Output:
Enter the Value..4
Enter the Value..2
Enter the Value..6
[4, 2, 6]
Total Value : 12
Average : 4.0
for i in range(4):
print("\n")
for j in range(4):
print("#",end=" ")
Output:
####
####
####
####
Example 2
for i in range(4):
print("\n")
for j in range(i+1):
print("#",end=" ")
Output:
#
##
###
####
Example 3
for i in range(4):
print("\n")
for j in range(4-i):
print("#",end=" ")
Output:
####
###
##
Example
n = int(input("Enter any Value:"))
for i in range(n):
print("\n")
for j in range(i+1):
print(j+1,end=" ")
suppose n = 4
Output:
12
123
1234
Example
for i in range(n):
print()
for j in range(n-i-1):
print(" ",end=" ")
for j in range(i+1):
print(j+1,end=" ")
Output:
1
12
123
1234
Example
Write a program to check value number is Prime or Not Prime.
num=12
temp=0
for i in range(2,num):
if num%i==0:
temp=1
break
if temp == 1:
print("given number is not prime")
else:
print("given number is prime")
Output:
given number is not prime
i=0
while i < 4 :
j=0
while j < 4 :
print("*", end=" ")
j += 1
print()
i += 1
Output:
****
****
****
****
i=0
Example
while i < 4 :
j=0
while j < i+1 :
print("*", end=" ")
j += 1
print()
i += 1
Output:
*
**
***
****
Example
i=1
while i <= 5:
print()
print("Microtek ",end=" ")
i=i+1
j=1
while j <= 4:
print("College ",end=" ")
j=j+1
Output:
Microtek College College College College
Microtek College College College College
Microtek College College College College
Microtek College College College College
Microtek College College College College
Dictionary :
Note – Dictionary keys are case sensitive, the same name but different
cases of Key will be treated distinctly.
student_age = {'Jack': 25, 'Ritika': 15, 'Jack' : 28}
print(student_age)
Output:
{'Jack': 28, 'Ritika': 15}
Example
x={"A":98,"B":5,"C":7,"D":4}
print(x)
Output:
{'A': 98, 'B': 5, 'C': 7, 'D': 4}
Example
print(x["C"])
Output:
7
The get() method returns the value of the item with the specified key.
x={"A":98,"B":5,"C":7,"D":4}
print(x.get("B"))
Output:
5
Example
my_dict = {'name': 'Jack', 'age': 26}
print(my_dict['name'])
Output:
Jack
zip function:
The zip() function returns a zip object, first item in each passed iterator is
paired together,
and then the second item in each passed iterator are paired together etc.
Example
keys = ["Navin","Kiran","Harsh"]
values = ["Python","Java","JS"]
data = dict(zip(keys,values))
print(data)
Output:
{'Navin': 'Python', 'Kiran': 'Java', 'Harsh': 'JS'}
Example
Add element in Dictionary
data["manoj"]="CS"
print(data)
Output:
Example
prog =
{'JS':'manoj','CS':'VS','python':['pycharm','jupiter'],'java':{'JS':'VS','JSP':'Eclip
se'}}
print(prog)
Output:
{'JS': 'manoj', 'CS': 'VS', 'python': ['pycharm', 'jupiter'], 'java': {'JS': 'VS',
'JSP': 'Eclipse'}}
Example
prog =
{'JS':'manoj','CS':'VS','python':['pycharm','jupiter'],'java':{'JS':'VS','JSP':'Eclip
se'}}
print(prog['python'])
Output:
['pycharm', 'jupiter']
Example
Output:
{0: ‘A’, 1: ‘B’, 2: ‘C’, 3: ‘D’}
list1 = salary.values()
print(list1)
Output:
dict_values([50000, 60000, 5000])
keys Function with dictionary
Example
Output:
['x', 'y', 'z']
Functions that readily come with Python are called built-in functions. If we
use functions written by others in the form of library, it can be termed as
library functions.
Creating a Function
# Declaring a function
def fun():
print("Welcome to Microtek")
fun() #this is prototype name of function declaration and while it is calling
function
Output:
Welcome to Microtek
Parameterized Function
The function may take arguments(s) also called parameters as input within
the opening and closing parentheses, just after the function name followed
by a colon.
Syntax:
def evenOdd( x ):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code
evenOdd(2)
evenOdd(3)
Output:
even
odd
Example
def add(a,b):
c=a+b
print(c)
add(10,23)
Position:
def persone(name,age):
print(name)
print(age)
persone("amit",23)
Output:
amit
23
def persone(name,age):
print(name)
print(age)
persone(age=23,name="amit")
Output:
amit
23
Default argument:
def persone(name,age):
print(name)
print(age)
persone("manoj")
def persone(name,age=22):
print(name)
print(age)
persone("manoj")
#so in above program if we're not passing argument then actual function
will assign default value in age variable.
Output:
manoj
22
Variable length :
It may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments. An asterisk (*) is placed before the variable name that
holds the values of all nonkeyword variable arguments. This tuple remains
empty if no additional arguments are specified during the function call.
def add(a,*b):
c=a
for i in b:
c=c+i
print(c)
add(5,6,34,78)
Output:
123
Example
def calculateTotalSum(*arguments):
totalSum = 0
for number in arguments:
totalSum += number
print(totalSum)
# function call
calculateTotalSum(5,4,3,2,1)
Output:
15
Example
def getstudent(**args):
for key,value in args.items():
print("%s=%s" %(key,value))
getstudent(naveen=54,suresh=62,manish=73)
Output:
naveen=54
suresh=62
manish=73
Example
Write a program in function, which return the value
def addsum(x, y):
res = x + y
return res
num1 = int(input("enter First No. :"))
num2 = int(input("enter Two No. :"))
m = addsum(num1, num2)
print("the sum of two ",m)
Output:
enter First No. :16
enter Two No. :25
the sum of two 41
Example
Function in Factorial
def fact(x):
i=1
fact = 1
while i <= x:
fact = fact * i
print(fact,end=" ")
i +=1
m = int(input("enter any Number :"))
fact(m)
Output:
enter any Number :6
1 2 6 24 120 720
Example
Write a program which takes input from user and display the value is Prime
or Not Prime
def prime(num):
count=0
for i in range(2,num):
if num%i==0:
print("not prime.")
break
else:
print("Prime..")
x=int(input("Enter value:"))
prime(x)
Output:
Enter value:19
Prime..
Example
Write a program which takes input from user and display the series of
prime number of input value.
def check(num):
for i in range(2,num):
if num%i==0:
break
else:
print(num,end=" ")
x=int(input("Enter value:"))
for m in range(2,x):
check(m)
Output:
Enter value:10
2357
Array
An array is a collection of items stored at contiguous memory locations.
The idea is to store multiple items of the same type together.
In python the size of array is not fixed. Array can increase or decrease their
size dynamically.
Array and List are not same. Python arrays store homogenous values only
Note : Python does not Multi Dimensional Array But we can create Multi
Dimensional Array Using Third Party packages like numpy
Array :
import array
std_roll = array.array('i',[101,102,103,104,105])
print(std_roll[0])
Output :
101
Backward Index :
import array as arr
std_roll = arr.array('i',[101,102,103,104,105])
print(std_roll[-2])
print(std_roll[-5])
Output:
104
101
The del keyword is used for removing the entire object from the memory
location as well as delete
any specific element
Output:
array('i', [101, 102, 103, 104, 105])
after delete array array('i', [101, 103, 104, 105])
Output:
array('i', [101, 102, 103, 104, 105])
after delete array array('i', [101, 102, 103, 105])
using the remove() method:
Output:
array('i', [101, 102, 103, 104, 105])
after delete array array('i', [101, 102, 104, 105])
s = set(std_roll)
print("original Array :",s)
s.discard(104)
print("After removing :",s)
Output:
original Array : {101, 102, 103, 104, 105}
After removing : {101, 102, 103, 105}
without Index
import array
std_roll = array.array('i',[101,102,103,104,105])
for x in std_roll:
print(x,end=" ")
Output:
101 102 103 104 105
With Index
Output:
101 102 103 104 105
Slicing on Arrays
Slicing on arrays can be used to retrieve a piece of the array that can be
group of elements. Slicing is useful to retrieve a range of element
Output:
0 = 101
1 = 102
2 = 103
3 = 104
4 = 105
--Slicing--
102 103
Example
Program in User input the integer Value in Array :
for i in std_roll:
print(i,end=" ")
Output:
Enter any size of Array :5
Enter Value :1
1
Enter Value :2
12
Enter Value :3
123
Enter Value :4
1234
Enter Value :5
12345
#Array form data from user input and display into list
Output:
Enter any size of Array :4
Enter the Value.2
[2, 6, 1, 7]
Program of sum of array.
Output:
Enter any size of Array :4
Enter Value :3
3
Enter Value :2
32
Enter Value :1
321
Enter Value :4
3214
4
Value are : 3
Value are : 2
Value are : 1
Value are : 4
def check(n):
dicts={}
m = arr.array('i',[])
c=[]
for i in range(n):
val=int(input("Enter the Value" ))
m.append(val)
#print(m)
for t in m:
c.append(t)
print(c)
# z=list(map(str,list(c)))
g=[str(k) for k in list(c)]
print(g)
Output:
Enter the Array Size 4
Enter the Value8
Enter the Value6
Enter the Value5
Enter the Value3
[8, 6, 5, 3]
['8', '6', '5', '3']
Numpy
Numpy is a Python package which stands for "Numerical Python". This was
created by
Travis Oliphant.
Numpy is the core library for scientific computing in Python.
It provides a high performance multidimensional Array object, and tools for
working with these Array.
NumPy is often called as an alternate for MatLab(a programming Plateform
designed specifically for
engineers and scientists for Data Analysis etc. Developing Algorithms,
create Model and Application
etc.
Shortcuts to Remember :
1- To Run program You have written Press : Cnt + Enter.
2- To Run Command as Well as Insert a Cell Below : Shift + Enter.
3- To Insert a Cell below Just Press "b"
To Delete a Cell - Press Esc button ( to go to Command Mode as in Edit
mode You can not delete the Cell ) and then "d" two times
The first reason to prefer python NumPy arrays is that it takes less memory
than the python list.
Then, it is fast in terms of execution, and at the same time, it is convenient
and easy to work with it.
Example
import numpy as np
arr = np.array([5,2,4,9,1])
arr = arr + 5
print(arr)
Output:
[10 7 9 14 6]
Example
Insert the list value into the position value
x.insert(2, [0,5,11,13,6])
for r in x:
for c in r:
print(c,end = " ")
print()
Output:
11 12 5 2
15 6 10
0 5 11 13 6
10 8 12 5
12 15 8 6
Example
Updating Values
We can update the entire inner array or some specific data elements of the
inner array by reassigning the values using the array index.
T[2] = [11,9]
T[0][3] = 7
for r in T:
for c in r:
print(c,end = " ")
print()
Output:
11 12 5 7
15 6 10
11 9
12 15 8 6
Output:
When the above code is executed, it produces the following result −
11 12 5 2
15 6 10
10 8 12 5
Example
Addition of two array
import numpy as np
arr1 = np.array([[1, 2, 3, 4]])
arr2 = np.array([[5, 6, 9, 8]])
arr3 = arr1 + arr2
print(arr3)
Output:
[[ 6 8 12 12]]
Example
Display the square root in array
from numpy import *
#import numpy as np
arr1 = np.array([5,2,4,7,1])
print(sqrt(arr1))
Output
[2.23606798 1.41421356 2. 2.64575131 1. ]
Python – Itertools.Product()
itertools.product() is used to find the cartesian product from the given
iterator, output is lexicographic ordered. The itertools.product() can used in
two different ways:
itertools.product(*iterables, repeat=1):
It returns the cartesian product of the provided iterable with itself for the
number of times specified by the optional keyword “repeat”. For example,
product(arr, repeat=3) means the same as product(arr, arr, arr).
itertools.product(*iterables):
It returns the cartesian product of all the iterable provided as the argument.
For example, product(arr1, arr2, arr3).
Example
from itertools import product
import numpy as np
np.array(list(product(range(3), range(3))))
Output:
array([[0, 0],
[0, 1],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 0],
[2, 1],
[2, 2]])
Example
import numpy as np
np.array(list(product(range(1,3), range(1,3))))
Output:
array([[1, 1],
[1, 2],
[2, 1],
[2, 2]])
Example
from itertools import product
def cartesian_product(arr1, arr2):
# Driver Function
if __name__ == "__main__":
arr1 = [1, 2, 3]
arr2 = [5, 6, 7]
print(cartesian_product(arr1, arr2))
Output:
[(1, 5), (1, 6), (1, 7), (2, 5), (2, 6), (2, 7), (3, 5), (3, 6), (3, 7)]
Example
import numpy as np
for m in np.ndindex(3,2):
print(m)
Output:
(0, 0)
(0, 1)
(1, 0)
(1, 1)
(2, 0)
(2, 1)
In this case, we use the ndindex function to get the index of the elements in
an array of shapes (3,2).
Shape of an Array
NumPy arrays have an attribute called shape that returns a tuple with each
index having the number of corresponding elements.
Example
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
Output:
(2, 4)
Example
import numpy as np
arr = np.array([[1,2,3], [4,5,6]])
for m in np.ndindex((arr.shape)):
print(m)
Output:
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)
Reshaping arrays
Reshaping means changing the shape of an array.
The shape of an array is the number of elements in each dimension.
By reshaping we can add or remove dimensions or change number of
elements in each dimension.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
x = arr.reshape(4, 3)
print(x)
Output:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
ndmin
Specifies minimum dimensions of resultant array
Example
Create an array with 5 dimensions using ndmin using a vector with values
1,2,3,4 and verify that last dimension has value 4:
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', arr.shape)
Output:
[[[[[1 2 3 4]]]]]
shape of array : (1, 1, 1, 1, 4)
Example
Insert the value for 2D Array in the form of Matrix through function
import numpy as np
def funcarr(row,col):
matrix=[]
for i in range(row):
a=[]
for j in range(col):
val = int(input("Enter the Number: "))
a.append(val)
matrix.append(a)
arr=np.array(matrix)
#print(arr)
m=[]
for i in range(row):
c=[]
for j in range(col):
#print(arr[i][j],end=" ")
c.append(arr[i][j])
m.append(c)
print(m)
Output:
Enter the Row Number: 2
Enter the Column Number: 2
Enter the Number: 1
Enter the Number: 2
Enter the Number: 3
Enter the Number: 4
[[1, 2], [3, 4]]
File Handling
till we've learn so many program in Python
whenever we execute any Program then output comes but when we close
the Program
Output doesn't store any where. so for this reasone we need File handling
for save the records as like output.
File Handling
Python too 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. The concept of file
handling has stretched over various other languages,
but the implementation is either complicated or lengthy, but like other
concepts of Python, this concept here is also easy and short.
Python treats files differently as text or binary and this is important.
File Handling
|
--------------------------------
| |
Text File Binary File
The open command will open the file in the read mode and the for loop will
print each line present in the file.
Before performing any operation on the file like reading or writing, first, we
have to open that file.
For this, we should use Python’s inbuilt function open() but at the time of
opening, we have to specify
the mode, which represents the purpose of the opening file.
f = open(filename, mode)
This will create a File file.txt [notepad file] in the root directory.
fobj = open("std.txt","w")
fobj.write("Hello World")
fobj.write("I'm Gaurav")
fobj.close()
fobj = open("std.txt","w")
fobj.write("This is Microtek")
fobj.close()
fobj=open("D:\\aspnet\\std.txt","w")
fobj.write("This is Gaurav")
fobj.close()
for using single backward slash symbol then add "r" before path
fobj=open(r"D:\aspnet\mash.txt","w")
fobj.write("Varanasi Microtek")
fobj.close()
Type the content in output file and check file after type
fobj=open("chage.txt","w")
s=input("enter String= ")
fobj.write(s)
fobj.close()
Output:
enter String= Hi. this is from Microtek.
Press Enter
fobj = open("std.txt","r")
val = fobj.read(12)
print(val)
Output:
This is Micr
kjl
ygf
119
shlok
120
naman
mahesh
fobj=open("D:\\CheckRes\\hello.txt","r")
x=fobj.read(5)
print(str(x))
fobj.close()
Output:
kjl
y
Example
def writefile():
with open("D:\\CheckRes\\ayush.txt","w") as f1 :
for i in range(5) :
sqr = i*i
f1.write(str(sqr)+" ")
f1.close()
def myread():
writefile()
with open("D:\\CheckRes\\ayush.txt","r") as f1 :
x=f1.read(3)
print(x,end=" ")
f1.close()
myread()
Output:
01
Example
fobj = open("std.txt","r")
val = fobj.read()
print(val)
Output:
This is Microtek Hi i'm going to Microtek
fobj=open("D:\\aspnet\\std.txt","r")
val=fobj.readline()
print(val)
val=fobj.readline()
print(val)
fobj.close()
Output:
This is Gaurav
This is from Microtek
Example
fobj=open("chage.txt","r")
while str:
str = fobj.readline()
print(str)
fobj.close()
Output:
101,ram,87.0
102,jai,65.0
103,manoj,81.0
104,alok,49.0
105,nishant,43.0
fobj=open("D:\\aspnet\\std.txt","w")
fobj=open("C:\\Users\\Gaurav\\AppData\\Local\\Programs\\Python\\Python3
10\\chage.txt","w")
n = int(input("How many Line:="))
x=[]
for i in range(n):
s=input("Enter the String :")
x.append(s+"\n")
fobj.writelines(x)
fobj.close()
fobj=open("chage.txt","w")
n = int(input("How many Line:="))
x=[]
for i in range(n):
s=input("Enter the String :")
x.append(s+"\n")
fobj.writelines(x)
fobj.close()
Output:
How many Line:=3
Enter the String :Gaurav
Enter the String :singh
Enter the String :Microtek
fobj=open("D:\\CheckRes\\hello.txt","w")
n=int(input("Enter The Value :"))
for i in range(n):
s=input("enter the String :")
fobj.write(s+"\n")
fobj.close()
def myread():
fobj=open("D:\\CheckRes\\hello.txt","r")
x=fobj.read()
print(x)
fobj.close()
newwrite()
myread()
Output:
Enter The Value :3
enter the String :manoj kumar
enter the String :ajay pandey
enter the String :harshit mishra
manoj kumar
ajay pandey
harshit mishra
Example
size = int(input("How many Student.? "))
fobj=open("chage.txt","w")
for i in range(size):
roll=int(input("Enter the Roll Number :"))
name=input("Enter the Name :")
marks=float(input("Enter the Marks :"))
rec=str(roll)+","+name+","+str(marks)+"\n"
fobj.write(rec)
fobj.close()
Output:
How many Student.? 2
Enter the Roll Number 101
Enter the Name :suraj
Enter the Marks :74
Enter the Roll Number 102
Enter the Name :aman
Enter the Marks :63
Example
Write a program which increment the value of variable and multiplies of its
index value of 5
def writefile():
with open("D:\\CheckRes\\ayush.txt","w") as f1 :
for i in range(5) :
sqr = i*i
f1.write(str(sqr) + "\n")
f1.close()
def myread():
writefile()
with open("D:\\CheckRes\\ayush.txt","r") as f1 :
x=f1.read()
print(x)
f1.close()
myread()
Output:
0
1
4
9
16
tell() Function
Definition and Usage
The tell() method returns the current file position in a file stream.
fobj=open("chage.txt","r")
str=fobj.read()
print(str)
print("innitally the position is : ", fobj.tell())
Output:
101,shukla,65.0
102,mohit,78.0
103,sanjay,64.0
104,Kamal,66.0
105,Radha,70.0
Seek() Function
Pass
Pass statement is used to do nothing. it can be used inside a loop or if
statement to represent
no operation. Pass is useful when we need statement syntactically correct
we do any operation.
if b > a:
pass
Output:
No output
strip()
returns a copy of the string with both leading and trailing
characters removed
Output:
Varanasi Kashi
Varanasi Kashi
Example
Read Text File and result comes with every word into list in string type.
fh=open("yes.txt","r")
for line in fh:
word = line.split()
print(word,end=" ")
Solution
Here in create a text/notepad file and saved in python default path write a
something like I’ve written as given below.
First of all, what is a CSV ?
Output:
['First', 'of', 'all,', 'what', 'is', 'a', 'CSV', '?']
-------------------------------------------------------------------------
Unpickling
Unpickling
Byte Stream-------------------------> Structure
For storing
b = pickle.dumps(db)
# For loading
myEntry = pickle.loads(b)
Dump()
Write the content into Binary file is used Dump()
pickle.dump(structure,fileobject)
load()
Reads the contents of Binary file is used load()
.dat File :
Example
Create a binary file and store the data into list format
import pickle
f=open("myfile.dat","wb")
def write():
f=open("myfile.dat","wb")
lst=['abc','mnp','pqr','xyz']
pickle.dump(lst,f)
f.close()
write()
print("Data Saved..")
Example
import pickle
f=open("myfile.dat","wb")
def write():
f=open("myfile.dat","wb")
lst=['abc','mnp','pqr','xyz']
pickle.dump(lst,f)
f.close()
def readfile():
f=open("myfile.dat","rb")
list1=pickle.load(f)
print(list1)
f.close()
write()
readfile()
Example
Create a binary file and store data and read and display the data from
binary file.
def write():
lst=""
f=open("myfile.dat","wb")
lst="microtek courses"
pickle.dump(lst,f)
f.close()
def readfile():
f=open("myfile.dat","rb")
list1=pickle.load(f)
print(list1)
f.close()
write()
readfile()
2. While True: --> it'll become False when end of file is reached
EOF exception) except EOFError:
Example
Program of list data input in Binary File.
import pickle
f=open("myfile.dat","wb")
def write():
f=open
c=[]
for m in range(3):
n = input("Enter the String: ")
c.append(n)
pickle.dump(c,f)
f.close()
def readfile():
m=[]
f=open("myfile.dat","rb")
try:
print("File m.dat stores data: ")
while True:
m=pickle.load(f)
print(m)
except EOFError:
f.close()
write()
readfile()
Output:
Enter the String: jai
Enter the String: kamal
Enter the String: sumanth
File m.dat stores data:
['jai']
['jai', 'kamal']
['jai', 'kamal', 'sumanth']
Example
import pickle
emp1 = {"Empno" : 1207, "Name" : "Saurav", "Age" : 36,}
emp2 = {"Empno" : 1208, "Name" : "nidhi", "Age" : 37,}
emp3 = {"Empno" : 1209, "Name" : "Kishan", "Age" : 43,}
fobj=open("myfile.dat","ab")
pickle.dump(emp1,fobj)
pickle.dump(emp2,fobj)
pickle.dump(emp3,fobj)
print("succesfully written in dictionary..")
stu = {}
fobj=open("myfile.dat","rb")
try:
print("fobj.stu Record")
#x=pickle.load(fobj)
while True:
str=pickle.load(fobj)
print(str)
except EOFError:
fobj.close()
Output:
succesfully written in dictionary..
fobj.stu Record
{'Empno': 1204, 'Name': 'Saurav', 'Age': 28}
{'Empno': 1205, 'Name': 'Kalyan', 'Age': 36}
{'Empno': 1206, 'Name': 'Kishan', 'Age': 39}
{'Empno': 1207, 'Name': 'Saurav', 'Age': 36}
{'Empno': 1208, 'Name': 'nidhi', 'Age': 37}
{'Empno': 1209, 'Name': 'Kishan', 'Age': 43}
Example
Input in dictionary in Binary File
import pickle
fobj=open("mygrv.dat","wb")
st = {}
ans = 'y'
while ans=='y':
r=int(input("Enter the rollno :"))
n=input("Enter the name : ")
m=int(input("Enter the marks : "))
st['rno'] = r
st['nm'] = n
st['mrk'] = m
pickle.dump(st,fobj)
ans=in
put("Want to Add : ? (y/n)..")
fobj.close()
Output:
Enter the rollno :108
Enter the name : jaikamal
Enter the marks : 70
Want to Add : ? (y/n)..y
Enter the rollno :111
Enter the name : hemant
Enter the marks : 72
Want to Add : ? (y/n)..n
What is a CSV ?
CSV (Comma Separated Values) is a simple file format used to
store tabular data, such as a spreadsheet
or database. A CSV file stores tabular data (numbers and text)
in plain text. Each line of the file is a data record.
Each record consists of one or more fields, separated by commas.
The use of the comma as a field separator
is the source of the name for this file format.
import csv
As CSV file text are text file such as translation of end of line
(EOL)
For Example
[30,"Amit\rRawat",24,3.14] --> here \r is EOL character of the file in
Macintosh system due to different OS for EOL character, if you want to
avoid this problem use newline='' argument.
csv.writer --> returns a writer object which writes data into csv file.
sturec = [[11,naman,78],[12,manoj,80.0],[13,alok,46.0]]
<writerobject>.writerows(Sturec)
import csv
f = open("student.csv","w")
wr = csv.writer(f)
head = ['rno','name','address','perc']
wr.writerow(head)
for i in range(3)
r = int(input("Enter Roll No. "))
nm = input("Enter Name ")
addr = input("Enter Area of Address. ")
p = float(input("Enter Percentage. "))
l = [r,nm,addr,p] :--> all input are into list
wr.writerow(l) :--> written the list into csv file
f.close()
Example
import csv
f = open("student.csv","w")
wr = csv.writer(f)
head = ['rno','name','marks']
wr.writerow(head)
for i in range(3):
print("student Record ",(i+1))
r = int(input("Enter Roll No. "))
nm = input("Enter Name ")
mrk = float(input("Enter Marks "))
strec = [r,nm,mrk]
wr.writerow(strec)
f.close()
Example
Reading data from csv file and display the output.
import csv
f = open("D:\\aspnet\\stdlist.csv","r")
csv_reader = csv.reader(f) # csv_reader is csv reader object
print("Content of Student File are :")
for row in csv_reader:
print(row)
f.close()
Output:
['Name', 'Class', 'Marks']
['Amit', 'XI', '56']
['Ajay', 'XI', '58']
['Aman', 'XI', '64']
['Alok', 'XI', '51']
['Bhanu', 'XI', '50']
['Jai', 'XI', '69']
Output
result.csv file will be created default path of python
Example
CSV file reading without specifying the newline argument:
with open(<csv file>.<read mode>) as <file handle>
import csv
with open("result.csv","r",newline ='\r\n') as csvf:
record = csv.reader(csvf)
print("Content of Result File :")
row = []
for rec in record:
row.append(rec)
print(row)
Output:
Content of Result File :
[['name', 'Points', 'Rank'], ['Amit', '1500', '26'], ['Alok', '3600', '14'], ['Ajay',
'1800', '19']]
Example
import csv
with open("result.csv","r",newline ='\r\n') as csvf:
record = csv.reader(csvf)
print("Content of Result File :")
#row = []
for rec in record:
print(rec)
Output:
Content of Result File :
['name', 'Points', 'Rank']
['Amit', '1500', '23']
['Alok', '3600', '10']
['Ajay', '1800', '11']
Example
import csv
fh = open("Empl.csv","w",newline ='')
ewriter = csv.writer(fh)
empdata = [
['EmpNo','Name','Desig','Sal'],
['110','Manoj','Admin','18000'],
['120','Manish','Admin','10000'],
['100','Ajay','Lecturer','20000'],
['111','Aman','Clerk','10000'],
['114','Naveen','Analyst','22000']
]
ewriter.writerows(empdata)
print("File Successfully created..")
fh.close()
Output:
Empl.csv file will be created default path of python and records saved into
Empl.csv file
Example:
Display all line/record Number:
import csv
with open("Empl.csv","r",newline ='\r\n') as csvf:
record = csv.reader(csvf)
print("Content of Result File :")
Output:
Content of Result File :
['EmpNo', 'Name', 'Desig', 'Sal']
['110', 'Manoj', 'Admin', '18000']
['120', 'Manish', 'Admin', '10000']
['100', 'Ajay', 'Lecturer', '20000']
['111', 'Aman', 'Clerk', '10000']
['114', 'Naveen', 'Analyst', '22000']