UNIT1 - PDS - Basic Python
UNIT1 - PDS - Basic Python
UNIT1 - PDS - Basic Python
FOR
DATA SCIENCE
( 3150713 )
and Returns True if both statements are true x < 5 and x < 10
not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)
Python Identity Operators
Operator Description Example
is Returns True if both x is y
variables are the same
object
is not Returns True if both x is not y
variables are not the
same object
Output:
a is greater than b
Branching Programs
Output:
1
2
3
While with continue
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Example:
# Python program to illustrate
# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
Output:
0123
range() function
The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
39
Types of Data Structures in Python
Python has implicit support for Data Structures
which enable you to store and access data.
These structures are called List, Dictionary, Tuple
and Set.
Python allows its users to create their own Data
Structures enabling them to have full control over
their functionality.
The most prominent Data Structures are Stack,
Queue, Tree, Linked List and so on which are also
available to you in other programming languages
40
Types of Data Structures in Python
41
Mutable vs Immutable Objects
in Python
Every variable in python holds an instance of an
object.
There are two types of objects in python
i.e. Mutable and Immutable objects.
Whenever an object is instantiated, it is assigned
a unique object id. The type of the object is
defined at the runtime and it can’t be changed
afterwards. However, it’s state can be changed if
it is a mutable object.
To summarise the difference, mutable objects can
change their state or contents and immutable
objects can’t change their state or content
42
Mutable Objects : It can changed after it is
created.
These are of type list, dict, set .
Custom classes are generally mutable.
Immutable Objects : It can not be changed after it
is created.
These are of in-built types like int, float, bool,
string, unicode, tuple.
43
Python collections/Data
structures
There are four collection data types in the Python
programming language:
List
It is a collection which is ordered and changeable.
Allows duplicate members. It is mutable.
Tuple
It is a collection which is ordered and unchangeable.
Allows duplicate members. It is non-mutable.
Set
It is a collection which is unordered and unhindered.
No duplicate members. It is mutable.
Dictionary
It is a collection which is unordered, changeable and
indexed. It is mutable. No duplicate members. 44
List
A list is a collection which is ordered and changeable.
In Python lists are written with square brackets.
Example :
L1 = ["apple", "banana", "cherry"]
print(L1)
45
Access items from list
>> L1=["a","b","c"]
>>> print(L1)
['a', 'b', 'c']
>>> L1[0]
'a'
>>> L1[1]
'b'
>>> L1[2]
'c'
>>> L1[-1]
'c'
>>> L1[-2]
'b'
>>> L1[-3]
46
'a'
Range of Indexes
Specify a range of indexes by specifying where to
start and where to end the range.
When specifying a range, the return value will be a
new list with the specified items.
Example:
Return the second, third, fourth, and item:
a = [“ apple", "banana", "cherry", "orange“]
print(a[1:3])
Output :['banana', 'cherry']
>>print(a[0: ]) - ['apple', 'banana', 'cherry', 'orange']
>>print(a[:4]) -['apple', 'banana', 'cherry', 'orange']
47
Range of Negative Indexes
starts from right to left with indexing -1.
a = [“ apple", "banana", "cherry", "orange“]
print(a[-4:-1])
Output : ['apple', 'banana', 'cherry']
48
Change Item Value –as List is
mutable
Example :
>>> a=["apple","banana","cherry","orange"]
>>> a
['apple', 'banana', 'cherry', 'orange']
>>> a[1]="mango"
>>> a
['apple', 'mango', 'cherry', 'orange']
>>>
49
Loop Through a List
50
Check if Item Exists
Example:
a = ["apple", "banana", "cherry"]
if "apple" in a:
print("Yes, 'apple' is in the fruits
list")
51
List methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Create a Tuple:
a = ("apple", "banana", "cherry")
print(a)
Output :
('apple', 'banana', 'cherry')
59
There are four collection data types in the
Python programming language:
List is a collection which is ordered and
changeable. Allows duplicate members.
Tuple is a collection which is ordered and
unchangeable. Allows duplicate members.
Set is a collection which is unordered and
unindexed. No duplicate members.
Dictionary is a collection which is unordered and
changeable. No duplicate members.
60
Access Tuple Items
61
Change Tuple Values
63
Create Tuple With One Item
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
64
Remove Items
65
Join Two Tuples
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output: ('a', 'b', 'c‘, 1, 2, 3)
The tuple() Constructor
a = tuple(("apple", "banana", "cherry")) # note the
double round-brackets
print(a)
66
Tuple methods
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position
of where it was found
67
Dictionary
69
Change Values
70
Check if Key Exists
71
Loop Through a Dictionary
1. Example - Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Output : brand model year
2. Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Output: Ford Mustang 1964
3. You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Output: Ford Mustang 1964
4. Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Output:
brand Ford
model Mustang
year 1964
72
Dictionary Length - To determine how many items
(key-value pairs) a dictionary has, use
the len() method.
print(len(thisdict))
Adding Items - Adding an item to the dictionary is
done by using a new index key and assigning a
value to it:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict) 73
Removing Items
74
The popitem() method removes the last inserted
item (in versions before 3.7, a random item is
removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
75
Example - The del keyword removes the item with
the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
76
Example - The clear() keyword empties the
dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
77
Copy a Dictionary
You cannot copy a dictionary simply by
typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made
in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use
the built-in Dictionary method copy().
Make a copy of a dictionary with
the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy() 78
print(mydict)
Make a copy of a dictionary with
the dict() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
79
Nested Dictionaries
create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
} 80
}
Or, if you want to nest three dictionaries that already exists as
dictionaries:
Example - Create three dictionaries, than create one dictionary
that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2, 81
"child3" : child3
}
The dict() Constructor
82
Dictionary Methods
Method Description
clear() Removes all the elements from the dictionary
setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
Output: {“apple”,’banana”,”cherry”}
84
Access Items
87
Get the Length of a Set
88
Example - Remove "banana" by using
the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Note:
If the item to remove does not exist,
remove() will raise an error.
If the item to remove does not
exist, discard() will NOT raise an error.
89
You can also use the pop(), method to remove an
item, but this method will remove the last item.
Remember that sets are unordered, so you will
not know what item that gets removed.
The return value of the pop() method is the
removed item.
Remove the last item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset)
Note: Sets are unordered, so when using
the pop() method, you will not know which item
that gets removed. 90
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Example - The del keyword will delete the set
completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
91
Join Two Sets
There are several ways to join two or more sets in
Python.
You can use the union() method that returns a
new set containing all items from both sets, or
the update() method that inserts all the items
from one set into another:
Example - The union() method returns a new set
with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
92
Example - The update() method inserts the items
in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Note: Both union() and update() will exclude any
duplicate items.
The set() Constructor- It is also possible to use
the set() constructor to make a set. Using the
set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note
the double round-brackets
print(thisset) 93
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
difference_update() Removes the items in this set that are also included in another, specified set
intersection_update() Removes the items in this set that are not present in other, specified set(s)
symmetric_difference_update() inserts the symmetric differences from this set and another
95
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
OR
You can use threee single quotes
96
Strings are arrays:
Python does not have a character data type, a single
character is simply a string with a length of 1.
Square brackets can be used to access elements of
the string.
Example - Get the character at position 1 (remember
that the first character has the position 0):
a = "Hello, World!"
print(a[1])
97
How String slicing in Python works
Python slicing can be done in two ways:
Using a slice() method
Using array slicing [ : : ] method
String = 'ASTRING'
# String slicing
String = 'GEEKSFORGEEKS' Output:
GEE
# Using indexing sequence EK
print(String[:3]) SEGOSE
10
4
Looping Through a String
Since strings are arrays, we can loop through the
characters in a string, with a for loop.
for x in “SVMIT":
print(x)
10
5
Check String
check if a certain phrase or character is present in
a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
o Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.") 10
6
Check if NOT
10
8
expandtabs() Sets the tab size of the string
find() Searches the string for a specified
value and returns the position of where
it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified
value and returns the position of where
it was found
isalnum() Returns True if all characters in the
string are alphanumeric
10
9
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
11
0
istitle() Returns True if the string follows the
rules of a title
isupper() Returns True if all characters in the
string are upper case
join() Joins the elements of an iterable to the
end of the string
ljust() Returns a left justified version of the
string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
11
1
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
11
3
Get a list as input from user
# creating an empty list
L1 = []
# number of elements as input
n = int(input("Enter number of elements : "))
map() Returns the specified iterator with the specified function applied to
each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
Python Built in Functions
Function Description
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified
character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
def function_name():
statement
statement
Example : write a code to find out maximum no between two
using function.
Execute at promt:
>>> max(3,4)
>>>4
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
Python Code:
sum = 0
for x in my_list:
sum += x
print(sum)
Output:
50
Object-oriented coding
This type of coding relies on the data fields, which are treated
as objects. These can be manipulated only through prescribed
methods. Python doesn’t support this paradigm completely, due
to some features like encapsulation cannot be implemented.
This type of coding also supports code reuse.
.
Python Code:
class word:
def test(self):
print("Python")
string = word()
string.test()
Output:
Python
Procedural coding
Usually, most of the people begin learning a language through
procedural code, where the tasks proceed a step at a time. It is the
simplest form of coding. It is mostly used by non-programmers as it is a
simple way to accomplish simpler and experimental tasks. It is used for
iteration, sequencing, selection, and modularization.
Python Code:
def add(list):
sum = 0
for x in list:
sum += x
return sum
print(add(my_list))
Output:
50