Introduction To PYTHON
Introduction To PYTHON
Python List:In this tutorial, we'll learn everything about Python lists: creating lists, changing list
elements, removing elements, and other list operations with the help of examples.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
# list with mixed data types
my_list = [1, "Hello", 3.4]
List Index
We can use the index operator [] to access an item in a list. In Python, indices start at 0. So, a
list having 5 elements will have an index from 0 to 4.
Working with data types and variables
# Empty tuple
my_tuple = ()
print(my_tuple)
A tuple in Python is similar to a list. The difference between the two is that
we cannot change the elements of a tuple once it is assigned whereas we can
change the elements of a list.
Python del Statement: The Python del keyword is used to delete objects. Its
syntax is:
# delete obj_name
del obj_name
Python Dictionary: Python dictionary is an unordered collection of items. Each item of
a dictionary has a key/value pair.
Working with data types and variables
An item has a key and a corresponding value that is expressed as a pair (key:
value).
# empty dictionary
my_dict = {}
Dictionary Items
Dictionary items are ordered, changeable, and does not allow
duplicates.
Dictionary items are presented in key:value pairs, and can be
referred to by using the key name.
Dictionaries cannot have two items with the same key:
Working with numeric data.
>>> 1 - 1
0
To multiply two numbers, use the * operator:
>>> 3 * 3
9
Working with numeric data.
>>> 9 / 3
3.0
If you want to make sure that you get an integer after dividing two numbers,
you can use int () to convert the result.
Working with string data.
Python does not have a character data type, a single character is simply a
string with a length of 1
Unit 2:classes in python
A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class
creates a new type of object, allowing new instances of that type to be made. Each class
instance can have attributes attached to it for maintaining its state.
Class Definition Syntax:
class ClassName:
# Statement
The examples above are classes and objects in their simplest form,
and are not really useful in real life applications.
To understand the meaning of classes we have to understand the
built-in __init__() function.
All classes have a function called __init__(), which is always executed
when the class is being initiated.
Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created:
The __init__() Function
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
2.1 OOPS Concepts.
A class has some data which describes the state of the objects and the
functions perform different operations. These operations are mainly
performed on the data of the object.
class SuperHuman:
# attribute init
name = "Bruce Wayne"
power = "super strong"
def tagline(self):
print(f"My name is: {self.name}", f"and my character is {self.power}")
Classes and objects.
# Driver code
# initalising object
bat = SuperHuman()
bat.tagline()
OutputMy name is: Bruce Wayne and my character is super strong
Object in Python
Different data types like integer, string, float, array, dictionaries, all are
objects.
Object in Python
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Constructor
def __init__(self):
# body of the constructor
Types of constructors :
# parameterized constructor
def __init__(self, f, s):
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
# parameterized constructor
ef calculate(self):
self.answer = self.first + self.second
# creating object of the class
# this will invoke parameterized constructor
obj = Addition(1000, 2000)
# perform Addition
obj.calculate()
# display result
obj.display()
parameterized constructor
Output :
class GeekforGeeks:
# default constructor
def __init__(self):
self.geek = "GeekforGeeks"
GeekforGeeks
Destructors
class Employee:
# Initializing
def __init__(self):
print('Employee created.')
# Deleting (Calling destructor)
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
Employee created.
Destructor called, Employee deleted.
Data hiding, Creating classes
when we do not want to give out sensitive parts of our code implementation
and this is where data abstraction came.
An Object is an instance of a Class. A class is like a blueprint while an
instance is a copy of the class with actual values
When an object of a class is created, the class is said to be instantiated. All
the instances share the attributes and the behavior of the class
Data hiding, Creating classes
Inheritance
Inheritance is the capability of one class to derive or inherit the properties from another class.
The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived clas
Single Inheritance
Single Inheritance
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
Multiple Inheritance
A class can be derived from more than one base class in Python, similar to C+
+. This is called multiple inheritance.
class Base1:
pass
class Base2:
pass
class Class1:
def m(self):
print("In Class1")
class Class2(Class1):
def m(self):
print("In Class2")
Multiple Inheritance
class Class3(Class1):
def m(self):
print("In Class3")
class Class4(Class2, Class3):
pass
obj = Class4()
obj.m()
Output:
In Class2
Multilevel Inheritance
Multilevel Inheritance
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
Multilevel Inheritance
# Derived class
class Son(Father):
def __init__(self, sonname, fathername, grandfathername):
self.sonname = sonname
Multilevel Inheritance
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Multilevel Inheritance
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance:
Hierarchical Inheritance:
When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a
parent (base) class and three child (derived) classes.
Hierarchical Inheritance:
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
Hybrid Inheritance:
Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid
inheritance.
Hybrid Inheritance:
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
Hybrid Inheritance:
Polymorphism in python defines methods in the child class that have the same
name as the methods in the parent class. In inheritance, the child class
inherits the methods from the parent class. Also, it is possible to modify a
method in a child class that it has inherited from the parent class.
class Bird:
def intro(self):
print("There are different types of birds")
def flight(self):
print("Most of the birds can fly but some cannot")
Polymorphism
class parrot(Bird):
def flight(self):
print("Parrots can fly")
class penguin(Bird):
def flight(self):
print("Penguins do not fly")
obj_bird = Bird()
Polymorphism
obj_parr = parrot()
obj_peng = penguin()
obj_bird.intro()
obj_bird.flight()
obj_parr.intro()
obj_parr.flight()
obj_peng.intro()
obj_peng.flight()
Polymorphism
Output:
class India():
def capital(self):
print("New Delhi")
def language(self):
print("Hindi and English")
class USA():
def capital(self):
print("Washington, D.C.")
Polymorphism
def language(self):
print("English")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
Polymorphism
output
New Delhi
Hindi and English
Washington, D.C.
English
Python Custom Exceptions
To create a custom exception class, you define a class that inherits from the
built-in Exception class or one of its subclasses such as ValueError class:
class CustomException(Exception):
""" my custom exception class """
Example of Custom Exceptions
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
output
Enter a number: 12
This value is too large, try again!
Enter a number: 0
This value is too small, try again!
Enter a number: 8
This value is too small, try again!
Enter a number: 10
Congratulations! You guessed it correctly.
Iterators in Python
Iterators in Python
Iterators are everywhere in Python. They are elegantly implemented within for loops,
comprehensions, generators etc. but are hidden in plain sight.
Iterator in Python is simply an object that can be iterated upon. An object which will
return data, one element at a time.
Technically speaking, a Python iterator object must implement two special methods,
__iter__() and __next__(), collectively called the iterator protocol.
An object is called iterable if we can get an iterator from it. Most built-in containers in
Python like: list, tuple, string etc. are iterables.
Python generators
Python generators are a simple way of creating iterators. All the work we
mentioned above are automatically handled by generators in Python.
If a function contains at least one yield statement (it may contain other yield or
return statements), it becomes a generator function. Both yield and return will
return some value from a function.
Python Decorators
Decorators in Python
Python has an interesting feature called decorators to add functionality to an
existing code.
A Run time error is that occurs during execution of the program. It is caused
because of some illegal operation taking place.
For example
1. If a program is trying to open a file which does not exists or it could
not be opened(meaning file is corrupted), results into an execution error.
2. An expression is trying to divide a number by zero are RUN TIME
ERRORS
Logical Error
Open a file
Read or write (perform operation)
Close the file
Python has a built-in open() function to open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
File I/O: Examples
We can specify the mode while opening a file. In mode, we specify whether
we want to read r, write w or append a to the file. We can also specify if we
want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode, we get strings when
reading from the file.
Python Directory
Python Directory
If there are a large number of files to handle in our Python program, we can
arrange our code within different directories to make things more
manageable.
We can get the present working directory using the getcwd() method of the os
module
Changing Directory
We can change the current working directory by using the chdir() method.
Making a New Directory
We can make a new directory using the mkdir() method.
Python Directory
Syntax errors
Logical errors (Exceptions)
Error caused by not following the proper structure (syntax) of the language is
called syntax error or parsing error.
Errors that occur at runtime (after passing the syntax test) are called
exceptions or logical errors.
For instance, they occur when we try to open a file(for reading) that does not
exist (FileNotFoundError), try to divide a number by zero (ZeroDivisionError),
or try to import a module that does not exist (ImportError).
We can connect to relational databases for analyzing data using the pandas
library as well as another additional library for implementing database
connectivity
We will use Sqlite3 as our relational database as it is very light weight and
easy to use. Though the SQLAlchemy library can connect to a variety of
relational sources including MySql, Oracle and Postgresql and Mssql.
The purpose of this post is to share the most commonly used SQL commands
for data manipulation and their counterparts in Python language
.
SQL statements for data manipulation.
Example
create a database named "mydatabase":
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
Using Python to work with a database.
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
The data can be saved in a txt file where each line has a new data point.
The data can be stored in a CSV(comma separated values) file.
The data can be also stored in TSV(tab separated values) file.
Usage of Pandas for Data Analysis.
Pandas provide tools for reading and writing data into data structures and
files. It also provides powerful aggregation functions to manipulate data.
2. Reference Books:
- To be added
3. Web References:
- https://www.w3schools.com/python
- https://docs.python.org/3/tutorial/index.html
- https://www.python-course.eu/advanced_topics.php
- https://www.tutorialspoint.com/python3/
Seaborn for Statistical plots.
Line Plot
Scatter Plot
Box plot
Point plot
Count plot
Violin plotataset.
Machine Learning is about building programs with tunable parameters that
are adjusted automatically so as to improve their behavior by adapting to
previously seen data.
Machine Learning can be considered a subfield of Artificial Intelligence since
those algorithms can be seen as building blocks to make computers learn to
behave more intelligently by somehow generalizing rather that just storing
and retrieving data items like a database system would do.
Thank you