Professional Documents
Culture Documents
Unit-1 - OVERVIEW OF PYTHON
Unit-1 - OVERVIEW OF PYTHON
Features of Python:
1. It is Simple
2. Easy to learn
3. Free and Open source
4. High level language: Strong abstraction from the details of the computer like registers,
memory address and call stacks.
5. Compiled as well as Interpreted: For the most part, Python is an interpreted language and
not a compiled one, although compilation is a step. Python code, written in .py file is first
compiled to what is called bytecode which is stored with a .pyc or .pyo format. This bytecode
is a low-level set of instructions that can be executed by an interpreter.
6. Embedded: The code of the other programming language can use in the Python source code.
We can use Python source code in another programming language as well. It can embed other
language into our code.
7. Extensible ( Support for other languages ): Python is an Extensible language. We can write
us some Python code into C or C++ language and also we can compile that code in C/C++
language.
8. Dynamically Typed: Python is a dynamically-typed language. That means the type (for
example- int, double, long, etc.) for a variable is decided at run time not in advance because
of this feature we don’t need to specify the type of variable.
9. Platform Independent: Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a program
only once.
10. Procedure as well as Object oriented
11. Large standard Library support: Python has a large standard library which provides a rich
set of module and functions so you do not have to write your own code for every single thing.
There are many libraries present in python for such as regular expressions, unit-testing, web
browsers, etc.
12. GUI Programming Support
1
LJIET Sem-5 PDS (3150713)
Interpreter Compiler
It Translates program one statement at a time. Compiler scans the whole program in one go.
Considering it scans code one line at a time, As it scans the code in one go, the errors (if any)
errors are shown line by line. are shown at the end together.
It does not require source code for later
It requires source code for later execution.
execution.
It takes large amount of time to analyse the
It takes less amount of time to analyse the source
source code but the overall execution time is
code but the overall execution time is slower.
comparatively faster.
Example: Python, Ruby, Perl, etc. Example: C, C++ etc.
C v/s Python :
C Python
C is a general-purpose, procedural computer Python is an interpreted, high-level, general-
programming language. purpose programming language.
It is easier to write a code in Python as the
Program syntax is harder than Python.
number of lines is less comparatively.
Python follows both the Procedure Oriented
C follows Imperative (Procedure Oriented)
as well as Object oriented Programming
programming paradigm.
paradigm.
C has a limited number of built-in functions. Python has a large library of built-in functions.
C programs runs faster than python program. Python code runs much slower than c.
Type Discipline is Static and Weak. Type Discipline is Dynamic and Strong.
It supports the concept of Switch Statement. It does not have Switch Statement.
It supports for, while and do…while loop. It supports only for and while loop.
Pointers are available in C. No pointers functionality available in Python.
No exception Handling. Supports Exceptional Handling mechanism.
Array Index can be positive as well as negative
Array Index Should be positive integer.
integer.
C uses traditional braces to start and end blocks. Python uses indentation to start and end blocks.
A semicolon (;) is used to terminate the
New Line (enter) indicates end of the statement.
statement.
2
LJIET Sem-5 PDS (3150713)
3
LJIET Sem-5 PDS (3150713)
Variable:
Variables provide a way to associate names with objects.
In Python, variable names can contain uppercase and lowercase letters, digits (but they
cannot start with a digit), and the special character _.
Python variable names are case-sensitive e.g., Julie and julie are different names.
Finally, there are a small number of reserved words (sometimes called keywords) in Python
that have built-in meanings and cannot be used as variable names. Different versions of
Python have slightly different lists of reserved words.
Example: a=5
Python allows multiple assignment. The statement: x, y = 2, 3 works same as x=2 and y=3.
Comments:
Text following the symbol # is not interpreted by Python.
For example:
# This is a single line comment.
2. Numeric Type:
int: An integer number is a number without any decimal point or fraction part.
a= 15, b= -30, c=0
float: float data type represents an floating point numbers. A floating number is a number
with decimal point or fraction part.
a= 55.679995; b= 22.55e3
Complex: complex number is a number that is written in the form of “a+b j” or “a+b J”.
where ‘a’ is a real part and ‘b’ is an imaginary part.
a= - 1 – 5.5 j
Bool: There are two Boolean values “True” and “False”. Python internally represents True
as 1 and false as 0. A blank string like “” is also represents as False.
4
LJIET Sem-5 PDS (3150713)
3. Sequences:
str: str represents string data type. A string is a group of characters. Strings are enclosed in
single quotes or double quotes.
S1 = “Python”
S2=‘Java’
Bytes: bytes data type represents a group of bye numbers just like an array does. The byte
number is any positive integer from 0 to 255.
elements= [10, 20, 30 40]
x = bytes (elements)
print (x[0]) # To print single element
for i in x: # To print all elements
print (i)
Bytearray: bytearray data type represents a group of bye numbers just like an bytes does. But
the main difference is bytes type array cannot be modified but bytearray type array can be
modified.
elements= [10, 20, 30, 40]
x = bytearray(elements)
print (x[0]) # To print single element
for i in x: # To print all elements
print (i)
x[1] = 80 # Can modify values
List: List is an ordered sequence of values, where each value is identified by an index. In
Python programming, a list is created by placing all the items (elements) inside a square
bracket [ ], separated by commas. It can have any number of items and they may be of different
types (integer, float, string etc.).
my_list = [1, 2, 3]
my_list = [1, "Hello", 3.4]
Tuple: Like strings, tuples are ordered sequences of elements. The difference is that the
elements of a tuple need not be characters. The individual elements can be of any type, and
need not be of the same type as each other. In Python programming, a list is created by placing
all the items (elements) inside a round bracket ( ) , separated by commas. It can have any
number of items and they may be of different types (integer, float, string etc.). we cannot
change the elements of a tuple once it is assigned whereas in a list, elements can be changed.
my_tuple = (1, 2, 3)
my_tuple = (1, "Hello", 3.4)
Range : returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number..
r = range(10)
s = list(r)
print (s)
O/P: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5
LJIET Sem-5 PDS (3150713)
4. Sets: A set is an unordered collection of elements. It means that the elements may not appear
in the same order as they are entered into set. Set does not accept duplicate elements.
S = {10, 20, 30, 40}
5. Mappings: a map represents a group of elements in the form of key and value pairs so that
when the key is given, we can retrieve the value associated with it. The dict (dictionary) data
type is an example of map.
my_dict = {1: 'apple', 2: 'ball'}
Operators:
Arithmetic Operator:
Divide left operand by the right one print ('x / y =', x/y)
/
(always results into float) # Output: x / y = 3.75
Logical Operator:
Operators Meaning Example
x = True, y = False
and True if both the operands are true print ('x and y is', x and y)
# Output: x and y is False
print('x or y is', x or y)
or True if either of the operands is true
# Output: x or y is True
True if operand is false (complements print('not x is', not x)
not
the operand) # Output: not x is False
6
LJIET Sem-5 PDS (3150713)
Comparison Operator:
Not equal to - True if operands are not print ('x != y is', x!=y)
!=
equal (always results into float) # Output: x != y is True
Greater than or equal to - True if left print ('x >= y is',x>=y)
>= operand is greater than or equal to the
# Output: x >= y is False
right
Less than or equal to - True if left print ('x <= y is',x<=y)
<=
operand is less than or equal to the right # Output: x <= y is True
Assignment Operator:
7
LJIET Sem-5 PDS (3150713)
Bitwise Operator:
Identity Operator:
Membership Operator:
8
LJIET Sem-5 PDS (3150713)
Branching Program:
9
LJIET Sem-5 PDS (3150713)
Examples of if else:
If Statement:
temp = 20
if temp > 10 :
print ("It is cold!)
If else Statement:
temp = 20
if temp > 10 :
print ("It is cold!)
else:
print ("It feels good!)
Nested Condition:
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
10
LJIET Sem-5 PDS (3150713)
Iteration:
A generic iteration (also called looping) mechanism is depicted in Figure. Like a conditional
statement it begins with a test. If the test evaluates to True, the program executes the loop
body once, and then goes back to revaluate the test.
This process is repeated until the test evaluates to False, after which control passes to the code
following the iteration statement.
Example: Example:
counter = 0
digits = [0, 1, 5]
while counter < 3:
for i in digits:
print ("Counter: ", counter)
print (i)
counter = counter + 1
else:
else:
print ("No items left.")
print ("Inside Else.")
Output: Output:
0 Counter: 0
1 Counter: 1
5 Counter: 2
No items left. Inside Else.
11
LJIET Sem-5 PDS (3150713)
Control Structure:
There are mainly three type of control structure in python:
BREAK: The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.
for letter in 'Python':
if letter == 't':
break
print ('Current Letter :', letter)
Output:
Current Letter: P
Current Letter: y
CONTINUE: The continue statement rejects all the remaining statements in the current
iteration of the loop and moves the control back to the top of the loop.
for letter in 'Python':
if letter == 'h':
continue
print 'Current Letter :', letter
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n
PASS: The pass statement is a null operation; nothing happens when it executes. The pass is
also useful in places where your code will eventually go, but has not been written yet
for letter in 'Python':
if letter == 'h':
pass
print 'This is pass block' print
'Current Letter :', letter
Output:
Current Letter: P
Current Letter: y
Current Letter: t
This is pass block
Current Letter: h
Current Letter: o
Current Letter: n
12
LJIET Sem-5 PDS (3150713)
Function:
Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
The ability for programmers to define and then use their own functions, as if they were built-
in, is a qualitative leap forward in convenience.
Syntax:
def name of function (list of formal parameters):
body of function
def is a reserved word that tells Python that a function is about to be defined.
Example:
def greet(name):
print("Hello, " + name + ". Good morning!")
#Function Call
greet('World')
Output:
Hello, World. Good morning!
Example: Output:
def demo(name, age): Name: Python
print (“Name: “,name) Age: 20
print (“Age: “,age)
demo (“Python”,20)
2. Python Keyword Arguments: A keyword argument is where you provide a name to the
variable as you pass it into the function. When we call functions in this way, the order
(position) of the arguments can be changed. we can mix positional arguments with keyword
arguments during a function call. But we must keep in mind that keyword arguments must
follow positional arguments. Having a positional argument after keyword arguments will
result into errors.
Example: Output:
def demo(name, age): Name: Python
print (“Name: “,name) Age: 25
print (“Age: “,age)
demo (age =25, name=“Python”)
13
LJIET Sem-5 PDS (3150713)
3. Python Default Arguments: Function arguments can have default values in Python. We can
provide a default value to an argument by using the assignment operator (=). Any number of
arguments in a function can have a default value. But once we have a default argument, all
the arguments to its right must also have default values. This means to say, non-default
arguments cannot follow default arguments.
Example: Output:
def demo(name, age=20): Name: Python
print (“Name: “,name) Age: 20
print (“Age: “,age)
demo (“Python”)
Example: Output:
def demo(*name): Name: Python
for i in name: Name: Java
print (“Name: “,i) Name: AI
Name: ML
demo (“Python”, “Java”, “AI”, “ML”)
Lambda:
A lambda function is a small anonymous function. A lambda function can take any number
of arguments, but can only have one expression.
Syntax:
lambda argument_list : expression
Output: Output:
25 square of 5 = 25
14
LJIET Sem-5 PDS (3150713)
Map: The map() function acts on each element of the sequence and perhaps changes the
elements.
Syntax: map( function, sequence)
Example:
def squares(x):
return x*x
lst=[1,2,3,4,5]
lst1=list(map(squares,lst))
print (lst1)
Output: [1, 4, 9, 16, 25]
Filter: The filter() function is useful to filter out the elements of a sequence depending on
the result of a function.
Syntax: filter (function, sequence)
Example:
def is_even(x):
if x%2==0:
return True
else:
return False
lst= [10, 23, 45, 46, 79, 99]
lst1= list(filter(is_even,lst))
print (lst1)
Output: [10, 46]
15
LJIET Sem-5 PDS (3150713)
Output:
Globle Value outside function: 100
Local Value inside function: 10
If you want to access global variable inside the function then you have to use global
keyword
var = 100
# this function will not give error
def my_func():
global var
var = var + 10
print (“Value inside function:",var)
my_func()
print (“Value outside function:",var)
Output:
Value inside function: 110
Value outside function: 110
It is important to note that though the actual and formal parameters have the same name,
they are not the same variable. Each function defines a new name space, also called a
scope.
16
LJIET Sem-5 PDS (3150713)
Specification:
A specification of a function defines a contract between the implementer of a function and
those who will be writing programs that use the function. We will refer to the users of a
function as its clients. This contract can be thought of as containing two parts:
1. Assumptions: These describe conditions that must be met by clients of the function.
Typically, they describe constraints on the actual parameters. Almost always, they specify the
acceptable set of types for each parameter, and not infrequently some constraints on the value
of one or more of the parameters.
2. Guarantees: These describe conditions that must be met by the function, provided that it has
been called in a way that satisfies the assumptions.
Example:
def fact(n) :
"""Assumes that n is an int > 0
Returns n!"""
result = 1
while n > 1 :
result = result * n
n -= 1
return result
The text between the triple quotation marks is called a doctoring in Python. By convention,
Python programmers use docstrings to provide specifications of functions. These docstrings
can be accessed using the built-in function help().
docstrings can also be accessed using: Function-Name.__doc__
Example:
print (fact.__doc__)
17
LJIET Sem-5 PDS (3150713)
Modules:
A module represents a group of classes, methods, functions and variables. When a module is
developed, it can be reused in any program that needs that module.
In python we have several in built modules like sys, io, time etc. just like this modules, we
can also create our own modules and use them whenever we need them.
Python modules allow us to easily construct a program from code in multiple files. A module
is a .py file containing Python definitions and statements. We could create, for example, a file
circle.py containing.
Example:
circle.py file:
pi = 3.14159
def area(radius):
return pi*(radius**2)
def circumference(radius):
return 2*pi*radius
def sphereSurface(radius):
return 4.0*area(radius)
circle_run.py file:
import circle import circle as c
print (circle.pi) print (c.pi)
print (circle.area(3)) print (c.area(3))
print (circle.circumference(3)) print (c.circumference(3))
Output:
3.14159
28.27431
18.849539999999998
Executing import M creates a binding for module M in the scope in which the
importation occurs. Therefore, in the importing context we use dot notation to indicate that
we are referring to a name defined in the imported module.
For example, outside of circle.py, the references pi and circle.pi can (and in this case do) refer
to different objects.
There is a variant of the import statement that allows the importing program to omit the
module name when accessing names defined inside the imported module. Executing the
statement from M import * creates bindings in the current scope to all objects defined within
M, but not to M itself.
For example, the code
from circle import *
18
LJIET Sem-5 PDS (3150713)
Recursion:
Recursion is the process of defining something in terms of itself. In simple words, it is a
process in which a function calls itself directly or indirectly.
Recursion is a method of solving a problem where the solution depends on solutions to smaller
instances of the same problem.
Advantages:
A complicated function can be split down into smaller sub-problems utilizing recursion.
Sequence creation is simpler through recursion than utilizing any nested iteration.
Recursive functions render the code look simple and effective.
Disadvantages:
A lot of memory and time is taken through recursive calls which makes it expensive for use.
Recursive functions are challenging to debug.
The reasoning behind recursion can sometimes be tough to think through.
Example: (Factorial)
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
Output:
Enter No: 4
The factorial of 4 is 24
19
LJIET Sem-5 PDS (3150713)
String:
Indexing in String:
Index represents the position number. They are written using square braces [ ]. By specifying
the index we can refer individual elements.
String[i] represents ith element of string. Positive index starts from left to right and negative
index starts from right to left (end of the string).
Slicing in String:
Slice represents a part or piece of a string.
Syntax: string_name [ start : stop : step_size ]
Example:
S1='core python'
print (S1 [0:9:1]) #accessing string from 0th to 8th element in steps of 1
print (S1[::]) #access string from start to last character
print (S1 [2:6:1]) #accessing strting from S1[2] to S1[5] element in steps of 1
print (str[::2]) #accessing entire strting in steps of 2
print (S1[::-1]) #reverse the string
Output:
core pyth
core python
re p
20
LJIET Sem-5 PDS (3150713)
cr yhn
nohtyp eroc
Repeating in String:
str='core python'
print (str*2)
s=str[5:7]*3
print(s)
Output:
core pythoncore python
pypypy
Concatenation of String:
str1='core python'
str2="programs"
str3=str1+str2
print (str3)
Comparing String:
str1="Box"
str2="box"
if(str1==str2):
print ("Both are same")
else:
print ("Both are not same")
21
LJIET Sem-5 PDS (3150713)
Method Description
len() Returns the length of string
count() Returns the number of times a specified value occurs in a string
upper() Converts a string into upper case
lower() Converts a string into lower case
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
Returns the string whose first letter is capital and remaining are
capitalize()
lowercase
startswith() Returns true if the string starts with the specified value
endswith() Returns true if the string ends with the specified value
rstrip() Returns a right trim version of the string
lstrip() Returns a left trim version of the string
strip() Returns a trimmed version of the string
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdigit() Returns True if all characters in the string are digits
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
istitle() Returns True if the string follows the rules of a title
isspace() Returns True if all characters in the string are whitespaces
Searches the string for a specified value and returns the position of where
find()
it was found
Searches the string for a specified value and returns the last position of
rfind()
where it was found
Searches the string for a specified value and returns the position of where
index()
it was found
Searches the string for a specified value and returns the last position of
rindex()
where it was found
Returns a string where a specified value is replaced with a specified
replace()
value
split() Splits the string at the specified separator, and returns a list
join() Joins the elements of an iterable to the end of the string
22
LJIET Sem-5 PDS (3150713)
Example:
#Changing case of a string:
str1="pYthon pRograMming is a fun" Output:
print("String: ",str1) String: pYthon pRograMming is a fun
print ("Upper: ",str1.upper()) Upper: PYTHON PROGRAMMING IS A FUN
print ("Lower: ",str1.lower()) Lower: python programming is a fun
print ("Swapcase: ",str1.swapcase()) Swapcase: PyTHON PrOGRAmMING IS A FUN
print ("Title: ",str1.title()) Title: Python Programming Is A Fun
print ("Capitalize: ",str1.capitalize()) Capitalize: Python programming is a fun
#Split() of string:
str1= "One, Two, Three, Four" Output:
str2= str1.split(',') ['One', ' Two', ' Three', ' Four']
print (str2)
#join() of string:
str1=('one','two','three') Output:
str2='-'.join(str1) one-two-three
print (str2)
23
LJIET Sem-5 PDS (3150713)
List:
List in Python can be written as a list of comma-separated values (items) between square
brackets.
List items are ordered, Mutable (changeable), and allow duplicate values.
Syntax for creating an empty list: list1 = []
List storing string data: List2 = [‘Python’ , ’Data Science’]
List storing heterogeneous data: List2 = [‘Hello World’ ,1,2.50,5+10j]
Method Description
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
copy() Returns a shallow copy of the list
index() Returns the index of the first matched item
count() Returns the count of occurrence of item passed as an argument
insert() Insert an item at the defined index
append() Add an element to the end of the list
extend() Add all elements of a list to the another list
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
del() Delete an item at particular index
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
min() Return the smallest item in the list.
max() Return the largest item in the list.
sorted() Return a new sorted list (does not sort the original list).
sum() Return the sum of all elements in the list.
all() Return True if all elements of the list are true (or if the list is empty).
Return True if any element of the list is true. If the list is empty, return
any()
False.
Return an enumerate object. It contains the index and value of all the
enumerate()
items of list as a tuple.
24
LJIET Sem-5 PDS (3150713)
Example:
# List with mixed DataTypes Output:
my_list = [1, "Hello", 3.4] [1, 'Hello', 3.4]
print(my_list)
#Indexing Output:
my_list = ['l','j','i','e','t','s','g','h','y'] l
print(my_list[0]) i
print(my_list[2]) t
print(my_list[4])
#Slicing Output:
my_list = ['l','j','i','e','t','s','g','h','y'] ['i', 't']
print(my_list[2:5:2]) ['l', 'j', 'i', 'e']
print(my_list[:-5]) ['s', 'g', 'h', 'y']
print(my_list[5:]) ['y', 'h', 'g', 's', 't', 'e', 'i', 'j', 'l']
print(my_list[::-1])
#Concatenation Output:
odd = [2, 4, 6, 8] [2, 4, 6, 8]
print(odd) + operator to combine two lists
print("+ operator to combine two lists") [2, 4, 6, 8, 9, 7, 5]
print(odd + [9, 7, 5])
25
LJIET Sem-5 PDS (3150713)
#Creating list using range() : We can use the range() to generate a sequence of integers which
#can be stored in a list.
lst=list(range(4,9,2))
print(lst)
26
LJIET Sem-5 PDS (3150713)
#sorted():Return a new sorted list (does not sort the list itself).
lst1=[3,6,2,1,25,69,9,1]
print(lst1)
print (sorted(lst1,reverse=True))#lst1.sort()
print (lst1)
27
LJIET Sem-5 PDS (3150713)
#any():Return True if any element of the list is true. If the list is empty, return False.
lst1=[0,1,2,3,4,5,6]; lst2=[0,0,0]
print (any(lst1), any(lst2))
#enumerate(): Return an enumerate object. It contains the index and value of all the items of
#list as a tuple
lst1=[11,12,30,4]
print (enumerate(lst1))
print (list(enumerate(lst1)))
28
LJIET Sem-5 PDS (3150713)
Tuple:
Method Description
len() Return the length (the number of items) in the list.
list() Convert an iterable object to a tuple.
index() Returns the index of the first matched item
count() Returns the count of occurrence of item passed as an argument
min() Return the smallest item in the list.
max() Return the largest item in the list.
sorted() Return a new sorted list (does not sort the original list).
Example:
#Tuple Declaration
t1=()
t2=(1, 'two', 3, 2.5)
t3=(12,) #singletone element
print (t1)
print (t2)
print (t3)
29
LJIET Sem-5 PDS (3150713)
student =(10,'Python',20,30,40)
print (student[0:2])
rno, name = student[0:2]
print (rno)
print (name)
#sorted(): Return a new ascending sorted tuple (does not sort the tuple itself),
#sorted(tup,reverse=True) will sort in reverse order.
tup1=(3,6,2,1)
print (sorted(tup1))
print (sorted(tup1,reverse=True))
30
LJIET Sem-5 PDS (3150713)
#Nested tuple
emp=((90,'Ram',30000),(52,'Shyam',25000),(64,'Krishna',35000))
print (emp)
print (emp[1][1])
print (sorted(emp))
print (sorted(emp,reverse=True))
print (sorted(emp,key=lambda x:x[1])) #sort on name
print (sorted(emp,key=lambda x:x[2])) #sort on salary
31
LJIET Sem-5 PDS (3150713)
Dictionary:
Dictionary in Python is an ordered collection of data values, used to store data values like a
map, which, unlike other Data Types that hold only a single value as an element, Dictionary
holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
In Python, a Dictionary can be created by placing a sequence of elements within curly {}
braces, separated by ‘comma’.
Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its Key:value.
Method Description
len() Return the length (the number of items) in the dictionary.
clear() Removes all the elements from the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist:
setdefault()
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
Return True if all keys of the dictionary are true (or if the dictionary
all()
is empty).
Return True if any key of the dictionary is true. If the dictionary is
any()
empty, return False.
sorted() Return a new sorted list of keys in the dictionary.
Output:
{'ML': '30', 'Python': '10', 'AI': '20'}
32
LJIET Sem-5 PDS (3150713)
Example:
#Dictionary Declaration
print("Displaying Dictionary")
my_dict = {}
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
my_dict = dict([(1,'apple'), (2,'ball')])
print(my_dict)
# fromkey method: Return a new dictionary with keys from seq and value
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
print(list(sorted(marks.keys())))
33
LJIET Sem-5 PDS (3150713)
#get(key[,d]): Return the value of key. If key does not exit, return d (defaults to None).
d={1:'Python',2:'Java'}
d[10]="Bye"
print (d.get(1,'none'))
print (d.get(3,'Key not exist'))
#pop(key[,d]): Remove the item with key and return its value or d if key is not found.
#If d is not provided and, raises KeyError
d={1:'Python',2:'Java',3:'AI'}
print (d.pop(1,'Not Present'))
print (d.pop(30,'Not Present'))
34
LJIET Sem-5 PDS (3150713)
#update([other]): Update the dictionary with the key/value pairs from other,
#overwriting existing keys
d={1:'Python',2:'Java',3:'AI'}
ud={3:'ML',4:'AI'}
d.update(ud)
print (d)
d.update({5:'AI++'})
print (d)
35
LJIET Sem-5 PDS (3150713)
Set:
Set items are unordered, mutable (changeable), and do not allow duplicate values.
We can create set using curly brackets.
We cannot access items in a set by referring to an index as sets are unordered the items has
no index.
Syntax for creating an empty set:
s1 = {}
s1=set()
Example:
s={1,2,3,4}
print ("set: ",s)
O/P: set: {1,2,3,4}
#Membership Operator
s={1,2,3,4} O/P:
print ("set: ",s) set: {1, 2, 3, 4}
print ("1 in Set: ",1 in s) 1 in Set: True
print ("9 in Set: ",9 in s) 9 in Set: False
36
LJIET Sem-5 PDS (3150713)
#Slice Operation
s={1,2,3,4,5}
print ("set: ",s)
print ("After Slicing: ",s[2])
O/P:
TypeError: 'set' object is not subscriptable
#intersection(): Returns a set that contains the similarity between two Sets.
x={1,2,3,4,5} O/P:
y={1,3,5} original set X: {1, 2, 3, 4, 5}
print("original set X:",x) original set Y: {1, 3, 5}
print("original set Y:",y) Intersection: {1, 3, 5}
print("Intersection:",x.intersection(y))
37
LJIET Sem-5 PDS (3150713)
# difference(): Return a set that contains the items that only exist in set x, and
not in set y, it does not change the original set x or y.
x = {1,2,3,4} O/P:
y = {1,3} original set X: {1, 2, 3, 4}
print("original set X:",x) original set Y: {1, 3}
print("original set Y:",y) Difference: {2, 4}
print("Difference: ",x.difference(y))
# difference_update(): Removes the items that are common in both the set from
the original Set. It returns none and updates the original set
x = {1,2,3,4} O/P:
y = {1,3} original set X: {1, 2, 3, 4}
print("original set X:",x) original set Y: {1, 3}
None
print("original set Y:",y)
Difference: {2, 4}
print(x.difference_update(y))
print("Difference: ",x)
38
LJIET Sem-5 PDS (3150713)
# issubset(): Returns True If all items in the set exists in the specified set, Else it
returns False
x={1,2,3,4,5} O/P:
y={1,3,5} X issubset Y: False
print("X issubset Y:",x.issubset(y)) Y issubset X: True
print("Y issubset X:",y.issubset(x))
# issuperset(): Returns True If all items in the specified set exists in the original
set, Else it retunes False.
x={1,2,3,4,5} O/P:
y={1,3,5} X issuperset Y: True
print("X issuperset Y:",x.issuperset(y)) Y issuperset X: False
print("Y issuperset X:",y.issuperset(x))
Frozenset:
A frozen set is a collection of elements which is unordered and unindexed.
Immutable
We can create frozen set using frozenset() method.
Syntax for creating a frozen set
s1 = {1,2,3,4,5}
fset = frozenset(s1)
39
LJIET Sem-5 PDS (3150713)
#Membership Operator
fs1=frozenset({1,2,3,4})
print(fs1)
print ("1 in fs1: ",1 in fs1)
print ("9 in fs1: ",9 in fs1)
O/P:
frozenset({1, 2, 3, 4})
1 in fs1: True
9 in fs1: False
#Accessing Items
fs1=frozenset({1,2,3,4})
for i in fs1:
print ('Item: ',i)
O/P:
Item: 1
Item: 2
Item: 3
40
LJIET Sem-5 PDS (3150713)
Item: 4
#concatenation of frozenset
fs1=frozenset({1,2,3,4})
fs2=frozenset({5,6,7})
print ("concatenation= ",fs1+fs2)
#Repetition of frozenset
fs1=frozenset({1,2,3,4})
print ("Repetition= ",fs1*2)
#Slicing of frozenset
fs1=frozenset({1,2,3,4})
print ("Slicing= ",fs1[2])
41
LJIET Sem-5 PDS (3150713)
Practice Code:
# Odd-Even
n=int(input('Enter No:'))
if n%2==0:
print(n, ' is Even.')
else:
print(n, ' is Odd.')
# Factorial
n=int(input('Enter No:'))
f=1
while n>0:
f*=n
n-=1
print('Factorial is: ',f)
#Prime No
num=int(input('Enter No:'))
flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a Prime Number")
else:
print(num, "is a Prime Number")
#Seq of Prime No
num=int(input('Enter No:'))
for j in range(2,num+1):
flag = False
for i in range(2, j):
if (j % i) == 0:
flag = True
break
if flag:
print(j, "is not a Prime Number")
else:
print(j, "is a Prime Number")
42
LJIET Sem-5 PDS (3150713)
n=5 *
* *
for i in range(0,n): * * *
for j in range(0,i+1): * * * *
print("* ",end="") * * * * *
print("\r")
n=5 $ $ $ $ $
$ $ $ $
for i in range(5,0,-1): $ $ $
for j in range(0,i): $ $
print("$ ",end="") $
print("\r")
n=5 # # # # #
# # #
for i in range(5,1,-2): #
for j in range(0,i): # # #
print("# ",end="") # # # # #
print("\r")
for i in range(1,n+1,2):
for j in range(0,i):
print("# ",end="")
print("\r")
43
LJIET Sem-5 PDS (3150713)
# Palindrom
s = input("String: ")
if (s==s[::-1]) :
print ('String is Palindrom')
else:
print ('String is not Palindrom')
Write a Python program which takes a list and returns a list with the elements "shifted l
eft by one position" so [1, 2, 3] yields [2, 3, 1].
n=input().split()
l=list(map(int,n))
print(l)
l.append(l.pop(0))
print('After Rotation: ',l)
Write a Python program which will return the sum of the numbers in the array, returnin
g 0 for an empty array. Except the number 13 is very unlucky, so it does not count and n
umber that come immediately after 13 also do not count.
n=input().split()
l=list(map(int,n))
print(l)
s=0
for i in range(len(l)):
if l[i]==13 or (l[i-1]==13 and i!=0):
continue
else:
s+=l[i]
print("Sum: ",s)
Write a program to interchange the List elements on two positions entered by a user.
l=[2,3,5,6,8,9,10]
print("List: ",l)
p1=int(input("Position 1:"))
p2=int(input("Position 2:"))
l[p1],l[p2]=l[p2],l[p1]
print('After Interchange: ',l)
44