Python Notes
Python Notes
,m PYTHON
-----------------------------------------------------------------------------------
-------------------
1.PYTHON IS HIGH LEVEL OBJECT ORIENTED PROGRAMMING LANGUAGE.
2.PYTHON IS OPEN SOURCE LANGUAGE.
3.PYTHON IS PLATFORM INDEPENDENT.
WHICH CAN RUN ON ANY PLATFORM SUPPOSE ON WINDOWS,LINUX,MACOS.
PYTHON IS POPULAR PROGRAMMING LANGUAGE.
FEATURES:
1.PYTHON IS INTEREPTED.
IN PYTHON CHECK EACH AND EVERY LINE OF PROGRAM .IN ANY PARTICUL LINE OCCURS ERROR
THROWS EXCEPTION.
2.PYTHON IS INTERACTIVE.
PYTHON PROVIDE COMMAND LINE INTERFACES TO INTERACT WITH IT.
3.PYTHON IS OBJECT-ORIENTED.
BEACUSE PYTHON SUPPORTS OOPS
CONCEPTS(ENCAPSUALTION,POLYMORPHISM,ABSTRACTION,INHERITANCE).
4.PYTHON IS DYNAMICALY TYPED PROGRAMMING LANGUAGE
WHICH MEANS WE DONT WANT TO SPECIFY DATATYPE
5.BEGINNERS PROGRAMMING LANGUAGE.
HISTORY OF PYTHON:
PYTHON------->1989
GUIDO VAN ROSSUM AT CWI IN NETHERLANDS.
PYTHON 1.0--------->1994
PYTHON 3.0------->2008
PYTHON IS INFULENCED BY -----ABC,MODULE-3 PROGRAMMING LANGUAGES.
PYTHON APPLICATIONS:
1.WEB APPLICATIONS
2.TESTING
NOW DAYS PYTHON IS USING IN TESTING.
3.DATA ANALYSIS
4.DATA SCIENCE
5.ARTIFICIAL INTELLIGENCE
6.MACHINE LEARNING.
TOP COMBANIES:GOOGLE,IBM,HCL,INFOSYSE..
DOWNLOAD AND INSTALL PYTHON ON WINDOWS:HTTP://WWW.PYTHON.ORG.
MANY WAYS OF RUNNING PYTHON:
METHOD 1:C:\Users\PROGRAMMINGFILES(X86)\PYTHON 3.10
PYTHON.EXE
METHOD-2:
PYTHON SHELL:COMMAND PROMPT
WRITE IN NEW FILE AND SAVE AND RUN IT.
METHOD-3:
WINDOWS COMMAND PROMPT
METHOD-4:
NOTEPAD++
EDITPLUS
PYTHON TEST.PY
METHOD-5:ONLINE CODE EDITORS---------REPL.IT
METHOD-6:ECLIPSE,PYCHARM.
Eg:print("HELLO WORLD");
COMMENTS:
1.LOGICS TO UNDERSTAND IS VERY EASY
2.CODE MAINTAINENCE
3.NON-EXECUTABLE CODE
4.COMMENTS ARE IGNORED BY PYTHON AT TIME OF EXECUTION.
TWO TYPES OF COMMENTS:
1.SINGLE LINE COMMENT:
IT IS FOLLWED BY # SYMBOL.
EG:#SINGLE-LINE COMMENT
2.MULTILINE COMMENTS:
IT IS FOLLWED BY " " "......." " ".
EG:
" " "
COMMENT 1
COMMENT2
..............
.................
" " "
KEYWORDS:
IN PYTHON 2.X----------->import keyword;
print keyword.kwlist;
IN PYTHON 3.X----------->import keyword;
print(keyword.kwlist);
PARENTHESIS ARE NOT MANADATORY IN PYTHON 2.X BUT MANADATORY IN PYTHON 3.0.--------
>PARAENTHESIS().
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
remove from python 3.0----->print
added keywords in python 3.0----------->False,True,None.
VARIABLES:
1.to resevere some memory allocated to variable to store value.
2.to store data.
3.memory is allocated when value is assigned to variable.
4.variables must have some data type.
eg:
#single values to single variables
a=100
b=10.5
name="hari"
name1='bharath'
print(a)
print(b)
print(name)
print(name1)
#multilple values to multiple variables
a,b,name=100,10.5,"jayavardhana"
print(a,b,name)
#when same value to all variables method 1
a,b,c=10,10,10
print(a,b,c)
#when same values to all variables method 2
a=b=c=10
print(a,b,c)
#swappping program
a=100
b=300
a,b=b,a
print(a,b)
output:
----------------------------
100
10.5
hari
bharath
100 10.5 jayavardhana
10 10 10
10 10 10
300 100
DATATYPES:
1.Numbers
2.String
3.List
4.Tuple
5.Dicionary
6.Boolean
we have buit-in function to find data type of a variable in python is type( ).
1.Numbers:
eg:#Number data type
a.integers:
a=100
print(type(a))
----------------------
output:<class 'int'>
b.float:
a=89.7
print(type(a))
------------------------
output:<class 'float'>
2.String:a string is sequence of characters which is enclosed in single quotes or
double quotes.
eg:
#String data type
s="hari"
print(type(s))
------------------------
output:<class 'str'>
6.Boolean:
eg:b=True
print(type(b))
-------------------------------
output:<class 'bool'>
CONCATENATION(Joining):
we can concatenate same types but we cannot concatenate different types.
Eg:
print(10+10)#valid
print(2.5+3.5)#valid
print("hari"+"rayapati")#valid
print(10+10.5)#valid
print(True+10)#valid:True=1
print(False+10.5)#valid:False=0
print(10+"kiran")#invalid
print(19.8+"bharath")#invalid
print(True+"mahesh")#invalid
---------------------------------------------------------
output:20
6.0
harirayapati
20.5
11
10.5
#invalid
TypeError: unsupported operand type(s) for +: 'int' and 'str'
SWAPPING VARIABLES&redeclare&DELETING varaibles:
EG:
#swapping variables
a=10
b=900
print("before swapping variables",a,b)
a,b=b,a
print("after swapping variables",a,b)
#redeclaring variables
c=90
print(c)
c=780
print(c)
#deleting variables
z=76
print(z)
del z
print(z)
-------------------------------------
output:before swapping variables 10 900
after swapping variables 900 10
90
780
76
NameError: name 'z' is not defined
HOW TO TAKE INPUT FROM USER:
getting the input from the user in python 2.x,python 3.x.
in python 2.x-------->
input( )-------->which can take any type of data.
raw_input( )-------->which can take only string.
in python 3.x------------>
input( )---------->which can take only string.
in python 3.0 input() is behaves as raw_input(),raw_input() changes as input() in
python 3.0.
TYPECONVERSION:
getting data from user by using input function in the form of String then
converting.
NOTE:float can handle int.but int cannot handle float.
EG:
#TAKING INPUT FROM THE USER.
num1=input("enter first number:");
num2=input("enter second number:");
print(num1+num2);
# TYPE CONVERSION:String to float,String to int
num1=int(input("enter first number:"));
num2=int(input("enter second number:"));
print(num1+num2);
num1=float(input("enter first number:"));
num2=float(input("enter second number:"));
print(num1+num2);
num1=input("enter first number:");
num2=input("enter second number:");
print(int(num1)+int(num2));
num1=input("enter first number:");
num2=input("enter second number:");
print(float(num1)+float(num2));
num1=input("enter first number:");
num2=input("enter second number:");
print(int(num1)+float(num2));
num1=input("enter first number:");
num2=input("enter second number:");
print(float(num1)+int(num2));
--------------------------------------------------------------------------------
output:enter first number:10
enter second number:20
1020
enter first number:10
enter second number:30
40
enter first number:10.8
enter second number:4.9
15.700000000000001
enter first number:12
enter second number:34
46
enter first number:45.8
enter second number:34.3
80.1
enter first number:10
enter second number:23.8
33.8
enter first number:10.9
enter second number:34.3
Traceback (most recent call last):
File "C:/Users/Mahesh/AppData/Local/Programs/Python/Python310/typeconversion.py",
line 23, in <module>
print(float(num1)+int(num2));
ValueError: invalid literal for int() with base 10: '34.3'
FORMATTING OUTPUT:
formatting output
EG:
#formatting output
name="hari";
age=34;
sal=34000;
#approach 1
print(name)
print(age)
print(sal)
#approach 2
print("Name:",name)
print("Age:",age)
print("sal",sal)
#approach 3:type is important here
print("Name:%s Age:%d Sal:%f"%(name,age,sal))
#approach 4:value is important here
print("Name:{} Age:{} sal:{}".format(name,age,sal))
#approach 5:index and value is important here
print("Name:{0} Age:{1} Sal:{2}".format(name,age,sal))
-----------------------------------------------------------------------------------
--------------
output:
hari
34
34000
Name: hari
Age: 34
sal 34000
Name:hari Age:34 Sal:34000.000000
Name:hari Age:34 Sal:34000
Name:hari Age:34 Sal:34000
FLOWCONTROL STATEMENTS IN PYTHON:
1.conditional statements:
a.if else:
EG:
#if else Example 1:
a=34
if a>20:
print("a is greater than b");
else:
print("a is lessthan b");
#if else Example 2:
a=34
if True:
print("a is greater than b");
else:
print("a is lessthan b");
#if else Example 3:
a=34
if False:
print("a is greater than b");
else:
print("a is lessthan b");
#if else Example 4:
a=34
if 1:
print("a is greater than b");
else:
print("a is lessthan b");
#if else Example 5:
a=34
if 0:
print("a is greater than b");
else:
print("a is lessthan b");
#if else Example 6:even _odd:
a=34
if a%2==0:
print("a is greater than b");
else:
print("a is lessthan b");
#single line if else
print("welcome")if True else print("python");
#multiple statements if else
a=30
if True:
print("statement 1");
print("statement 2");
print("statement 3");
else:
print("statement 4");
print("statemnent 5");
print("statement 6");
print("statement 7");
#multiple statements in a single line if else
print("welcome"),print("python") if True else print("hi"),print("hello everyone");
-----------------------------------------------------------------------------------
--------------------------------------------------------------
output: a is greater than b
a is greater than b
a is lessthan b
a is greater than b
a is lessthan b
a is greater than b
welcome
statement 1
statement 2
statement 3
statement 7
welcome
python
hello everyone
b.elif:
Eg:#elif
a=90
if a==10:
print("ten");
elif a==20:
print("twenty");
elif a==90:
print("ninty");
else:
print("not in listed");
-----------------------------------------------------------
output:ninty
2.iterative statements(loops):
loop:it is defined as a block of statements executed multiple times.
a.for b.while
EG:
#for:1 to 10
for i in range(10):
print(i)
#for:even numbers
for i in range(2,10,2):
print(i)
#for:odd numbers
for i in range(1,10,2):
print(i)
#for:ascending order
for i in range(1,10,-1):
print(i)
#for:desceding order
for i in range(10,1,-1):
print(i)
#while:1 to 10
i=1;
while i<=10:
print(i)
i=i+1
#while:1 to 10
i=10;
while i<=1:
print(i)
i=i-1
-----------------------------------------------------------------------------------
-----
output:
0
1
2
3
4
5
6
7
8
9
2
4
6
8
1
3
5
7
9
10
9
8
7
6
5
4
3
2
1
2
3
4
5
6
7
8
9
10
3.Transfer statements(jumping statements):
a.Break:if u want to jump up from the loop based on certain condition.
b.Continue:to skip current number or jump into the next number by skipping
condition number.
EG:
#break
for i in range(1,10):
if i==5:
break
print(i)
#continue
for i in range(1,10):
if i==4:
continue
print(i)
------------------------------------------------------------
output: 1
2
3
4
1
2
3
5
6
7
8
9
1.NUMBERS IN PYTHON:
we have two type s of numbers are
a.integer b.float
Number types
Number type conversions:type()------>to find the data type of variables.
Type int(x)----------->convert x to a plain integer.
Type float(x)-------------->convert x to a plain floating point number.
buit-in functions on Number type:max()--------->it gives largest from
argumennts,min()----------->it gives smallest from arguments.
EG:#NUMBERS
#integer
a=10
print(a)
#float
a=23.5
print(a)
#typeconversions:integer,float
a=10
b=34
print(int(a)+int(b))
a=34.4
b=23.7
print(float(a)+float(b))
#type()
a=10
b=45
print(type(int(a)+int(b)))
a=23.4
b=45.5
print(type(float(a)+float(b)))
-----------------------------------------------------------------------------------
-----
OUTPUT:10
23.5
44
58.099999999999994
<class 'int'>
<class 'float'>
2.Strings:a string is a collection of characters we can include that in double
quotes or single quotes.
A.creating strings
EG:#string operations
#creating strings:approach1,approach2,approach3
name="hari"#1
name1='joshna'#2
name2=str("daney")#3
print(name)
print(name1)
print(name2)
-------------------------------
OUTPUT:hari
joshna
daney
B.Strings are immutable in python:
once string is created it cant be modified (immutable).
id()-every object in python is stored somewhere in memory.we can use id() to get
that memory address
EG:#strings are immutable
str1="welcome"
str2="welcome"
print(id(str1))
print(id(str2))
str2=str2+"python"
print(id(str2))
--------------------------------
output:2171175656240
2171175656240
2171174979056
C.operations on string:
String index starts from 0.
+ operator is used to concatenate string and * operator is a repetition operator
for string
EG:#concatenatation and repetition of strings
name="python"
print(name+"programming")
print(name*4)
---------------------------------------------
output:pythonprogramming
pythonpythonpythonpython
D.slicing of a string:
we can take subset of a string from original string by using []operator also known
as slicing operator.
syntax:s[start:end]
this will return part of the string starting from index start to index end-1.
EG:#SLICING STRING
name="environment"
print(name[2:7])
print(name[:9])
print(name[1:])
print(name[1:-1])
----------------------------------------------
output:viron
environme
nvironment
nvironmen
E.ord() and chr()functions:
ord()- function returns the ASCII code of the character.
chr()-function returns character represented by a ASCII number.
EG:#ord() and chr() functions
print(ord('s'))
print(chr(90))
-----------------------------------------------------
output:115
Z
F.len(),max(),min() functions:
len()- returns the length of the string.
max()-returns the character having highest ASCII value.
min()-returns the character having lowest ASCII value.
EG:#len(),min(),max() functions
name="jayavaradhana"
print(len(name))
print(max(name))
print(min(name))
---------------------------------------------------
output:13
y
a
G.in and not in operators:
you can use in and not in operators to check existence of string in another string
they are also known as membership operator.
EG:#in and not in operators
name="photographs"
print("photo" in name)
print("graphs" not in name)
----------------------------------------------------------
output:True
False
H.String comparison:
you can use (<,>,<=,>=,==,!=) to compare two strings.
phyton compares string lexicograhically i.e using ASCII value of the characters.
EG:
#string comparisons
name1="bharath"
name2="sreenath"
print(name1>name2)
print(name1<name2)
print(name1<=name2)
print(name1>=name2)
print(name1==name2)
print(name1!=name2)
-----------------------------------------------------------
output:False
True
True
False
False
True
I.iterating string using for loop:
string is sequence type and also iterable using for loop.
EG1:#iterating string using for loop
s="venkateshwaraswamy"
for i in s:
print(s)
print(i)
--------------------------------------------------------
output:venkateshwaraswamy
v
venkateshwaraswamy
e
venkateshwaraswamy
n
venkateshwaraswamy
k
venkateshwaraswamy
a
venkateshwaraswamy
t
venkateshwaraswamy
e
venkateshwaraswamy
s
venkateshwaraswamy
h
venkateshwaraswamy
w
venkateshwaraswamy
a
venkateshwaraswamy
r
venkateshwaraswamy
a
venkateshwaraswamy
s
venkateshwaraswamy
w
venkateshwaraswamy
a
venkateshwaraswamy
m
venkateshwaraswamy
y
EG2:#iterating string using for loop
s="hello"
for i in s:
print(i)
print(s,end="\n")#this is default behaviour
print(s,end=" ")#print string with out new line
print(s,end="hi")#print hi after every string
--------------------------------------------------------
output:h
hello
hello hellohie
hello
hello hellohil
hello
hello hellohil
hello
hello hellohio
hello
hello hellohi
J.Testing string methods:
isalnum()- returns True if string is alphanumeric.
isalpha()-returns True if string contains only alphabets.
isdigit()-returns True if string contains only digits.
isidentifier-returns True if string is a valid identifier.
islower()-returns True if string is in lowercase.
isupper()-returns True if string is in uppercase.
isspace()-returns True if string contains only whitespaces
EG:#Testing strings
s="kevukeka"
print(s.isalnum())
print("A".isalpha())
print("21".isdigit())
print("class".isidentifier())
print("hello".islower())
print("DAVID".isupper())
-------------------------------------------------------------
output:True
True
True
Tyguhrue
True
True
K.Searching methods for Substrings:
endswith(s1:str):bool-returns True strings endswith substring s1.
startswith(s1:str):bool-returns True string starts with substring s1.
count(substring):int-returns number of occurrences of substring the string.
find(s1):int-returns lowest index from where s1 starts in the string .if string not
found returns -1.
rfind(s1):int-returns the highest index from the where s1 starts in the string not
found returns -1.
EG:#searching methods for substrings
s="welcome to python"
print(s.endswith("thon"))
print(s.startswith("good"))
print(s.find("come"))
print(s.find("become"))
print(s.rfind("o"))
print(s.count("o"))
print(" ".isspace())
--------------------------------------------------------
output:True
False
3
-1
15
3
True
L.Converting strings:
capitalize():str-returns a copy of this string with only the first character
capitalized.
lower():str-returns the string by converting every character to lowercase.
upper():str-returns the string by converting every character to uppercase.
title():str-the function return string by capitalizing the first letter of
everyword in the string.
swapcase():str-return a string in which the lowercase letter is converted to
uppercase and uppercase to lowercase.
replace(old,new):str-this function returns new string by replacing the occurrence
of old string with new string.
EG: #converting strings
s="String in PYTHON"
print(s.capitalize())
print(s.title())
print(s.lower())
print(s.upper())
print(s.swapcase())
print(s.replace('i','o'))
-----------------------------------------------
output:String in python
String In Python
string in python
STRING IN PYTHON
sTRING IN python
Strong on PYTHON
3.List:
list type is another sequence type defined by the list class of python.
list allows you add,delete,process elements in very simple ways.
list is very similar to arrays.
A.Creating list in python:
EG:#creating list:
list1=list()
list2=list([8,6,4,2])
list3=list(["hari","bharath","mahesh"])
list4=list("python")
print(list1)
print(list2)
print(list3)
print(list4)
------------------------------------------------------------------
output:[]
[8, 6, 4, 2]
['hari', 'bharath', 'mahesh']
['p', 'y', 't', 'h', 'o', 'n']
B.Accessing elements in list:
you can use index operator([])to access individual elements in the list.list index
starts from 0.
EG:#Accessing elements in list
list1=[90,56,23,12]
print(list1[3])
----------------------------------------------------------------------
output:12
C.List common operations:
x in s - True if element x is in sequence s.
x not in s - False if element x is not in sequence s.
s1+s2 - Concatenate two sequences s1 and s2.
s*n,n*s - n copies of sequence s concatenated.
s[i]- ith element in sequence s.
len(s)-length of sequence
min(s)-smallest element in sequence s.
max(s)-largest element in sequence s.
sum(s)-sum of all numbers in sequence s.
for loop-traverses elements from left to right in a for loop.
EG:#list common operations
list1=[45,34,23,12,65]
print(34 in list1)
print(23 not in list1)
list2=[45,23,12]
list3=list1+list2
print(list3)
print(list3*2)
print(list1[4])
print(len(list1))
print(min(list1))
print(max(list1))
print(sum(list1))
#iterating using for loop
list1=[89,34,23,78]
for i in list1:
print(i)
-----------------------------------------------------------------------
output:True
False
[45, 34, 23, 12, 65, 45, 23, 12]
[45, 34, 23, 12, 65, 45, 23, 12, 45, 34, 23, 12, 65, 45, 23, 12]
65
5
12
65
179
89
34
23
78
D.List slicing:
slice operator ([start:end]) allows to fetch sublist from list .it works similar to
string.
EG:#list slicing operator
list2=["hari","bharath","nayak","venky"]
print(list2[1:3])
print(list2[:2])
print(list2[1:])
--------------------------------------------------------------------
output:['bharath', 'nayak']
['hari', 'bharath']
['bharath', 'nayak', 'venky']
E.Commonly used list methods with return type:
append(x:object):none- Adds an element x to the end of the list and returns none.
count(x:object):int- Returns the number of times element x appears in the list.
extend(l:list):none-appends all the elements in l to list and returns none.
index(x:object):int-returns the index of the first occurrence of element x in the
list.
insert(index:int,x:object):none- inserts an element x at a given index.note: that
the first element in the list has index 0 and returns none.
remove(x:object):none-removes the first occurrence of element x from the list and
returns none.
reverse():none-reverse the list and returns none.
sort():none-sorts the elements in the list in ascending order and returns none.
pop(i):object-removes the element at the given position and returns it.the
parameter i is optional.if it is not specified,pop() removes and returns the last
element in the list.
EG:#commonly used list methods with return type
list1=[23,34,45,24,56,67]
list2=[45,34,89,90]
list1.append(89)
print(list1)
print(list1.count(24))
list1.extend(list2)
print(list1)
print(list1.index(45))
list1.insert(0,45)
print(list1)
list1.remove(34)
print(list1)
list1.reverse()
print(list1)
list1.sort()
print(list1)
list1.pop()
print(list1)
--------------------------------------------------------------
output:[23, 34, 45, 24, 56, 67, 89]
1
[23, 34, 45, 24, 56, 67, 89, 45, 34, 89, 90]
2
[45, 23, 34, 45, 24, 56, 67, 89, 45, 34, 89, 90]
[45, 23, 45, 24, 56, 67, 89, 45, 34, 89, 90]
[90, 89, 34, 45, 89, 67, 56, 24, 45, 23, 45]
[23, 24, 34, 45, 45, 45, 56, 67, 89, 89, 90]
[23, 24, 34, 45, 45, 45, 56, 67, 89, 89]
F.List Comprehension:
EG:#List comprehension
for x in list1:
print(x)
list1=[x for x in range(10)]
print(list1)
list2=[x+1 for x in range(10)]
print(list2)
list3=[x for x in range(10) if x%2==0 ]
print(list3)
--------------------------------------------------------
output:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 2, 4, 6, 8]
4.Tuple:
Tuples are very similar to list but once a tuple is created,you cannot
add,delete,replace,reorder elements.
Tuples are immutable.
A.creating Tuples:
EG:#Creating tuples
t1=()
t2=(11,22,33)
t3=tuple([1,2,3,4])
t4=tuple("abc")
print(t1)
print(t2)
print(t3)
print(t4)
------------------------------------------------------------------
output:()
(11, 22, 33)
(1, 2, 3, 4)
('a', 'b', 'c')
B.Tuple functions:
Functions like max,min,len,sum can also be used with tuples.
EG:#Tuple functions
t1=([23,45,67,78])
print(len(t1))
print(min(t1))
print(max(t1))
print(sum(t1))
----------------------------------------------------------------------------
output:4
23
78
213
C.Iterating through tuples:
Tuples are iterable using for loop
EG:#Iterating the tuples using for loop
t1=([12,23,34,45,67,78])
for i in t1:
print(i,end=" ")
--------------------------------------------------------------------------------
output:12 23 34 45 67 78
D.Slicing Tuples:
Slicing operators works same in tuples as in list and string
EG:#Slicing operator
t1=([34,56,27,58])
print(t1[1:4])
print(t1[:3])
print(t1[2:])
print(t1[1:-1])
-----------------------------------------------------------------------------------
output:[56, 27, 58]
[34, 56, 27]
[27, 58]
[56, 27]
E.in and not in operator:
we can use in and not in operators to check existance of item in tuples.
EG:#in and not in operators
t1=(["hari","lohith","ajay"])
print("hari" in t1)
print("ajay" not in t1)
--------------------------------------------------------------------------
output:True
False
5.Dictionary:
Dictionary is python data type that is used to store key value pairs.
It enables you to quickly retrieve,add,remove,modify values using key.
Dictionary is very similar to Hashmap in java.
Dictionaries are mutable.
A.Creating Dictionary:
Dictionaries can be created using pair of curly braces { }.
Each item in the dictionary consist of key,followed by colon,which is followed by
value.
and each item is sepearted using commas(,).
Key must be of hashtable type ,but value can be of any type.Each key in the
dictionary must be unique.
EG:#Creating dictionary
friends={'tom':'11-222-333','jerry':'666-777-111'}
print(friends)
--------------------------------------------------------------------------
output:{'tom': '11-222-333', 'jerry': '666-777-111'}
B.Retrieving,Modifying,adding,deleting elements in the Dictionary:
EG:
friends={'jerry':'888-999-444','tom':'333-222-444','jhon':'555-444-333'}
print(friends)#printing dictionary
print(friends['tom'])#retrieveing
friends['luis']='222-999-555';#adding
print(friends)
friends['tom']='777-666-444';#modifying
print(friends)
del friends['tom'];#deleting
print(friends)
-----------------------------------------------------------------------------------
-----------------------
output:{'jerry': '888-999-444', 'tom': '333-222-444', 'jhon': '555-444-333'}
333-222-444
{'jerry': '888-999-444', 'tom': '333-222-444', 'jhon': '555-444-333', 'luis': '222-
999-555'}
{'jerry': '888-999-444', 'tom': '777-666-444', 'jhon': '555-444-333', 'luis': '222-
999-555'}
{'jerry': '888-999-444', 'jhon': '555-444-333', 'luis': '222-999-555'}
C.Looping items in the Dictionary:
EG:#looping the items in the dictionary
friends={'jerry':'888-999-444','tom':'333-222-444','jhon':'555-444-333'}
for i in friends:
print(i,":",friends[i])
-----------------------------------------------------------------------------------
-----------------------------------
output:jerry : 888-999-444
tom : 333-222-444
jhon : 555-444-333
D.Find the length of the dictionary:
we can use len() function to find the length of the dictionary.
EG:#len()
friends={'jerry':'888-999-444','tom':'333-222-444','jhon':'555-444-333'}
print(len(friends))
-----------------------------------------------------------------------------------
---------------------------------------
output:3
E.Equality Tests in Dictionary:
== and != operators tells whether dictionary contains same items are not.
NOTE:you can't use other relational operators like <,>,<=,>= to compare
dictionaries.
EG:#Equality operators ==,!=
d1={'mike':'333-111','ajay':'999-666-444'}
d2={'mike':'333-111','ajay':'999-666-444'}
print(d1==d2)
print(d1!=d2)
-----------------------------------------------------------------------------------
------------------------------------------
output:True
False
F.Dictionary Methods:
popitem()-Returns randomly select item from the dictionary and also remove
selected item.
clear()-Delete everything from dictionary
keys()-return keys in dictionary as tuples.
values()-return values in dictionary as tuples.
get(key)-return value of the key.if key is not found it returns None.instead of
throwing keyerrorexception
pop(key)-remove the item from the dictionary.if key is not found key error will be
thrown.
EG:#Dictionary methods
d1={'mike':'333-111','ajay':'999-666-444'}
print(d1.popitem())
print(d1)
print(d1.clear())
print(d1)
print(d1.keys())
print(d1.values())
print(d1.get('mike'))
print(d1.pop('mike'))
-----------------------------------------------------------------------------------
----------------------------------------
output:{'ajay':'999-666-444'}
None
mike,ajay
333-111,999-666-444
333-111
333-111
File Handling:
we can use file handling to read and write data to and from the file.
File operations-
-opening a file
-closing a file
-writing data in to file
-reading data from file
-Appending data from a file
-Looping through the data using for loop
A.opening and closing Files:
before reading/writing you first need to open the file.
Syntax of a opening a file
f=open(filename,mode)
After you have finished reading/writing to the file you need to close the file
using close() method like this
f.close()
Different modes of opening a file are
'r'-open a file for read only
'w'-open a file writing .if file already exists its data will be cleared before
opening ,otherwise new file will be created.
'a'-opens a file in append modei.e to write a data to the end of the file.
B.Writing Data into file:
C.Reading data from the file:
to read data back from the file you need one of these three methods
read([number])-return specified number of characters from the file.if omitted it
will read the entire contents of the file.
readline()-return the next line of the file.
readlines()-Read all the lines as a list of strings in the file.
D.Appending data:
to append the data you need to open the file in 'a' mode.
E.Looping through the data using for loop
EG:#file operations:read,close,write,open,append,for loop
file=open('C:\demos\jai.txt','w')
file.write("hello welcome to my python world\n")
file.write("hello welcome to my best world\n")
file.close()
file=open('C:\demos\jai.txt','r')
print(file.read())
file.close()
file=open('C:\demos\jai.txt','r')
print(file.read(5))
file.close()
file=open('C:\demos\jai.txt','r')
print(file.readline())
file.close()
file=open('C:\demos\jai.txt','r')
print(file.readlines())
file.close()
file=open('C:\demos\jai.txt','a')
file.write("hello welcome to my future world\n")
file.write("hello welcome to my world\n")
file.close()
file=open('C:\demos\jai.txt','r')
for line in file:
print(line)
file.close()
-----------------------------------------------------------------------------------
---------------------
output:hello welcome to my python world
hello welcome to my best world
hello
hello welcome to my python world
class B(A):
a,b=60,40
def m2(self,a,b):
print(a+b)
print(self.a+self.b)
print(super().a+super().b)
print(globals()['a']+globals()['b'])
bobj=B()
bobj.m2(100,300)
-----------------------------------------------------------------------------------
-----------------------
output:400
100
90
17
3.To invoke parent class constructor:
EG:#to invoke parent class constructor
class A:
def __init__(self):
print("this is constructor from class A")
class B(A):
def __init__(self):
print("this is constructor of class B")
super().__init__()#approach 1
A.__init__(self)#approach 2
bobj=B()
-----------------------------------------------------------------------------------
---------------
output:this is constructor of class B
kjthis is constructor from class A
this is constructor from class A
POLYMORPHISM:
Sometimes an object comes in many types or forms.
If we have a button ,there are many different draw outputs(round button,check
button,square button,button with image)but they do share the same logic onClick().
We can access them using the same method.This idea is called Polymorphism.
Overriding:
EG:
#ovverriding variables
class A:
name="hari"
class B(A):
name="jaikrishna"
bobj=B()
print(bobj.name)
-----------------------------------------------------------------------------------
-------------------
output:jaikrishna
EG:
#overriding methods
class A:
def m1(self):
return o
class B(A):
def m1(self):
return 10
bobj=B()
print(bobj.m1())
-----------------------------------------------------------------------------------
------------------------
output:10
Method overloading:
In python you can define a method in such way that there are multiple ways to call
it.
Given a single method or function .we specify the no of parameters our self.
EG:
#overloading methods
class A:
def display(self,name=None):
if name is None:
print("hello"+name)
else:
print("hello")
obj=A()
obj.display("hari")
-----------------------------------------------------------------------------------
-------------------------
OUTPUT:hello
MODULES:
Module is a python file (.py) containing a set of functions you want to include in
your application.
A module's contents are accessed with the import staement.
EG1:
operations.py
def add(num1,num2):
print(num1+num2)
def mul(num1,num2):
print(num1*num2)
------------------------------------------------------------------------------
main.py
#approach 1
import operations
operations.add(10,20)
operations.mul(10,20)
#approach 2
from operations import add,mul
add(19,90)
mul(20,20)
#approach 3
from operations import *
add(10,20)
mul(20,60)
-----------------------------------------------------------------------------------
--
output:30
200
109
400
30
1200
EG2:bird.py
def fly():
print("animal cant fly")
def color():
print("animal is in black color")
-----------------------------------------------------------------------------------
-----------
#approach 1
import bird
bird.fly()
bird.color()
#approach 2
from bird import fly,color
fly()
color()
#approach3
from bird import *
fly()
color()
-----------------------------------------------------------------------------------
-------------------
output:animal cant fly
animal is in black color
animal cant fly
animal is in black color
animal cant fly
animal is in black color
EG3:a.py
class Animal:
def display(self):
print("i like cow")
-----------------------------------------------------------------------------------
-----------------
b.py
class Bird:
def display(self):
print("I like parrot")
-----------------------------------------------------------------------------------
------------------
#approach1
import a
import b
aobj=a.Animal()
aobj.display()
bobj=b.Bird()
bobj.display()
#approach 2
from a import Animal
from b import Bird
aobj=Animal()
aobj.display()
bobj=Bird()
bobj.display()
-----------------------------------------------------------------------------------
------------------------------
output:i like cow
I like parrot
i like cow
I like parrot
EG4:dir()-mrthod returns how many classes are there in it.
ab.py
class A:
pass
class B:
def m1(self):
print("this is method m1")
def m2(self):
print("this is method m2")
-----------------------------------------------------------------------------------
------
#dir()
import ab
print(dir(ab))
-----------------------------------------------------------------------------------
--------
output:['A', 'B', '__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__']
*args & **kwargs:-
what is *args?
*args:(*-represents the multiple values and args represents the variables.)
*args allow us to pass variable number of arguments to the function.
def sum(a,b):
print("sum is",a+b)
this program only accepts two numbers ,what if you want to pass more than two
arguments ,this is where *args comes into play.
NOTE:name of *args is just convention you can use anything
that is a valid identifier .eg:*myargs is perfectly valid.
EG:#*args
def sum(*args):
s=0
for i in args:
s+=i
print("sum is:",s)
sum(1,2)
sum(1,2,3)
---------------------------------------------------------------------------
output:sum is:3
sum is:6
EG2:
#*args
def my_three(a,b,c,d):
print(a,b,c,d)
args=[1,2,3,4]
my_three(*args)
------------------------------------------------------------------------------
output:1 2 3 4
what is **kwargs?
**kwargs allow us to pass variable number of keyword argument like this
*-key,*-value
func_name(name='tim',team='school')
EG1:#**kwargs
def my_three(a,b,c):
print(a,b,c)
a=['a':"one",'b':"two",'c':"three"]
my_three(**a)
-------------------------------------------------------------------------------
output:one two three
EG2:#**kwargs
def my_func(**kargs):
for i,j in kargs.items():
print(i,j)
my_func(name='tom',spot='football',roll=10)
-----------------------------------------------------------------------------------
-----
OUTPUT:name tom
spot football
roll 10
EXCEPTION HANDLING:
Exception is an abnormal condition.
Exception is an event that disrupts the normal flow of the program.
Error is a programming mistake.
Errors are two types :1.syntax error 2.logic error
case1:Exception occured --->except-->finally
case2:Exception occured-->Not handled-->finally
case3:Exception not occured-->no except-->else-->finally
MultiException Blocks:
statements under the else clause run only when no exception is raised.
statements in finally block will run every time no matter exception occurs or not.
Raising exceptions:
To raise your exceptions from the your own methods you need to use raise keyword
like this.
raiseExceptionClass("your argument")
Using Exception Objects:
try:
#this code is excepted to throw exception
except ExceptionType ex:
#code to handle exception
EG:#Handling exception with try and except block
print("program is started")
try:
print(10/0)
except ZeroDivisionError:
print("entered into except block and handle exception")
print("program is finished")
#Handling exception with try and except block
print("program is started")
try:
print(10/5)
except ZeroDivisionError:
print("entered into except block and handle exception")
print("program is finished")
#Handling exception with try and except block
print("program is started")
try:
print(10/0)
except ZeroDivisionError:
print("entered into except block and handle exception")
except TypeError:
print("enterd into except block and handle exception")
print("program is finished")
#Handling exception with try and except block
print("program is started")
try:
print(10/5)
except ZeroDivisionError:
print("entered into except block and handle zerodivision error exception")
except TypeError:
print("enterd into except block and handle etypeerrorxception")
print("program is finished")
#Handling exception with try and except block
print("program is started")
try:
print(10/5)
except ZeroDivisionError:
print("entered into except block and handle zerodivision error exception")
except TypeError:
print("enterd into except block and handle etypeerrorxception")
print("program is finished")
else:
print("enterd into else block........")
#Handling exception with try and except block
print("program is started")
try:
print(10/0)
except ZeroDivisionError:
print("entered into except block and handle zerodivision error exception")
except TypeError:
print("enterd into except block and handle etypeerrorxception")
print("program is finished")
else:
print("entered into else block......")
#Handling exception with try and except block
print("program is started")
try:
print(10/5)
except ZeroDivisionError:
print("entered into except block and handle zerodivision error exception")
except TypeError:
print("enterd into except block and handle etypeerrorxception")
print("program is finished")
else:
print("entered into else block........")
finally:
print("entered into finally block.......")
def sum(start,end):
result=0
for i in range(start,end+1):
result=result+1
print(result)
sum(100,200)
#return none
def test():
i=100
return
print(test())
#local and global variables
global_var=12
def fun():
local_var=100
print(global_var)
fun()
#global
a=100
def fun():
global t
t=90
print(t)
print(a)
fun()
#positional arguments
def name_args(name,greeting):
print(name+" "+greeting)
name_args("hari","good morning")
#keyword arguments
def name_args(name,greeting):
print(name+" "+greeting)
name_args(name="hari",greeting="good morning")
#positional&keyword arguments
def name_args(name,greeting):
print(name+" "+greeting)
name_args("hari",greeting="good morning")
#returning multiple values
def bigger(a,b):
if a>b:
return a,b
else:
return b,a
s=bigger(100,200)
print(s)
print(type(s))
-----------------------------------------------------------------------------------
------------------
output:101
None
12
90
100
hari good morning
hari good morning
hari good morning
(200, 100)
<class 'tuple'>
LAMBDA FUNCTION:
A function which has no name is known as a lambda function.
this is also known as anonymous function
A lambda function can take any number of arguments ,but only have one expression.
syntax:lambda arguments:expression
eg:#lambda function
x=lambda a:a+10
print(x(5))
x=lambda a,b:a+b
print(x(10,80))
x=lambda a,b,c:a+b+c
print(x(10,20,30))
#add
def add(a):
a=a+10
return a
print(add(10))
-----------------------------------------------------------------------------------
---------
output:15
90
60
20