Python Module - 1
Python Module - 1
DATA ANALYTICS
Module - I: Python Concepts, Data Structures, Classes
Introduction
Python is a popular programming language. It was created by Guido
van Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Why python?
if 5 > 2:
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:
Variables in Python:
x=5
y = "Hello, World!"
Python has no command for declaring a variable.
Comment statement
#This is a comment.
print("Hello, World!")
Python Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do
different things.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Example datatypes
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana",
frozenset
"cherry"})
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Python Numbers
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Python statements
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example
i=1
sum=0
n= int(input(“enter the number”))
while i < n:
sum=sum+i
i += 1
print(n)
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Example
Get the character at position 1 (remember that the first character has
the position 0):
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string,
with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output:
b
a
n
a
n
a
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Output: 13
Check String
To 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)
Output: True
Use it in an if statement:
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
a = "Hello, World!"
print(a.lower())
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Output: Jello, World!
The split() method returns a list where the text between the specified separator becomes the list
items.
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
a = "Hello"
b = "World"
c=a+b
print(c)
we cannot combine strings and numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Example 2:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Output: I want to pay 49.95 dollars for 3 pieces of item 567
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want
to insert.
An example of an illegal character is a double quote inside a string that
is surrounded by double quotes:
txt = "We are the so-called "Vikings" from the north.“
Return the number of times the value "apple" appears in the string:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x) #output: 2
Where in the text is the word "welcome"?:
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x) #output: 7
Where in the text is the first occurrence of the letter "e" when you only search between position 5 and 10?:
txt = "Hello, welcome to my world."
x = txt.find("e", 5, 10)
print(x) #output: 8
If the value is not found, the find() method returns -1, but the index() method will raise an exception
The input() function automatically converts the user input into string.
We need to explicitly convert the input using the type casting.
Python program for addition of two numbers
a=int(input("enter the first integer value "))
b=int(input("enter the second integer value "))
c=a+b
print("sum of {0} and {1} numbers is {2}".format(a,b,c))
Python program to find squareroot
a=float(input("enter the number "))
b=a**0.5
print('square root of %f is %.3f'%(a,b))
Python program to find the area of triangle
a = float(input('Enter first side: '))
b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
List items are indexed and you can access them by referring to the index number:
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1]) #output: banana
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Extend List
To append elements from another list to the current list, use the extend() method.
Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
Python - Remove List Items
Remove Specified Item
The remove() method removes the specified item. Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Remove Specified Index
The pop() method removes the specified index. Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
If you do not specify the index, the pop() method removes the last item.
Clear the List
The clear() method empties the list. The list still remains, but it has no content.
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Sort List Alphanumerically
List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
Sort Descending
To sort descending, use the keyword argument reverse = True:
Sort the list descending:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Python - Copy Lists
Another way to join two lists is by appending all the items from list2 into
list1, one by one:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Passing a List as an Argument
def my_function(food):
for x in food:
print(x)
my_function(fruits)
Python Tuples
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value.
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
A tuple can contain different data types:
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Range of Indexes
You can 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 tuple with the
specified items.
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango")
print(thistuple[2:5])
Python - Update Tuples
Tuples are unchangeable, meaning that you cannot change, add, or remove items once the tuple is
created.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it
also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list
back into a tuple.
print(x)
Add Items
Since tuples are immutable, they do not have a build-in append()
method, but there are other ways to add items to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, you
can convert it into a list, add your item(s), and convert it back into a
tuple.
Convert the tuple into a list, add "orange", and convert it back into a
tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
Add tuple to a tuple. You are allowed to add tuples to tuples, so if you
want to add one item, (or many), create a new tuple with the item(s),
and add it to the existing tuple:
Create a new tuple with the value "orange", and add that tuple:
thistuple = ("apple", "banana", "cherry")
y = ("orange",)
thistuple = thistuple+y
print(thistuple)
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a
tuple:
Packing a tuple:
fruits = ("apple", "banana", "cherry")
But, in Python, we are also allowed to extract the values back into variables. This is
called "unpacking":
Unpacking a tuple:
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Python - Loop Tuples
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Create a Parent Class
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and methods
from the Person class:
class Student(Person):
pass
Use the pass keyword when you do not want to add any other properties or
methods to the class.
Now the Student class has the same properties and methods as the Person
class.
Example
Use the Student class to create an object, and then execute the printname
method:
x = Student("Mike", "Olsen")
x.printname()
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
So far we have created a child class that inherits the properties and methods from
its parent.
We want to add the __init__() function to the child class (instead of the pass
keyword).
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Python also has a super() function that will make the child class inherit all the
methods and properties from its parent:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)