Python UNIT-1 - 240323 - 213721
Python UNIT-1 - 240323 - 213721
Introduction to Python
• Python is a general purpose high-level, interpreted, interactive and object-oriented
scripting language.
• It uses English keywords frequently where as other languages use punctuation, and it
has fewer syntactical constructions than other languages therefore It is very simple
and easy to use
• Python is recommended as first programming language for beginners.
In Python:
print("Hello World")
History of Python
• But officially Python was made available to public in 1991. The official Date
of Birth for Python is : Feb 20th 1991.
6) Object-Oriented Language
• Python supports object oriented language and concepts of classes
and objects come into existence.
7) Extensible
• Extensible. If needed, you can write some of your Python code in
other languages like C++. This makes Python an extensible language,
meaning that it can be extended to other languages.
8) Large Standard Library
• Python has a large and broad library and provides rich set of module and
functions for rapid application development.
10) Integrated
• It can be easily integrated with languages like C, C++, JAVA etc.
• Limitations of Python:
1. Performance wise not up to the mark b'z it is interpreted language.
2. Not using for mobile Applications. Disadvantages of Python
3. Python is not as fast as C and C++, It means it is slower than C/C++:
4. Does not check variable type at compile time. It use dynamic type so flexible that
Python interpreter cannot check the type for mismatch at the compile time.
Flavors of Python:
1.CPython:
• It is the standard flavor of Python. It can be used to work with C language
Applications.
2.Jython or JPython:
• It is for Java Applications. It can run on JVM.
3. IronPython:
• It is for C#.Net platform.
4.PyPy:
• The main advantage of PyPy is performance will be improved because JIT
compiler is available inside PVM.
5.Ruby Python:
• For Ruby Platforms.
6. Anaconda Python :
• It is specially designed for handling large volume of data processing.
Python Versions:
• Python 1.0V introduced in Jan 1994.
• Python 2.0V introduced in October 2000.
• Python 3.0V introduced in December 2008.
Current versions:
• Python 3.7.4 July 8, 2019
• Python 2.7.16 March 4, 2019
Other Versions:
• Python 3.6.9 July 2, 2019
• Python 2.7.15 May 1, 2018
• Python 3.6.1 March 21, 2017
• Python 2.7.13 April 9, 2012
The two versions Python 2 and Python 3 are very much different from each other.
A list of differences between Python 2 and Python 3 are given below:
• Python 2 uses print as a statement and used as print "something" to print some
string on the console.
• On the other hand, Python 3 uses print as a function and used as
print("something") to print something on the console.
• Python 2 uses the function raw_input() to accept the user's input. It returns the
string representing the value, which is typed by the user.
• To convert it into the integer, we need to use the int() function in Python.
• On the other hand, Python 3 uses input() function.
• In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit
string type is Unicode.
Difference between python 2 and 3
#Python 2
print "hello"
print ("hello world")
n=input("enter no1:")
n1=input("enter no 2:")
a=n+n1
b=n-n1
print a
print b
C:\Python27>python add.py
hello
hello world
enter no1:6
enter no 2:7
13
-1
Ex. Python 3
print ("hello")
a=input("enter no")
b=input("enter no")
c=a+b
print (c)
>>>
==== RESTART: C:/Users/HP50/AppData/Local/Programs/Python/Python38-
32/add.py ===
hello
enter no6
enter no7
67
>>>
print ("hello")
a=int(input("enter no"))
b=int(input("enter no"))
c=a+b
print (c)
c=a-b
print(c)
>>>
==== RESTART: C:/Users/HP50/AppData/Local/Programs/Python/Python38-32/add.py ===
hello
enter no2
enter no8
10
-6
>>>
How to Run Python Programs
• There are three way to execute python code they are given below;
1)Interactive Mode
2)Script Mode
3)Using IDE
1.Interactive interpreter prompt
Output:
C:\Python>python multiassn.py
0.1
100
string
C:\Python>
Keywords in Python
• raw_input()
• input()
1.raw_input():
• This function always reads the data from the keyboard in the form
of String Format. We have to convert that string type to our
required type by using the corresponding type casting methods.
Eg:
• x=raw_input("Enter First Number:")
• print(type(x)) It will always print str type only for any input type
• raw_input() : the function raw_input() always evaluates and return
string type data.
Syntax : x=raw_input()
• If input value is integer type then it returns string value or convert
integer value into string value.
• If input value is string type then it returns string value.
• x=input("Enter Value”)
• Print(type(x))
• 10 ===> int
• “siva"===>str
• 10.5===>float
• True==>bool
• Note: But in Python 3 we have only input() method and raw_input()
method is not available.
Python3 input() function behaviour exactly same as raw_input() method
of Python2. i.e every input value is treated as str type only.
• raw_input() function of Python 2 is renamed as input() function in
Python3
Example:
type(input("Enter value:"))
Enter value:10
<class 'str'>
INPUT Function:
• To get input from the user you can use the input function.
• The syntax for input statements is
input([prompt])
• Here prompt is the string to display on the screen.
• it is optional.
• Whatever you enter as input, the input() function converts it into a
string. If you enter an integer value, still it will convert it into a string.
• If you want to input number from a user, you need to perform type
conversion on the input value.
Example
Output:
name = input("Enter Employee Name: ")
salary = input("Enter salary: ")
C:\Python>python in.py
company = input("Enter Company name: ")
Enter Employee Name: Maya
print("\n")
Enter salary: 40000
print("Printing Employee Details")
Enter Company name: BRECW
print("Name", "Salary", "Company")
print(name, salary, company)
Printing Employee Details
Name Salary Company
Maya 40000 BRECW
C:\Python>
number = input("Enter number ") Output:
name = input("Enter name ") C:\Python>python in1.py
print("\n") Enter number 4
print("Printing type of a input Enter name maya
value") Printing type of a input value
print("type of number", type of number <class 'str'>
type(number))
type of name <class 'str'>
print("type of name", type(name))
C:\Python>
Accept an Integer input from User
• Let’s see how to accept an integer value from a user in Python. We need to
convert an input string value into an integer using a int() function.
E.g.
first_number = int(input("Enter first number "))
second_number = int(input("Enter second number "))
print("\n")
print("First Number:", first_number)
print("Second Number:", second_number)
sum1 = first_number + second_number
print("Addition of two number is: ", sum1)
• Output:
• Let’s see how to accept float value from a user in Python. You need to
convert user input to the float number using the float() function as
we did for the integer value.
print("Hello World")
By default output values are seperated by space.If we want we can specify seperator
by using "sep" attribute
a,b,c=10,20,30
print(a,b,c,sep=',’)
print(a,b,c,sep=':’)
C:\Python>python test.py
10,20,30
10:20:30
• Form-4: print() with end attribute:
Example:
print("Hello")
print(“shiva")
print(“welcome")
Output:
Hello
Shiva
Welcome
The default value for end attribute is \n,which is nothing but new line
character.
• If we want output in the same line with space
Example:
print("Hello”,end=‘ ‘)
print(“shiva“,end=‘ ‘)
print(“welcome“)
Output:
Hello Shiva Welcome
• Form-5: print(object) statement:
We can pass any object (like list,tuple,set etc)as argument to the
print() statement
l=[10,20,30,40]
t=(10,20,30,40)
print(l)
print(t)
Form-6: print(formatted string):
%i====>int
%d====>int
%f=====>float
%s======>String type
Syntax:
print("formatted string" %(variable list))
Example:1
a=10
b=20
c=30
print("a value is %i" %a)
print("b value is %d and c value is %d" %(b,c))
Output
a value is 10
b value is 20 and c value is 30
Example-2
s=“shiva"
list=[10,20,30,40]
print("Hello %s ...The List of Items are %s" %(s,list))
Output:
• Hello shiva ...The List of Items are [10, 20, 30, 40]
• Note: Python contains several inbuilt functions and In Python
everything is object
1.type()
to check the type of variable
2. id()
to get address of object
Python Data Types
1.char or byte: Python does not have a char or byte type to hold either single
character or 8-bit integers. It uses Strings for character type and integer type to
represent 8 bit number.
2.Pointer
• Python manages memory automatically, there is no need to access pointer
addresses.
• The closest to an address that you can get in Python is by looking at an
object's identity using the id() BIF.
3.short and long
• Python's integers are the universal "standard" integer type, obviating the need
for three different integer types, e.g., C's int, short, and long.
• Python use a single type integer ,even when the size of an integer is exceeded.
So python not uses short and long types.
• It uses integer only instead of short and long.
4.Double:
• C has both a single precision float type and double-precision double type.
Python's float type is actually a C double.
• So python float is double-precision type.
Categorizing the Standard Types
• There are three different models to help categorize the standard types, with
each model showing us the interrelationships between the types.
• These models help us obtain a better understanding of how the types are
related, as well as how they work.
1.Storage Model
2.Update Model
3.Access Model
Storage Model:
• Categorization of the types is described by how many objects can be
stored in an object of this type.
• In python a type which holds a single literal object we will call atomic or
scalar storage.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Output:
color[0] = "pink" ['red', 'blue', 'green']
color[-1] = "orange" ['pink', 'blue', 'orange']
print(color)
Access Model: previous two models of categorizing the types are useful when
being introduced to Python.
• They are not the primary models for differentiating the types.
• In order to access the stored values we use access model.
• Access Model is categorized in 3 types:
>>> str(1)
'1‘
>>> str(2e10)
'20000000000.0'
Eg: x = eval(“10+20+30”)
print(x)
Output: 60
Program:
a = True Output:
b = False True
print(a) False
print(b)
Strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
• Python allows for either pairs of single or double quotes.
s1=‘geetha govindam'
s1=“vijayadevarakonda"
• By using single quotes or double quotes we cannot represent
multi line string literals.
s1=“abc
pqrstuv”
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1=''‘siva
bhargav'''
s1=""“siva
bhargav""“
We can also use triple quotes to use single quote or double quote in our String.
''' This is " character'''
' This i " Character '
We can embed one string in another string
'''This "Python class very helpful" for java students'''
• Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.
• We can do the negative slicing in the string; it starts from the rightmost
character, which is indicated as -1. The second rightmost index indicates -
2, and so on. Consider the following image.
Strings
Program: Output:
str ="WELCOME" C:\Python>python str1.py
print(str) WELCOME
W
print(str[0])
LCO
print(str[2:5]) LCOME
print(str[2:]) WELCOMEWELCOME
print(str * 2) WELCOMEIT
print (str + "IT")
C:\Python>
Strings Methods
• capitalize()
str1=“hello"
print(str1.capitalize()) # Hello
• Center(width, fillchar)
str1="welcome“
print(str1.center(15,"*")) # ****welcome*****
• len(string)
str1="welcome"
print(len(str1)) #7
Strings Methods
• count(str, beg= 0, end=len(string))
str1="welcome"
print(str1.count('e',0,len(str1))) #2
print(str1.count('e’,2,len(str1)))
• isupper()
str2="welcome2017"
print (str2.isupper()) # False
Strings Methods
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!’]
a = "Hello"
b = "World"
c=a+b
print(c)
c=a+""+b
print(c)
Output:
HelloWorld
Hello World
str1="welcome"
print(str1.count('e',2,len(str1)))
str1="welcome"
print(str1.endswith('e',0,len(str1)))
str1="welcome"
print(str1.startswith('we',2,len(str1)))
str5="welcome to java"
print(str5.replace("java", "python"))
str1="welcome"
print(str1.find('el',0,len(str1)))
str2="welcome2017@"
print(str2.isalnum())
str2="welcome"
print(isalpha(str2))
a = "Hello World Welcome to Python"
print(a.split(" ")) # returns ['Hello', ' World’, 'Welcome', 'to', 'Python']
• Output:
C:\Users\HP>strmethods.py
Hello
****welcome*****
1
True
False
welcome to python
1
False
True
['Hello', 'World', 'Welcome', 'to', 'Python']
C:\Users\HP>
list data type
• A list can be defined as a collection of values or items
of different types.
• The items in the list are separated with the comma (,)
and enclosed with the square brackets [].
• An ordered, mutable, heterogeneous collection of
elements is nothing but list, where duplicates also
allowed.
• If we want to represent a group of individual objects
as a single entity where insertion order preserved and
duplicates are allowed, then we should go for List.
• List is dynamic because based on our requirement we can increase
the size and decrease the size.
-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
Creation of List Objects:
⦁ We can create empty list object as follows...
list=[]
print(list)
print(type(list))
Output
[]
<class 'list'>
• Example
list=[10,20,30,40]
2) >>> list[0]
3) 10
4) >>> list[-1]
5) 40
6) >>> list[1:3]
7) [20, 30]
8) >>> list[0]=100
9) >>> for i in list:print(i)
10) ...
11) 100
12) 20
13) 30
• With dynamic input:
list=input("Enter List:")
print(list)
print(type(list))
C:\Python>python test.py
Enter List:[10,20,30,40]
[10, 20, 30, 40]
• With list() function:
l=list(range(0,10,2))
print(l)
print(type(l))
C:\Python>python test.py
[0, 2, 4, 6, 8]
Accessing elements of List:
• We can access elements of the list either by using index or by using slice
operator(:)
1. By using index:
• print(list[0]) ==>10
• print(list[-1]) ==>40
• print(list[10]) ==>IndexError: list index out of range
2. By using slice operator:
Syntax:
list2= list1[start:stop:step]
start ==>it indicates the index where slice has to start default
value is 0
Output
C:\Python>python test.py
1
4
2
0
3. index() function: Returns the index of first occurrence of the specified item.
• Eg:
n=[1,2,2,2,2,3,3]
print(n.index(1)) ==>0
print(n.index(2)) ==>1
print(n.index(3)) ==>5
print(n.index(4)) ==> ValueError: 4 is not in list.
• Note: If the specified element not present in the list then we will get Value
Error. Hence before index() method we have to check whether item present
in the list or not by using in operator.
• print( 4 in n)==>False
Manipulating elements of List:
1. append() function:
We can use append() function to add item at the end of the list.
Eg:
list=[]
list.append("A")
list.append("B")
list.append("C")
print(list)
C:\Python>python test.py
C:\Python>python test.py
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
2.insert() function:
To insert item at specified index position
n=[1,2,3,4,5]
n.insert(1,888)
print(n)
C:\Python>python test.py
[1, 888, 2, 3, 4, 5]
Eg:
n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
C:\Python>python test.py
[999, 1, 2, 3, 4, 5, 777]
• Note: If the specified index is greater than max index then element will be
inserted at last position. If the specified index is smaller than min index then
element will be inserted at first position.
Differences between append() and insert()
• In List when we add any element it will come in last i.e. it will be last
element.
Output:
C:\Python>python test.py
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']
4. remove() function:
We can use this function to remove specified item from the list. If the item
present multiple times then only first occurrence will be removed.
Example:
n=[10,20,10,30]
n.remove(10)
print(n)
C:\Python>python test.py
[20, 10, 30]
5. pop() function:
• It removes and returns the last element of the list.
• This is only function which manipulates list and returns some element.
Eaxample:
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)
C:\Python>python test.py
40
30
[10, 20]
If the list is empty then pop() function raises IndexError
• In general we can use pop() function to remove last element of the list.
• But we can also use pop() to remove elements based on index.
• n.pop(index)===>To remove and return element present at specified
index.
• n.pop()==>To remove and return last element of the list
Example:
n=[10,20,30,40,50,60]
print(n.pop()) #60
print(n.pop(1)) #20
print(n.pop(10)) ==>IndexError: pop index out of range
Note:
• List objects are dynamic. i.e based on our requirement we can
increase and decrease the size.
• append(),insert() ,extend() ===>for increasing the size/growable
nature
• remove(), pop() ======>for decreasing the size /shrinking nature
clear() function:
• We can use clear() function to remove all elements of List.
Eg:
n=[10,20,30,40]
print(n)
n.clear()
print(n)
Output
C:\Python>python test.py
[10, 20, 30, 40]
[]
III. Ordering elements of List:
1. reverse():
Output:
C:\Python>python test.py
[40, 30, 20, 10]
2. sort() function:
The sort function sort the list in ascending order by default.
• For numbers ==>default natural sorting order is Ascending Order
• For Strings ==> default natural sorting order is Alphabetical Order
• Syntax
list.sort(reverse=True|False)
Reverse is Optional.
reverse=True will sort the list descending.
Default is reverse=False(ascending order)
Example:1
n=[20,5,15,10,0]
n.sort()
print(n) #[0,5,10,15,20]
Example:2
a=["Si", "sa", "Bh", "Pr", "GB"]
a. sort()
print(a) # ['Bh', ‘GB', 'Pr', 'Si', 'sa']
To sort in reverse of default natural sorting order:
We can sort according to reverse of default natural sorting order by using
reverse=True argument.
Eg:
n=[40,10,30,20]
n.sort()
print(n) ==>[10,20,30,40]
n.sort(reverse=True)
print(n) ===>[40,30,20,10]
n.sort(reverse=False)
print(n) ==>[10,20,30,40]
Example: (Descending order)
a=["Si", "sa", "Bh", "Pr", "GB"]
a.sort(reverse=True)
print(a)
Output:
['sa', 'Si', 'Pr', ‘GB', 'Bh']
• The sorted() function returns a sorted list of the specified iterable object.
l=[6,5,8,9]
l.sort(reverse=True)
print(l)
l1=sorted(l)
print(l1)
l2=sorted(l,reverse=True)
print(l2)
>>>
=== RESTART: C:/Users/HP50/AppData/Local/Programs/Python/Python38-32/lsort.py ==
[9, 8, 6, 5]
[5, 6, 8, 9]
[9, 8, 6, 5]
>>>
• Note: To use sort() function, compulsory list should contain only
homogeneous elements.otherwise we will get TypeError
Eg:
n=[20,10,"A","B"]
n.sort()
print(n)
print(lst)
Python List Operations
• The concatenation (+) and repetition (*) operator work in the same
way as they were working with the strings.
Consider a List l1 = [1, 2, 3, 4], and
l2 = [5, 6, 7, 8]
Operator Description Example
The repetition operator
enables the list elements
Repetition L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
to be repeated multiple
times.
It concatenates the list
Concatenation mentioned on either side l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
of the operator.
It returns true if a
particular item exists in a
Membership print(2 in l1) prints True.
particular list otherwise
false.
The for loop is used to
for i in l1: print(i) Output1
Iteration iterate over the list
234
elements.
Tuple:
2. t=(10,)
t=10,
creation of single valued tuple ,parenthesis are optional,should ends with comma
3. t=10,20,30
t=(10,20,30)
creation of multi values tuples & parenthesis are optional
4. By using tuple() function:
list=[10,20,30]
t=tuple(list)
print(t)
Eg:2
t=()
print(type(t)) # tuple
Accessing elements of tuple:
• We can access either by index or by slice operator.
Exmaple:
t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) IndexError: tuple index out of range
2. By using slice operator:
Example:
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[::2])
Output
(30, 40, 50)
(30, 40, 50, 60)
(10, 30, 50)
Tuple vs immutability:
2. count()
To return number of occurrences of given element in the tuple
Eg:
t=(10,20,10,10,20)
print(t.count(10)) #3
3. index()
• returns index of first occurrence of the given element.
• If the specified element is not available then we will get ValueError.
Eg:
t=(10,20,10,10,20)
print(t.index(10)) #0
print(t.index(30)) ValueError: tuple.index(x): x not in tuple
4. sorted()
• To sort elements based on default natural sorting order
t=(40,10,30,20)
t1=sorted(t) We can sort according to reverse of
print(t1) default natural sorting order as follows
print(t)
t1=sorted(t,reverse=True)
print(t1) [40, 30, 20, 10]
Output
[10, 20, 30, 40]
(40, 10, 30, 20)
5. min() and max() functions:
• These functions return min and max values according to default
natural sorting order.
Eg:
t=(40,10,30,20)
print(min(t)) #10
print(max(t)) #40
6. cmp():
• It compares the elements of both tuples.
• If both tuples are equal then returns 0
• If the first tuple is less than second tuple then it returns -1
• If the first tuple is greater than second tuple then it returns +1
Eg:
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2)) # -1
print(cmp(t1,t3)) # 0
print(cmp(t2,t3)) # +1
Note: cmp() function is available only in Python2 but not in Python 3
t1=(10,20,30,40)
t2=(40,60,70,80)
print(cmp(t1,t2))
C:\Python27>python tucmp.py
-1
C:\Python27>
t1=(50,20,30,40)
t2=(40,60,70,80)
print(cmp(t1,t2))
C:\Python27>python tucmp.py
1
C:\Python27>
t1=(20,70,30,40)
t2=(40,60,70,80)
print(cmp(t1,t2))
C:\Python27>python tucmp.py
-1
C:\Python27>
• Differences between List and Tuple:
• List and Tuple are exactly same except small difference: List objects
are mutable where as
• Tuple objects are immutable.
• In both cases insertion order is preserved, duplicate objects are
allowed, heterogenous
• objects are allowed, index and slicing are supported
Set Data Type:
• If we want to represent a group of values without duplicates where
order is not important then we should go for set Data Type.
• If we want to represent a group of unique values as a single entity
then we should go for set.
• Duplicates are not allowed.
• Insertion order is not preserved. But we can sort the elements.
• Indexing and slicing not allowed for the set.
• Heterogeneous elements are allowed.
• Set objects are mutable i.e once we creates set object we can perform any
changes in that object based on our requirement.
• We can represent set elements within curly braces and with comma separation
• Creation of Set objects:
Eg:
s={10,20,30,40}
print(s)
print(type(s))
Output
>>>
{40, 10, 20, 30}
<class 'set'>
>>>
• We can create set objects by using set() function
s=set(any sequence)
Eg 1:
l = [10,20,30,40,10,20,10]
s=set(l)
print(s) # {40, 10, 20, 30}
Eg 2:
s=set(range(5))
print(s) #{0, 1, 2, 3, 4}
Note: While creating empty set we have to take special care.
• Compulsory we should use set() function.
Eg: Eg:
s={} s=set()
print(s) print(s)
print(type(s)) print(type(s))
Output Output
{} set()
<class 'dict'> <class 'set'>
Important functions of set:
add(x):
Adds item x to the set
Eg:
s={10,20,30}
s.add(40);
print(s)➔ #{40, 10, 20, 30}
s={10,20,30} • Output
s.add(40); >>>
print(s) {40, 10, 20, 30}
s.add(50) {40, 10, 50, 20, 30}
print(s) {40, 10, 50, 20, 30}
s.add(40); {40, 10, 50, 20, 30}
print(s) >>>
s.add(10);
print(s)
2. update([x,y,z]):
To add multiple items to the set.
Eg:
s={10,20,30}
s.update([50,60])
print(s)
s={10,20,30} • output
s.update([50,60]) >>>
print(s) RESTART:
s.update([80,40]) C:/Users/91986/AppData/Local/Progra
ms/Python/Python36/setupdate.py
print(s)
{10, 50, 20, 60, 30}
s.update([50,40])
{40, 10, 80, 50, 20, 60, 30}
print(s)
{40, 10, 80, 50, 20, 60, 30}
>>>
• Note: We can use add() to add individual item to the Set, where as we can use
update() function to add multiple items to Set.
• add() function can take only one argument where as update() function can
take any number of arguments.
s={10,20,30}
s1=s.copy()
print(s1)
• 4. pop():It removes and returns some random element from the set.
Eg:
S = {"ram", "rahim", "ajay", "rishav", "aakash"}
# Popping three elements and printing them
print(S.pop())
print(S.pop())
print(S.pop())
# The updated set
print("Updated set is", S)
Output
>>>
= RESTART: C:/Users/91986/AppData/Local/Programs/Python/Python36/setpop1.py =
ajay
rishav
rahim
Updated set is {'ram', 'aakash'}
>>>
5. remove(x):It removes specified element from the set. If the specified element not
present in the Set then we will get Key Error.
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50
6. discard(x): It removes the specified element from the set. If the specified element
not present in the set then we won't get any error.
s={10,20,30}
s.discard(10)
print(s) ===> {20, 30}
s.discard(50)
print(s) ==> {20, 30}
7.clear(): To remove all elements from the Set.
s={10,20,30}
print(s)
s.clear()
print(s)
Output
{10, 20, 30}
set()
• Mathematical operations on the Set:
1.union():
x.union(y) ==>We can use this function to return all elements present in both
sets
x.union(y) or x|y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}
• 2. intersection():
x.intersection(y) or x&y
• Returns common elements present in both x and y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}
3. difference():
• x.difference(y) or x-y
• returns the elements present in x but not in y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10, 20}
print(y-x) #{50, 60}
4.symmetric_difference():
x.symmetric_difference(y) or x^y
Returns elements present in either x or y but not in both.
Eg:
x={10,20,30,40}
y={30,40,50,60}
Output
D:\Python_classes>py test.py
Enter List of values: [10,20,30,10,20,40]
{40, 10, 20, 30}
• Set Comprehension:
>>>fs.add(70)
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs.remove(10)
AttributeError: 'frozenset' object has no attribute 'remove'
Dictionary
• We can use List,Tuple and Set to represent a group of individual
objects as a single entity.
• If we want to represent a group of objects as key-value pairs
then we should go for Dictionary.
Eg:
rollno----name
phone number--address
ipaddress---domain name
• Duplicate keys are not allowed but values can be duplicated.
• Heterogeneous objects are allowed for both key and values.
• insertion order is not preserved
• Dictionaries are mutable
• Dictionaries are dynamic
• indexing and slicing concepts are not applicable
d[100]=“ananthapur"
d[200]=“srikakulam"
d[300]=“prakasam"
print(d) #{100: ‘ananthapur ', 200: ‘srikakulam ', 300: ‘prakasam '}
• If we know data in advance then we can create dictionary as follows
d= {100: ‘ananthapur ', 200: ‘srikakulam ', 300: ‘prakasam '}
d={key:value, key:value}
• How to access data from the dictionary?
• Output:
{100: ‘pavani', 200: ‘rani', 300: 'shivani'}
{100: ‘pavani', 200: ‘rani', 300: 'shivani', 400: ‘Geetha'}
{100: ‘Prerana', 200: ‘rani', 300: 'shivani', 400: ‘Geetha'}
delete elements from dictionary:
• It deletes entry associated with the specified key. If the key is not available
then we will get Key Error.
• Syntax: del d[key]
Eg:
d={100:"N",200:"T",300:"g"}
print(d) Output
del d[100] {100: 'N', 200: 'T', 300: 'g'}
print(d) {200: 'T', 300: 'g'}
del d[400] KeyError: 400
• del d
To delete total dictionary. Now we cannot access d
Eg:
d={100:"baby",200:"smart",300:"Maha"}
print(d)
del d
print(d)
Output:
{100: 'baby', 200: 'smart ', 300: 'Maha'}
Name Error: name 'd' is not defined
• d.clear() : To remove all entries from the dictionary
Eg:
d={100:"pavani",200:"rani",300:"shivani"}
print(d)
d.clear()
print(d)
Output
{100: 'pavani', 200: ‘rani', 300: 'shivani'}
{}
• Important functions of dictionary:
1. dict():
• To create a dictionary
3. clear():
To remove all elements from the dictionary
4. get():
To get the value associated with the key
• d.get(key)
If the key is available then returns the corresponding value otherwise returns None. It
wont raise any error.
• d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns default
value.
d={100:"pavani",200:"rani",300:"shivani"}
print(d)
print(d.get(200))
print(d.get(400,"abc"))
d.clear()
print(d)
>>>
{100: 'pavani', 200: 'rani', 300: 'shivani'}
rani
abc
{}
>>>
• 4. popitem():
• It removes an arbitrary item(key-value) from the dictionary and returns it.
Eg:
d={100:"Mahesh",200:"raviteja",300:"charan"}
print(d)
print(d.popitem())
print(d)
Output
{100: 'Mahesh', 200: 'raviteja', 300: 'charan'}
(300, 'charan')
{100: 'Mahesh', 200: 'raviteja‘}
Output:
Mahesh
{200:’raviteja’,300:’charan’}
KeyError: 400
• 5. keys():
• It returns all keys associated with dictionary
Eg:
d={100:"Pavan",200:"ravi",300:"shiva"}
print(d.keys())
for k in d.keys():
print(k)
Output
dict_keys([100, 200, 300])
100
200
300
6. values():
• It returns all values associated with the dictionary.
Eg:
d={100:"Orbiter",200:"Lander",300:"Rover"}
print(d.values())
for v in d.values():
print(v)
Output:
dict_values(['Orbiter', 'Lander', 'Rover'])
Orbiter
Lander
Rover
• 7. items():
• It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
Eg:
d={100:"Orbiter",200:"Lander",300:"Rover"}
print(d.items())
for k,v in d.items():
print(k,"--",v)
Output:
dict_items([(100, 'Orbiter'), (200, 'Lander'), (300, 'Rover')])
100 -- Orbiter
200 -- Lander
300 -- Rover
8. copy():
• To create exactly duplicate dictionary(cloned copy)
Syntax: d1=d.copy();
9. setdefault():
Syntax: d.setdefault(k,v)
• If the key is already available then this function returns the corresponding
value.
• If the key is not available then the specified key-value will be added as new
item to the dictionary.
• Eg:
d={100:"Ganguly",200:"Sehwag",300:"Dhoni"}
print(d.setdefault(400,"Kohli"))
print(d)
print(d.setdefault(100,"sachin"))
print(d)
Output:
Kohli
{100: 'Ganguly', 200: 'Sehwag', 300: 'Dhoni', 400: 'Kohli'}
Ganguly
{100: 'Ganguly', 200: 'Sehwag', 300: 'Dhoni', 400: 'Kohli'}
10. update():
• All items present in the dictionary x will be added to dictionary d.
d.update(x)
Example:
d = {1: “whatsapp", 2: “facebook"}
d1 = {2: “instagram"}# updates the value of key 2
d.update(d1) Output:
print(d)
{1: ‘whatsapp', 2: ‘instagram'}
d1 = {3: “faceapp"}# adds element with key 3 {1: ‘whatsapp', 2: ‘instagram', 3: ‘faceapp'}
d.update(d1)
print(d)
• The update method directly takes a key-value pair and puts it into the
existing dictionary. The key value pair is the argument to the update
function. We can also supply multiple key values as shown below.
• Example
CountryCodeDict = {"India": 91, "UK" : 44 , "USA" : 1, "Spain" : 34}
print(CountryCodeDict)
CountryCodeDict.update( {'Germany' : 49} )
print(CountryCodeDict)
# Adding multiple key value pairs
CountryCodeDict.update( [('Austria', 43),('Russia',7)] )
print(CountryCodeDict)
• Output(python3)
• >>>
• = RESTART:
C:/Users/HP50/AppData/Local/Programs/Python/Python38-
32/dicupdate.py
• {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34}
• {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34, 'Germany': 49}
• {'India': 91, 'UK': 44, 'USA': 1, 'Spain': 34, 'Germany': 49, 'Austria': 43,
'Russia': 7}
• >>>
Output(python2)
C:\>cd python27
C:\Python27>python dict.py
{'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'Germany': 49, 'Spain': 34, 'India': 91, 'USA': 1, 'UK': 44}
{'USA': 1, 'India': 91, 'Austria': 43, 'Germany': 49, 'UK': 44, 'Russia': 7,
'Spain': 34}
C:\Python27>
None Data Type:
• None means Nothing or No value associated.
• If the value is not available,then to handle such type of cases None introduced.
• It is something like null value in Java.
Eg:
def m1():
a=10
print(m1())
Output:
None
Python Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic Operators
consider a=10,b=20
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
• Division operator (/) always performs floating point arithmetic. Hence it will
always returns float value.
• Floor division (//) can perform both floating point and integral arithmetic.
We can use + operator for str concat also.
>>> “Python"+123
Output :TypeError: must be str, not int
>>> “Python"+"123"
Output: Python123
Comparison (Relational) Operators
If values of two operands are not equal, then condition (a <> b) is true. This is
<>
becomes true. similar to != operator.
• The following is the list of all possible compound assignment operators in Python
+=, -=, *=, /=, %=, //=, **=, &=, |=, ^=
Eg:1 x=10,
x+=10 ====> x = x+10
Eg:2
x=10
x+=20
print(x) ==>30
Eg: 3
x=10
x&=5
print(x) ==>0
Logical Operators
Operator Description Example
And
If both the operands are true then (a and b) is
Logical
condition becomes true. true.
AND
Or If any of the two operands are non-zero (a or b) is
Logical OR then condition becomes true. true.
not
Used to reverse the logical state of its Not (a and
Logical
operand. b) is false.
NOT
Logical Operators example:
and, or ,not
Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
Eg3: Program for minimum of 3 numbers
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
min=a if a<b and a<c else b if b<c else c
print("Minimum Value:",min)
Eg4: Program for maximum of 3 numbers
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
c=int(input("Enter Third Number:"))
max=a if a>b and a>c else b if b>c else c
print("Maximum Value:",max)
Special operators:
• Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
Identity Operators
Operator Description Example
Statement Description
if statement consists of a boolean expression followed by one or more
if statements
statements.
if statement can be followed by an optional else statement, which executes
if...else statements
when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if statement(s).
if Statement
• The if statement contains a logical expression using which data is compared and a
decision is made based on the result of the comparison.
• The condition is tested. If the condition is True, then the statements given after
colon (:) are executed.
• Indentation : Python relies on indentation (whitespace at the beginning of a line)
to define scope in the code. Other programming languages often use curly-brackets
for this purpose.
• Syntax:
if Condition:
Statements
if Statement
Program:
a=10
b=15
Output:
B is Big
if a < b :
print "b is Big“ The value is 15
print "The value is", b
a=10
b=15
if a < b :
print ("b is Big")
print ("The value is", b)
C:\Python>python if1.py
File "if1.py", line 4
print ("b is Big")
^
IndentationError: expected an indented block
C:\Python>
if….else Statement
• An else statement contains the block of code that
executes if the conditional expression in the if
statement resolves to 0 or a FALSE value.
• Syntax:
if Condition:
Statements
else:
Statements
if Statement
Program:
a=48
b=34 Output:
if a < b: a is big
print "b is big“ a value is 48
print "b value is", b
else:
END
print "a is big "
print "a value is", a
print "END"
• Write a program to check if a number is Odd or Even
We can write an entire if… else statement in another if… else statement called nesting, and
the statement is called nested if.
• Syntax
if expression1:
statement(s)
if expression2:
statement(s):
else:
statement(s)
else:
statement(s)
Example program
n = int(input(“Enter number:”))
If (n<=15):
if (n == 10):
print(‘play cricket’)
else:
print(‘play kabadi’)
else:
print(‘Don’t play game’)
Iteration Statements
• In general, statements are executed sequentially: The
first statement in a function is executed first, followed
by the second, and so on. There may be a situation
when you need to execute a block of code several
number of times.
• A loop statement allows us to execute a statement or
group of statements multiple times.
Output: Output:
1 1
END 2
2 3
END END
3
END
for Loop
• The for loop is useful to iterate over the elements of a sequence.
• It means, the for loop can be used to execute a group of statements
repeatedly depending upon the number of elements in the sequence.
• The for loop can work with sequence like string, list, tuple, range etc.
• Syntax:
for variable in sequence:
Statements
Example:
for i in [1,2,3,4]:
print i
print "END”
C:\Python>python forp.py
1
2
3
4
END
How to read multiple values from the keyboard in a single line:
Example2:
r = range(10,20)
for i in r : print(i) 10 to 19
Example3:
r = range(10,20,2)
for i in r : print(i) 2 means increment value
10,12,14,16,18
We can access elements present in the range Data Type by using index.
r=range(10,15)
print(r[0]) #10
print(r[15]) #IndexError: range object index out of range
Eg:
r[0]=100
TypeError: 'range' object does not support item assignment
for Loop
Program: Program:
for i in range(1,4): for i in range(1,4):
print(i) print(i)
print ("END“) print ("END“)
Output: Output:
1 1
END 2
2 3
END END
3
END
Nested Loops
• It is possible to write one loop inside another loop.
• For example, we can write a for loop inside a while loop or a for loop
inside another for loop.
Nested Loops
Program: Program:
for i in range(1,6): for i in range(1,6):
for j in range(1,i+1): for j in range(1,6):
print(j) print (j)
print ("“)
print ("“)
Jump Statements
• There are Three jump statements,
➢break
➢continue
➢pass
break statement
• The break is a keyword in python which is used to bring the program
control out of the loop.
• The break statement breaks the loops one by one, i.e., in the case of
nested loops, it breaks the inner loop first and then proceeds to outer
loops.
• In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after
the loop.
• The break is commonly used in the cases where we need to break the
loop for a given condition.
break statement Example
Program:
n=input("Enter the n value")
count=0
for i in range(2,n): Output:
if n%i==0: Enter the n value: 7
count=count+1 Prime Number
break
if count==0:
print ("Prime Number“)
else:
print ("Not Prime Number“)
continue statement
• The continue statement in Python is used to bring the program control to the
beginning of the loop.
• The continue statement skips the remaining lines of code inside the loop and
start with the next iteration.
• It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.
Program:
Output:
for number in range(1,7): Number is 1
if number == 4: Number is 2
continue Number is 3
print ('Number is ' + number) Number is 5
Number is 6
pass statement
• In Python, the pass keyword is used to execute nothing; it means,
when we don't want to execute code, the pass can be used to execute
empty.
• It is the same as the name refers to.
• It just makes the control to pass by without executing any code.
• If we want to bypass any code pass statement can be used.Program:
for number in range(1,7): Output:
Number is 1
if number == 4:
Number is 2
pass Number is 3
print ('Number is ' + number) Number is 4
Number is 5
Number is 6
for i in [1,2,3,4,5]: 1
if(i==4): 2
pass 3
print("This is pass block",i) This is pass block 4
print(i) 4
5