Python Unit-1
Python Unit-1
Programming
Unit-1
Syllabus
Unit I:
Introduction to Python:
Features of Python Language, Data Types, Operators,
Expressions, Control Statement, Standard I/O Operations,
Functions, OOP using Python, Modules, Packages, Doc Strings,
Built-in Functions, Exception, File management.
Unit II:
Strings and Regular Expressions:
String Operations, Built-in String Methods and Functions,
Comparing Strings, function in Regular Expression.
Sequence: List, Tuples, Dictionaries.
Why Python for Machine Learning, Other platforms, languages
and frameworks for ML
Syllabus
Unit III:
Understanding Python IDEs: Anaconda, Machine learning with
scikit-learn, K-means clustering, Data Pre-processing or Data
Mugging, Dimensionality Reduction, Entropy, Decision tree as a
classifier, Random Forest, Perceptron Learning Algorithm
Unit IV:
Other Python Packages:numpy for matrix computation, iPython
for enhanced interactive console, sympy for symbolic
calculations, pandas for data structures and analysis, pymc for
stochastic calculation, libpgm for Bayesian networks.
Syllabus
Unit V:
Scientific Python using matplotlib, different types of plotting,
Graphs, Pie-charts, vector
Estimating occupancy using decision tree, Introduction to
Theano and Kera.
Text Books & Reference Books:
Custom Publishing,2017.
Machine Learning with Python/Scikit-Learn, - Application to the
Learn and practice various python packages along with the main
Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.
We can also assign multiple objects to multiple variables.
For example −
Output:
4.Set
It returns only one instance of any value present more than once.
Also, it is mutable. We can change its elements or add more. Use the add() and
remove() methods to do so.
5.Dictionary
A dictionary is an unordered collection of data values, which
holds key-value pairs.
Declare it in curly braces, with pairs separated by commas.
Separate keys and values by a colon(:)
In Python, a Dictionary can be created by placing a sequence of
elements within curly {} braces, separated by ‘comma’.
Values in a dictionary can be of any datatype and can be
duplicated, whereas keys can’t be repeated and must be
immutable.
Dictionary can also be created by the built-in function dict()
Example
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Example
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Example
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Example
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Operators
Operators are the constructs which can manipulate the value of
operands.
Python language supports the following types of operators.
1.Arithmetic Operators
2.Comparison (Relational) Operators
3.Assignment Operators
4.Logical Operators
5.Bitwise Operators
6.Membership Operators
7.Identity Operators
1. Arithmetic Operators in Python
If a=10 and b=20
2.Relational Operator
These operators compare the values on either sides of them and decide the
relation among them.
Assume variable a holds 10 and variable b holds 20, then −
3.Assignment Operators
4.Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13; Now in the binary format their values
will be 0011 1100 and 0000 1101 respectively.
5.Logical Operators
These are conjunctions that can used to combine more than one
condition.
There are three Python logical operator – and, or, and not that
come under python operators.
6.Membership Operators
These operators test whether a value is a member of a sequence.
The sequence may be a list, a string, or a tuple.
There are two membership python operators- ‘in’ and ‘not in’
7. Identity Operators
Example
if-else
The if-else statement evaluates the condition and will execute the body
of if if the test condition is True, but if the condition is False, then the
body of else is executed.
Syntax
Example
n = 5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
if-elif-else
The if-elif-else statement is used to conditionally execute a
statement or a block of statements.
Example of if-elif-else
x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
nested if
Nested if statements are an if
statement inside another if
statement.
concept of if, if-else and even if-
elif-else statements combined to
form a more complex structure.
Example of nested if
a = 5
b = 10
c = 15
if a > b:
if a > c:
print("a value is big")
else:
print("c value is big")
elif b > c:
print("b value is big")
else:
print("c is big")
3. Repetition
A repetition statement is used to repeat a group(block) of
programming instructions.
In Python, we generally have two loops/repetitive
statements:
1.for loop
2.while loop
3. Loop Control Statements
4. Nested For Loop in Python
A while loop in python iterates till its condition becomes False.
Python While Loop
Example:
Functions
Python enables its programmers to break up a program into
segments commonly known as functions, each of which can be
written more or less independently of the others.
Every function in the program is supposed to perform a well-
defined task.
A function is a block of code which only runs when it is called
Function Declaration and Definition
A function, f that uses another function g, is known as the calling
function and g is known as the called function.
The inputs that the function takes are known as
arguments/parameters.
When a called function returns some result back to the calling
function, it is said to return that result.
The calling function may or may not pass parameters to the called
function. If the called function accepts arguments, the calling
function will pass parameters, else not.
Function declaration is a declaration statement that identifies a
function with its name, a list of arguments that it accepts and the
type of data it returns.
Function definition consists of a function header that identifies the
function, followed by the body of the function containing the
executable code for that function.
Function Definition
Function blocks starts with the keyword def.
Calling a Function:
Functions
We can assign the function name to a variable.
Doing this will allow to call same function using the
name of that variable.
Example:
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name,
inside the parentheses.
We can add as many arguments as we want, just
separate them with a comma.
A parameter is the variable listed inside the
parentheses in the function definition.
An argument is the value that is sent to the function
when it is called
Local and Global Variables
•A variable which is defined within a function is local to that function.
•A local variable can be accessed from the point of its definition until the
end of the function in which it is defined.
• It exists as long as the function is executing.
•Function parameters behave like local variables in the function.
Moreover, whenever we use the assignment operator (=) inside a function,
a new local variable is created.
•Global variables are those variables which are defined in the main body
of the program file.
•They are visible throughout the program file.
Local and Global Variables
Example:
Using the Global Statement
To define a variable defined inside a function as global, we must use the
global statement. This declares the local or the inner variable of the function
to have module scope.
Example:
Resolution of names
•Scope defines the visibility of a name within a block.
•If a local variable is defined in a block, its scope is that particular block.
•If it is defined in a function, then its scope is all blocks within that function.
•When a variable name is used in a code block, it is resolved using the
nearest enclosing scope.
• If no variable of that name is found, then a NameError is raised.
•In the code given below, str is a global string because it has been defined
before calling the function.
Exampl
e:
The Return Statement
•The syntax of return statement is, return [expression]
•The expression is written in brackets because it is optional. If the expression
is present, it is evaluated and the resultant value is returned to the calling
function.
•However, if no expression is specified then the function will return None.
Example:
Example:
Lambda Functions Or Anonymous
Functions
Lambda or anonymous functions are so called because they are not declared
as other functions using the def keyword. Rather, they are created using the
lambda keyword.
Lambda functions are throw-away functions, i.e. they are just needed where
they have been created and can be used anywhere a function is required.
The lambda feature was added to Python due to the demand from LISP
programmers.
Lambda functions contain only a single line. Its syntax can be given as,
Example:
Recursive Functions
A recursive function is defined as a function that calls itself to solve a
smaller version of its task until a final call is made which does not
require a call to itself.
Every recursive solution has two major cases, which are as follows:
base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function.
recursive case, in which first the problem at hand is divided into simpler
sub parts.
Recursion
Example: utilized divide and conquer technique of problem solving.
Module
A module is a file containing Python definitions and
statements. A module can define functions, classes, and
variables.
A module can also include runnable code.
Grouping related code into a module makes the code
easier to understand and use.
It also makes the code logically organized.
Create a Module
To create a module just save the code you want in a file
with the file extension .py
# A simple module, calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
•The import statement
•Any Python source file can be used as a module by executing an import
statement in some other Python source file.
•When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches for importing a module.
# importing module calc.py
import calc
print(add(10, 2))
The from import Statement
A module may contain definition for many variables and functions.
When we import a module, we can use any variable or function
defined in that module.
But if we want to use only selected variables or functions, then we
can use the from...import statement.
The from...import has the following syntax
Example:
To import more than one item from a
module, use a comma separated list
The from import * Statement
By using from import * it is also possible to import all
names from a module into the current namespace
Re-naming a Module
•We can create an alias when we import a module, by using
the as keyword:
•file mymodule.py
The dir() function
The dir() built-in function returns a sorted list of strings containing
the names defined by a module.
The list contains the names of all the modules, variables, and
functions that are defined in a module.
Example:
Built in Functions
Built in functions are those that are built in python and
therefore available to use
Python has around 80 built-in functions of various
types as:
1.Math functions such as abs(x),min(),round() etc
2.Type conversion functions such as int(x) etc
3.Input functions such as input(x) etc
4.Miscellaneous functions such as
len(x),reverse(x),sorted(x) etc