2/13/24, 10:25 PM Python notes
These are the basic codes for python exam
preparation.
Note: These are just glance of the syllabus,
if you want full syllabus refer your notes
In [75]: #to print multiple numbers
a=2,3,4
print(a)
(2, 3, 4)
In [33]: #To print multiple values at a time
print(12,3.4,"icbm")
12 3.4 icbm
In [7]: #Variable c=2, in this "C" is a variable
#funtion = ()
#List = []
In [9]: #integers(numbers)
x=(1,2,3)
print(x)
(1, 2, 3)
In [24]: #strings(text which is under " ")
x=("abc")
print(x)
abc
In [25]: x=('abc','bce')
print(x)
('abc', 'bce')
In [12]: #float(numbers with decimals)
x=(10.2,5.2,3)
print(x)
(10.2, 5.2, 3)
In [13]: #type
type("ali")
str
Out[13]:
In [27]: #Example program to print as int
type(2)
int
Out[27]:
In [17]: type(2.4)
localhost:8888/nbconvert/html/Python [Link]?download=false 1/21
2/13/24, 10:25 PM Python notes
float
Out[17]:
In [23]: #multiple types at once
x=("ali")
y=(22206)
z=(8.5)
print(type(x),type(y),type(z))
<class 'str'> <class 'int'> <class 'float'>
In [32]: # Example program to print the array location of particular value
# Id= will provide the memory location of a particular value or variable.
id(x)
2547355256768
Out[32]:
In [35]: # Arthemetic operators
# It means Addition, subraction, multiplication, division
# Note: we can do this with variable or without variable
# without a variable
2+4
6
Out[35]:
In [37]: #With ar variable
a=2+4
print(a)
In [39]: #All the functions of arthematic operators
a=4+2
b=4-2
c=3*2
d=9/2
print(a,b,c,d)
6 2 6 4.5
In [42]: #Modules (%) it gives the reminder
#example 12/5 it leaves the reminder 2
a=12%5
print(a)
In [50]: # Eample program to print as "Hello we are finance students"
a='are'
b='finance students'
c= 'Hello we {0} {1}'.format(a,b)
print(c)
#Note in this format is very important
Hello we are finance students
localhost:8888/nbconvert/html/Python [Link]?download=false 2/21
2/13/24, 10:25 PM Python notes
In [57]: #Input function
#It is an inbuilt function it enables us to accept and input srting from the user
#without evaluating
#input function
x=input("salary")
print(x)
salary14500
14500
In [59]: #EVAL function
#it considered the string as value
eval('5+6')
11
Out[59]:
In [ ]: eval('10+4')
In [ ]: #Round function
a=round(10.653)
print(a)
In [1]: # Type conversion (important question)
#without type conversion
cost=input("enter the cost ")
profit=input("enter your profit ")
saleprice=cost+profit
print(saleprice)
enter the cost 12
enter your profit 24
1224
In [4]: #with type conversion, by adding "int"
cost=int(input("enter the cost "))
profit=int(input("enter your profit "))
saleprice=cost+profit
print(saleprice)
enter the cost 12
enter your profit 24
36
In [6]: #min max pow functions,
print(max(22,5,12))
22
In [8]: print(min(22,5,12))
In [10]: print(pow(2,3))
localhost:8888/nbconvert/html/Python [Link]?download=false 3/21
2/13/24, 10:25 PM Python notes
In [12]: #Functions related to strings
x=('awais')
len(x)
5
Out[12]:
In [15]: #String are considered as compound data types.
#We can extract any character
x='icbm'
print(x[2])
In [19]: #String slicing: A segment of string is called slice
x='icbm sbe'
print(x[1:4])
#Remeber the index starts from zero in the Python
cbm
In [32]: # Starts with
a="awais"
print([Link]('a'))
True
In [35]: a="awais"
print([Link]('s'))
True
In [37]: #Alpha numeric = Combination of alphabet and number
p="iphone15"
print([Link]())
True
In [39]: #Find and count
x="we are icbm students "
print([Link]('e'))
In [49]: print([Link]('r'))
In [56]: #Case and align
print([Link]())
WE ARE ICBM STUDENTS
In [58]: print([Link]())
we are icbm students
In [60]: print([Link]())
We are icbm students
localhost:8888/nbconvert/html/Python [Link]?download=false 4/21
2/13/24, 10:25 PM Python notes
In [62]: print([Link]())
We Are Icbm Students
In [66]: # Encode
y='hello'.encode('utf-32')
print(y)
b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x0
0'
In [73]: y='123'.encode('utf-32')
print(y)
b'\xff\xfe\x00\x001\x00\x00\x002\x00\x00\x003\x00\x00\x00'
In [76]: #Decode
s=b'\xff\xfe\x00\x00h\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x
print([Link]('utf-32'))
hello
In [79]: #String concatination
# Example program to join two strings
a="icbm"
b='sbe'
c=a+"-"+b
print(c)
icbm-sbe
In [102… # To get output as we are "finance" students
x="we are \"finance\"student"
print(x)
we are "finance"student
In [108… #Conditional statement (if statements)
age=int(input("age "))
if(age>=18):
print("eligible")
else:
print("not eligible")
age 15
not eligible
In [2]: #for three variables
a=int(input('first number '))
b=int(input('second number '))
c=int(input('third number '))
if(a>b and a>c):
print('first number is bigger')
elif(b>c):
print('second number is bigger')
else:
print('third number is bigger')
localhost:8888/nbconvert/html/Python [Link]?download=false 5/21
2/13/24, 10:25 PM Python notes
first number12
second number15
third number10
second number is bigger
In [1]: # while loop
#statements are executed repeatedally as long as the value of expression
#remains non-zero
i=1
while(i<=5):
print(i)
i=i+1
1
2
3
4
5
In [2]: i=5
while(i>=1):
print(i)
i=i-1
5
4
3
2
1
In [19]: #for loop
for x in range(0,6,2):
print(x)
#in this zero to six with 2 difference
0
2
4
List methods
In [22]: #type list
x=['you','450']
type(x)
list
Out[22]:
In [25]: #len method
print(len(x))
In [28]: #negative indexing
x=['you',450,'me',900]
print(x[-2])
me
In [30]: print(x[-1])
localhost:8888/nbconvert/html/Python [Link]?download=false 6/21
2/13/24, 10:25 PM Python notes
900
In [33]: #mutable sequence
#Replacing
x1=["icbm","sbe","pgdm"]
x1[0]="school"
print(x1)
['school', 'sbe', 'pgdm']
In [42]: #deleting the item
x1=["icbm","sbe","pgdm"]
[Link]()
print(x1)
[]
In [51]: #APPEND
x1=["icbm","sbe","pgdm"]
[Link]("Awais")
print(x1)
['icbm', 'sbe', 'pgdm', 'Awais']
In [53]: #insert
#this insert a item
v=['icbm','sbe', 'school']
[Link](1,"books")
print(v)
['icbm', 'books', 'sbe', 'school']
In [57]: #extend: it joins two lists
v=['icbm','sbe', 'school']
x=["array",'rows']
[Link](x)
print(v)
['icbm', 'sbe', 'school', 'array', 'rows']
In [59]: #index
v=['icbm', 'sbe', 'school', 'array', 'rows']
[Link]('sbe')
1
Out[59]:
In [64]: #list using for loop (important)
v=['icbm', 'sbe', 'school', 'array', 'rows']
for v1 in v:
print(v)
['icbm', 'sbe', 'school', 'array', 'rows']
['icbm', 'sbe', 'school', 'array', 'rows']
['icbm', 'sbe', 'school', 'array', 'rows']
['icbm', 'sbe', 'school', 'array', 'rows']
['icbm', 'sbe', 'school', 'array', 'rows']
In [67]: #sort method: it sort alphabeitically
v=['icbm', 'sbe', 'school', 'array', 'rows']
[Link]()
print(v)
['array', 'icbm', 'rows', 'sbe', 'school']
In [71]: #for reverse sort
[Link](reverse=True)
localhost:8888/nbconvert/html/Python [Link]?download=false 7/21
2/13/24, 10:25 PM Python notes
print(v)
['school', 'sbe', 'rows', 'icbm', 'array']
In [72]: #Note: List will accept indexing, ordering, mutable, dublicates.
Sets
In [74]: #An object of type set array be created by enclosing the elements
#of the sets within loops "{}" => sets
#note: The element of a set required to be imutable objects
#it is a concept not a data type
#Note: Set types does not support indexing, slicing, additions & mulitplication
#It will allow dublicate value ex: {'icbm','icbm'}
In [77]: #example program on set
x={'icbm','ise','cse'}
print(x)
{'ise', 'icbm', 'cse'}
In [80]: # we cannot decide the order of output
a=set('aeiou')
print(a)
{'a', 'o', 'i', 'u', 'e'}
In [81]: # very very important, high chance of 10 marks
#example program to create a set with strings
# a) Chech with help of condition wheather a string is available or not
# b) Chech with help of loop wheather a string is available or not
In [83]: # a answer
a={'sbe', 'icbm', 'cse'}
if "sbe" in a:
print('available')
else:
print('not available')
available
In [85]: # b answer
for a1 in a:
print(a1)
sbe
icbm
cse
In [87]: #len method
print(len(a))
In [93]: #remove
a={'sbe', 'icbm', 'cse'}
[Link]('sbe')
print(a)
localhost:8888/nbconvert/html/Python [Link]?download=false 8/21
2/13/24, 10:25 PM Python notes
{'icbm', 'cse'}
In [97]: # use discard instead of remove to avoid effors for non-availability of the element
a={'sbe', 'icbm', 'cse'}
[Link]('sbe')
print(a)
{'icbm', 'cse'}
In [100… #add element
a={'sbe', 'icbm', 'cse'}
[Link]('bike')
print(a)
#NOTE: order cannot be decided
{'sbe', 'bike', 'icbm', 'cse'}
visualization
In [103… # first installation
!pip install matplotlib
Requirement already satisfied: matplotlib in c:\users\mdawa\anaconda3\lib\site-pac
kages (3.7.2)
Requirement already satisfied: contourpy>=1.0.1 in c:\users\mdawa\anaconda3\lib\si
te-packages (from matplotlib) (1.0.5)
Requirement already satisfied: cycler>=0.10 in c:\users\mdawa\anaconda3\lib\site-p
ackages (from matplotlib) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in c:\users\mdawa\anaconda3\lib\s
ite-packages (from matplotlib) (4.25.0)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\mdawa\anaconda3\lib\s
ite-packages (from matplotlib) (1.4.4)
Requirement already satisfied: numpy>=1.20 in c:\users\mdawa\anaconda3\lib\site-pa
ckages (from matplotlib) (1.24.3)
Requirement already satisfied: packaging>=20.0 in c:\users\mdawa\anaconda3\lib\sit
e-packages (from matplotlib) (23.1)
Requirement already satisfied: pillow>=6.2.0 in c:\users\mdawa\anaconda3\lib\site-
packages (from matplotlib) (9.4.0)
Requirement already satisfied: pyparsing<3.1,>=2.3.1 in c:\users\mdawa\anaconda3\l
ib\site-packages (from matplotlib) (3.0.9)
Requirement already satisfied: python-dateutil>=2.7 in c:\users\mdawa\anaconda3\li
b\site-packages (from matplotlib) (2.8.2)
Requirement already satisfied: six>=1.5 in c:\users\mdawa\anaconda3\lib\site-packa
ges (from python-dateutil>=2.7->matplotlib) (1.16.0)
In [109… import [Link] as plt
[Link](3,2,'ro')
[Link]()
localhost:8888/nbconvert/html/Python [Link]?download=false 9/21
2/13/24, 10:25 PM Python notes
In [111… import [Link] as plt
x=[1,3,5,6,10]
y=[2,5,10,12,15]
[Link](x,y,'ro')
[Link]
<function [Link](close=None, block=None)>
Out[111]:
In [124… import [Link] as plt
x=[1,3,5,6,10]
y=[2,5,10,12,15]
localhost:8888/nbconvert/html/Python [Link]?download=false 10/21
2/13/24, 10:25 PM Python notes
[Link](x,y,'b*--')
[Link]
# for title
[Link]('sample chart')
#x axis title
[Link]('numbers')
#y axis title
[Link]('age')
#for adding legend
[Link]('fin')
<[Link] at 0x28592bd9890>
Out[124]:
In [127… #bar chart
import [Link] as plt
x=[1,3,5,6,10]
y=[2,5,10,12,15]
#this code is important for creating a bar chart
[Link](x,y,color='green')
[Link]
# for title
[Link]('sample chart')
#x axis title
[Link]('numbers')
#y axis title
[Link]('age')
localhost:8888/nbconvert/html/Python [Link]?download=false 11/21
2/13/24, 10:25 PM Python notes
#for adding legend
[Link]('fin')
<[Link] at 0x285929a8850>
Out[127]:
In [10]: import [Link] as plt
x=[1,3,5,6,10]
y=[2,5,10,12,15]
[Link](x,y,'r*--')
[Link]
<function [Link](close=None, block=None)>
Out[10]:
localhost:8888/nbconvert/html/Python [Link]?download=false 12/21
2/13/24, 10:25 PM Python notes
In [20]: #to increase marker size
[Link](x,y,'r*--',markersize=25)
[<[Link].Line2D at 0x20846452810>]
Out[20]:
In [2]: #Numpy is a numerical package in python
#In this library we can extract numbers as arrays as index numbers
#which starts with array
!pip install numpy
localhost:8888/nbconvert/html/Python [Link]?download=false 13/21
2/13/24, 10:25 PM Python notes
Requirement already satisfied: numpy in c:\users\mdawa\anaconda3\lib\site-packages
(1.24.3)
In [4]: import numpy as np
arr=[Link]([1,2,3,4,5])
print(arr)
[1 2 3 4 5]
In [7]: import numpy as np
arr=[Link](5)
print(arr)
In [10]: import numpy as np
arr=[Link]([[1,2,3],[4,5,6],[7,8,9]])
print(arr)
[[1 2 3]
[4 5 6]
[7 8 9]]
In [13]: #extracting an element by using numpy
import numpy as np
arr=[Link]([1,2,3,4,5])
print(arr[2])
#as it is starts from '0'(zero)
In [15]: print(arr[1]+arr[2])
In [41]: import numpy as np
arr = [Link](1,51).reshape(5,5, 2)
#5 sets, 50 rows and 2 coloumns
print(arr)
localhost:8888/nbconvert/html/Python [Link]?download=false 14/21
2/13/24, 10:25 PM Python notes
[[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
[[11 12]
[13 14]
[15 16]
[17 18]
[19 20]]
[[21 22]
[23 24]
[25 26]
[27 28]
[29 30]]
[[31 32]
[33 34]
[35 36]
[37 38]
[39 40]]
[[41 42]
[43 44]
[45 46]
[47 48]
[49 50]]]
In [42]: # "T" to tranpose
arr=arr.T
print(arr)
[[[ 1 11 21 31 41]
[ 3 13 23 33 43]
[ 5 15 25 35 45]
[ 7 17 27 37 47]
[ 9 19 29 39 49]]
[[ 2 12 22 32 42]
[ 4 14 24 34 44]
[ 6 16 26 36 46]
[ 8 18 28 38 48]
[10 20 30 40 50]]]
In [47]: arr=[Link]([1,2,3])
arr1=[Link]([4,5,6])
con=[Link]([arr,arr1])
print(con)
[1 2 3 4 5 6]
In [49]: #Pandas is data library to analyse the data from external
#file like .csv, .xlxs, tsv
!pip install pandas
localhost:8888/nbconvert/html/Python [Link]?download=false 15/21
2/13/24, 10:25 PM Python notes
Requirement already satisfied: pandas in c:\users\mdawa\anaconda3\lib\site-package
s (2.0.3)
Requirement already satisfied: python-dateutil>=2.8.2 in c:\users\mdawa\anaconda3
\lib\site-packages (from pandas) (2.8.2)
Requirement already satisfied: pytz>=2020.1 in c:\users\mdawa\anaconda3\lib\site-p
ackages (from pandas) (2023.3.post1)
Requirement already satisfied: tzdata>=2022.1 in c:\users\mdawa\anaconda3\lib\site
-packages (from pandas) (2023.3)
Requirement already satisfied: numpy>=1.21.0 in c:\users\mdawa\anaconda3\lib\site-
packages (from pandas) (1.24.3)
Requirement already satisfied: six>=1.5 in c:\users\mdawa\anaconda3\lib\site-packa
ges (from python-dateutil>=2.8.2->pandas) (1.16.0)
In [57]: import pandas as pd
a=[Link]([101,'finance'])
print(a)
0 101
1 finance
dtype: object
In [66]: import pandas as pd
a=[Link]([101,'finance'],index=['subject_code','subject_name'])
print(a)
subject_code 101
subject_name finance
dtype: object
In [72]: import pandas as pd
a=[Link]({'sid':[1,2,3],'sname':['sid','azam','barak']})
print(a)
sid sname
0 1 sid
1 2 azam
2 3 barak
In [78]: import pandas as pd
a=[Link]({'Countires':['India', 'Pak', 'Aus', 'Eng'], 'Runs':[101, 96, 25, 25
print(a)
Countires Runs
0 India 101
1 Pak 96
2 Aus 25
3 Eng 25
In [82]: # Example program to get output as
# Day First_Hour subject
#0 mon H-1 IF
#1 tue H-1 BV
#2 wed H-1 RM
import pandas as pd
data=[Link]({'Day': ['mon','tue', 'wed'], 'First_Hour': ['H-1','H-1','H-1'],
print(data)
Day First_Hour subject
0 mon H-1 IF
1 tue H-1 BV
2 wed H-1 RM
localhost:8888/nbconvert/html/Python [Link]?download=false 16/21
2/13/24, 10:25 PM Python notes
In [87]: #to extract index data 1:
import pandas as pd
data=[Link]({'Day': ['mon','tue', 'wed'], 'First_Hour': ['H-1','H-1','H-1'],
print([Link][1])
Day tue
First_Hour H-1
subject BV
Name: 1, dtype: object
In [91]: #example program to get age coloumn
k=[Link]({'Ename':['Adam', 'Awais'], 'Age': [22,24]})
ages=k['Age']
print(ages)
0 22
1 24
Name: Age, dtype: int64
In [115… import pandas as pd
pnb = pd.read_csv(r"C:\Users\mdawa\Desktop\[Link]")
print(pnb)
#note this data is my own
Date Open High Low Close Adj Close Volume
0 2019-09-03 62.000000 62.400002 59.049999 59.400002 57.381382 68369998
1 2019-09-04 59.900002 60.349998 58.700001 59.900002 57.864388 34213414
2 2019-09-05 61.650002 61.900002 60.500000 61.099998 59.023605 30641680
3 2019-09-06 61.349998 61.599998 60.799999 61.299999 59.216808 19597727
4 2019-09-09 61.299999 62.849998 60.650002 62.599998 60.472630 21700960
5 2019-09-11 62.599998 65.000000 62.599998 64.849998 62.646172 24414845
6 2019-09-12 64.550003 65.500000 64.250000 64.550003 62.356365 21906448
7 2019-09-13 64.550003 65.199997 62.799999 64.900002 62.694469 21379499
In [112… print([Link][5])
Date 2019-09-11
Open 62.599998
High 65.0
Low 62.599998
Close 64.849998
Adj Close 62.646172
Volume 24414845
Name: 5, dtype: object
In [114… #to get the type
print(type(pnb))
<class '[Link]'>
In [117… #To get all the data types
print([Link])
localhost:8888/nbconvert/html/Python [Link]?download=false 17/21
2/13/24, 10:25 PM Python notes
Date object
Open float64
High float64
Low float64
Close float64
Adj Close float64
Volume int64
dtype: object
In [119… #to get info
print([Link]())
<class '[Link]'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Date 8 non-null object
1 Open 8 non-null float64
2 High 8 non-null float64
3 Low 8 non-null float64
4 Close 8 non-null float64
5 Adj Close 8 non-null float64
6 Volume 8 non-null int64
dtypes: float64(5), int64(1), object(1)
memory usage: 580.0+ bytes
None
In [122… #Extracting from subset method
subset=pnb['Date']
print(subset)
0 2019-09-03
1 2019-09-04
2 2019-09-05
3 2019-09-06
4 2019-09-09
5 2019-09-11
6 2019-09-12
7 2019-09-13
Name: Date, dtype: object
In [128… subset=pnb[['Date','Adj Close']]
print(subset)
Date Adj Close
0 2019-09-03 57.381382
1 2019-09-04 57.864388
2 2019-09-05 59.023605
3 2019-09-06 59.216808
4 2019-09-09 60.472630
5 2019-09-11 62.646172
6 2019-09-12 62.356365
7 2019-09-13 62.694469
In [131… print([Link](n=3))
Date Open High Low Close Adj Close Volume
0 2019-09-03 62.000000 62.400002 59.049999 59.400002 57.381382 68369998
1 2019-09-04 59.900002 60.349998 58.700001 59.900002 57.864388 34213414
2 2019-09-05 61.650002 61.900002 60.500000 61.099998 59.023605 30641680
In [136… #descriptive stats
localhost:8888/nbconvert/html/Python [Link]?download=false 18/21
2/13/24, 10:25 PM Python notes
print([Link]())
Open High Low Close Adj Close Volume
count 8.000000 8.000000 8.000000 8.000000 8.000000 8.000000e+00
mean 62.237501 63.099999 61.168750 62.325000 60.206977 3.027807e+07
std 1.619469 1.911805 1.913847 2.236707 2.160696 1.620360e+07
min 59.900002 60.349998 58.700001 59.400002 57.381382 1.959773e+07
25% 61.337498 61.825001 60.137500 60.799999 58.733801 2.162059e+07
50% 61.825001 62.625000 60.725001 61.949998 59.844719 2.316065e+07
75% 63.087499 65.049999 62.649998 64.625002 62.428817 3.153461e+07
max 64.550003 65.500000 64.250000 64.900002 62.694469 6.837000e+07
In [146… #Get the mean of a particular coloumn
print([Link]('Date')['Low'].mean())
Date
2019-09-03 59.049999
2019-09-04 58.700001
2019-09-05 60.500000
2019-09-06 60.799999
2019-09-09 60.650002
2019-09-11 62.599998
2019-09-12 64.250000
2019-09-13 62.799999
Name: Low, dtype: float64
In [155… print(pnb['Open'].plot(kind='line'))
Axes(0.125,0.11;0.775x0.77)
In [169… import [Link] as plt
import pandas as pd
a=[Link]({'emname':['Smith','Rock','Boss'], 'Salary':[10000,12200,15000]})
print(a)
[Link](x='emname',y='Salary',kind='bar',color='pink')
[Link]()
localhost:8888/nbconvert/html/Python [Link]?download=false 19/21
2/13/24, 10:25 PM Python notes
emname Salary
0 Smith 10000
1 Rock 12200
2 Boss 15000
In [182… mean=pnb['Open'].mean()
median=pnb['Open'].median()
var=pnb['Open'].var()
print(mean,median,var)
62.237500624999996 61.825001 2.6226814321474157
In [183… sum_by=[Link](['Open']).sum()
print(sum_by)
Date High Low Close \
Open
59.900002 2019-09-04 60.349998 58.700001 59.900002
61.299999 2019-09-09 62.849998 60.650002 62.599998
61.349998 2019-09-06 61.599998 60.799999 61.299999
61.650002 2019-09-05 61.900002 60.500000 61.099998
62.000000 2019-09-03 62.400002 59.049999 59.400002
62.599998 2019-09-11 65.000000 62.599998 64.849998
64.550003 2019-09-122019-09-13 130.699997 127.049999 129.450005
Adj Close Volume
Open
59.900002 57.864388 34213414
61.299999 60.472630 21700960
61.349998 59.216808 19597727
61.650002 59.023605 30641680
62.000000 57.381382 68369998
62.599998 62.646172 24414845
64.550003 125.050834 43285947
localhost:8888/nbconvert/html/Python [Link]?download=false 20/21
2/13/24, 10:25 PM Python notes
In [ ]:
localhost:8888/nbconvert/html/Python [Link]?download=false 21/21