100% found this document useful (1 vote)
213 views116 pages

Python Unit-1

The document discusses the syllabus and features of a Python programming course. It covers 5 units that will be taught which include Python basics, strings, machine learning packages, data visualization and estimating occupancy. It also lists textbooks and course outcomes.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
100% found this document useful (1 vote)
213 views116 pages

Python Unit-1

The document discusses the syllabus and features of a Python programming course. It covers 5 units that will be taught which include Python basics, strings, machine learning packages, data visualization and estimating occupancy. It also lists textbooks and course outcomes.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 116

Essentials of Python

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:

 “ReemaThareja”, Python Programming using Problem Solving

Approach, First Edition, Oxford Higher Education,2017.


 “Sebastian Raschka”, Python Machine Learning, PACKT Publishing,

Open Source, 2019.


 Kenneth A. Lambert, Fundamentals of Python,CENGAGE Learning

Custom Publishing,2017.
 Machine Learning with Python/Scikit-Learn, - Application to the

Estimation of Occupancy and Human Activities, GSCOP,Packt


Publishing Limited, 2019
Course Outcomes
 Understand the techniques to code in python and write the

standard programs using python.


 Understand to use different IDE's and package of python

 Understand the python codes for machine learning

 Learn and practice various python packages along with the main

packages used for machine learning


Introduction
 Python is a general-purpose interpreted, interactive, object-
oriented, and high-level programming language.
 It was created by Guido van Rossum during 1985- 1990. Like
Perl, Python source code is also available under the GNU
General Public License (GPL)
 Python is a high-level, interpreted, interactive and object-
oriented scripting language.
 Python is designed to be highly readable.
 It uses English keywords frequently where as other languages
use punctuation, and it has fewer syntactical constructions than
other languages.
Introduction
It is used for
Web Development
Software development
Mathematics
System Scripting
Python
Can be used on a server to create web applications
Can be used alongside software to create workflows
Can connect to database systems
Can be used to handle big data & perform complex mathematics
Can be used to for rapid prototyping or for production ready
software development
History of Python
 Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
 Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and
other scripting languages.
 Python is copyrighted. Like Perl, Python source code is now
available under the GNU General Public License (GPL).
 Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in
directing its progress.
Python Version History

 It support two major versions, Python 2.x & Python 3.x


Features of Python(Why Python?)
  Easy to code: Python is a high-level programming language.
Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc.
 It is very easy to code in python language and anybody can learn
python basics in a few hours or days.
 It is also a developer-friendly language.
 Portable: Python works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc).
 Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
 Interpreted: Python runs on an interpreter system, meaning that
code can be executed as soon as it is written. This means that
prototyping can be very quick.
Features of Python(Why Python?)
 Free and open source: Python language is freely available at the
official website and you can download it from the given
download link 
 Automatic Memory Management: There is an automatic
memory management is present ie no need to free up the unused
memory by the programmer
  Extensible feature: Python is a Extensible language. We can
write some Python code into C or C++ language and also we can
compile that code in C/C++ language.
 Python can be treated in a procedural way, an object-oriented
way or a functional way.
 GUI Programming Support:Graphical User interfaces can be
made using a module such as PyQt5, PyQt4, wxPython, or Tk in
python.
PyQt5 is the most popular option for creating graphical apps
Features of Python(Why Python?)
 Python is Integrated language: Python is also an Integrated
language because it can be easily integrated with other languages
like c, c++, etc.
 Dynamically Typed Language: 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.
  Large Standard Library: 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.
 It supports automatic garbage collection
Applications of Python
 Embedded scripting language: Python is used as an embedded
scripting language for various testing/ building/ deployment/
monitoring frameworks, scientific apps, and quick scripts.
 3D Software: 3D software like Maya uses Python for automating
small user tasks, or for doing more complex integration such as
talking to databases and asset management systems.
 Web development: Python is an easily extensible language that
provides good integration with database and other web standards.
 GUI-based desktop applications: Simple syntax, modular
architecture, rich text processing tools and the ability to work on
multiple operating systems makes Python a preferred choice for
developing desktop-based applications.
Applications of Python
 Image processing and graphic design applications: Python is
used to make 2D imaging software such as Inkscape, GIMP,
Paint Shop Pro and Scribus. It is also used to make 3D animation
packages, like Blender, 3ds Max, Cinema 4D, Houdini,
Lightwave and Maya.
 Scientific and computational applications: Features like high
speed, productivity and availability of tools, such as Scientific
Python and Numeric Python, have made Python a preferred
language to perform computation and processing of scientific
data. 3D modeling software, such as FreeCAD, and finite
element method software, like Abaqus, are coded in Python.
 Games: Python has various modules, libraries, and platforms
that support development of games. Games like Civilization-IV,
Disney's Toontown Online, Vega Strike, etc. are coded using
Python.
Applications of Python
 Enterprise and business applications: Simple and reliable
syntax, modules and libraries, extensibility, scalability together
make Python a suitable coding language for customizing larger
applications. For example, Reddit which was originally written
in Common Lips, was rewritten in Python in 2005. A large part
of Youtube code is also written in Python.
 Operating Systems: Python forms an integral part of Linux
distributions.
Python Variables & Identifiers

 Variable: Variable means its value can vary.


 We can store any piece of information in a variable.
 Variables are nothing but just parts of your computer’s memory where
information is stored.
 To be identified easily, each variable is given an appropriate name.
 Identifier: A Python identifier is a name used to identify a variable,
function, class, module or other object.
 An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
 Python does not allow punctuation characters such as @, $, and %
within identifiers.
 Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in
Python.
 Python variables
Assigning or dotonot
Initializing Values need explicit declaration to reserve memory space.
Variables

 The declaration happens automatically when you assign a value to a


variable. The equal sign (=) is used to assign values to variables.
 The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.
 Example:
Multiple Assignment
 Python allows to assign a single value to several variables
simultaneously. For example −

 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 −

 Here, two integer objects with values 1 and 2 are assigned to


variables a and b respectively, and one string object with the
value "john" is assigned to the variable c.
Keywords
 These are reserved words and you cannot use them as constant or
variable or any other identifier names. All the Python keywords
contain lowercase letters only.
Lines and Indentation
 Python provides no braces to indicate blocks of code for class and
function definitions or flow control.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount.
 For example −
Multi-Line Statements
 Statements in Python typically end with a new line.
 Python does, however, allow the use of the line continuation
character (\) to denote that the line should continue.
 For example −

 Statements contained within the [], {}, or () brackets do not need


to use the line continuation character.
 For example −
Comments in Python
 A hash sign (#) that is not inside a string literal begins a comment.
 All characters after the # and up to the end of the physical line are part
of the comment and the Python interpreter ignores them.

 Multi line Comments


Python does not really have a syntax for multi line comments.
To add a multiline comment you could insert a # for each line:
Comments in Python
 Since Python will ignore string literals that are not assigned to a
variable, we can add a multiline string (triple quotes) in our code,
and place our comment inside it:
Data Types

 The data stored in memory can be of many types.


 Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
 Python has five standard data types −
 Numbers
 Sets
 Sequences
 Boolean
 Dictionary
1.Numeric
 In Python, numeric data type represent the data which has numeric
value.
 Numeric value can be integer, long, floating number or even
complex numbers. These values are defined as int, long,
float and complex class in Python.
 Integers – This value is represented by int class. It contains positive
or negative whole numbers (without fraction or decimal). In Python
there is no limit to how long an integer value can be.
 Long-long integers, can also be used to represent octal and
hexadecimal
 Float – This value is represented by float class. It is a real number
with floating point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative
integer may be appended to specify scientific notation.
 Complex Numbers – Complex number is represented by complex
class. It is specified as (real part) + (imaginary part)j. For example
1.Numeric
type()
 type() function is used to determine the type of data type

 It prints <class 'int'>


2.Sequence Type

 In Python, sequence is the ordered collection of similar or


different data types.
 Sequences allows to store multiple values in an organized and
efficient fashion.
 There are several sequence types in Python –
 String
 List
 Tuple
String
 A string is a collection of one or more characters put in a single quote,
double-quote or triple quote.
 In python there is no character data type, a character is a string of
length one.
 It is represented by str class.
 Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working
their way from -1 at the end.
List
 Lists  are just like the arrays, declared in other languages which
is a ordered collection of data.
 It is very flexible as the items in a list do not need to be of the
same type.
 Lists in Python can be created by just placing the sequence
inside the square brackets[].
Tuples
 A tuple is another sequence data type that is similar to the list. A
tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
 The main differences between lists and tuples are: Lists are enclosed
in brackets ( [ ] ) and their elements and size can be changed, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
 Tuples can be thought of as read-only lists.
 For example −
3.Boolean
 Data type with one of the two built-in values, True or False.
 Boolean objects that are equal to True are truthy (true), and
those equal to False are falsy (false).
 It is denoted by the class bool.
 Example:
4.Set
 In Python, set is an unordered collection of data type that is iterable,
mutable and has no duplicate elements.
 The order of elements in a set is undefined though it may consist of
various elements.
 Sets can be created by using the built-in set() function with an
iterable object or a sequence by placing the sequence inside curly
braces, separated by ‘comma’.
 Type of elements in a set need not be the same, various mixed-up
data type values can also be passed to the set.
 Example:

Output:
4.Set
It returns only one instance of any value present more than once.

However, a set is unordered, so it doesn’t support indexing.

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

 These operators test if the two operands share an identity.


 There are two identity operators- ‘is’ and ‘is not’.
Precedence of Operators
Expressions
 An expression is a combination of values, variables, and
operators. 
 In Python most of the lines we will write will be expressions.
 Expressions are made of operators and operands.
 An expression is like 2 + 3
  A value all by itself is considered an expression, and so is a
variable.
 Ex: 17
Control Flow Statements
 A program’s control flow is the order in which the program’s
code executes.
 The control flow of a Python program is regulated by conditional
statements, loops, and function calls.
 Python has three types of control structures:
1.Sequential - default mode
2.Selection - used for decisions and branching
3.Repetition - used for looping, i.e., repeating a piece of code
multiple times.
1. Sequential
 Sequential statements are a set of statements whose execution
process happens in a sequence.
 The problem with sequential statements is that if the logic has
broken in any one of the lines, then the complete source code
execution will break.
## This is a Sequential statement
 
a=20
b=10
c=a-b
print("Subtraction is : ",c)
2. Selection/Decision control statements
 In Python, the selection statements are also known as Decision
control statements or branching statements.
 The selection statement allows a program to test several
conditions and execute instructions based on which condition is
true.
 Some Decision Control Statements are:
1.Simple if
2.if-else
3.nested if
4.if-elif-else
Simple if
 If statements are control flow statements that help us to run a
particular code, but only when a certain condition is met or
satisfied.
 A simple if only has one condition to check.
Syntax

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

 In other words, it executes the statements under itself while the


condition it takes is True.
The else statement for while loop
 A while loop may have an else statement after it. When the condition becomes
false, the block under the else statement is executed.
 However, it doesn’t execute if you break out of the loop or if an exception is
raised.
 Example:
Single Statement while
 Like an if statement, if we have only one statement in while’s
body, we can write it all in one line.
Python For Loop
 A for loop is used to iterate over a sequence that is either a list,
tuple, dictionary, or a set.
 We can execute a set of statements once for each item in a list,
tuple, or dictionary.
Python For Loop(The range() function)
 This function yields a sequence of numbers. When called with one
argument, say n, it creates a sequence of numbers from 0 to n-1

 Calling it with two arguments creates a sequence of numbers


from the first to the second.
Python For Loop(The range() function)
 We can also pass three arguments. The third argument is the interval.

 The interval can also be negative.


Iterating on lists or similar constructs
 We can use the loop to iterate on a list

 We can use the loop to iterate on a set


Iterating on lists or similar constructs
 We can also iterate on a string.
Iterating on indices of a list or a similar construct

 The len() function returns the length of the list.


 When we apply the range() function on that, it returns the indices of the list on a
range object.
 Example
The else statement for for-loop
 Like a while loop, a for-loop may also have an else statement after it.
 When the loop is exhausted, the block under the else statement
executes.
Nested Loops in Python
  Python programming language allows to use one loop inside
another loop
Loop Control Statements in Python
 Loop control statements change execution from its normal sequence.
 When execution leaves a scope, all automatic objects that were
created in that scope are destroyed. 
 Continue Statement:  When the program control reaches the
continue statement, it skips the statements after ‘continue’.
Loop Control Statements in Python

 break statement: When you put a break statement in the body


of a loop, the loop stops executing, and control shifts to the first
statement outside it.
Loop Control Statements in Python
 Pass Statement: We use pass statement to write empty loops
 It is a null statement. The interpreter does not ignore it, but it
performs a no-operation (NOP).
Standard I/O opeartions
 Python provides numerous built-in functions that are readily
available to us at the Python prompt.
 Some of the functions like input() and print() are widely used for
standard input and output operations respectively. 
 print() function is used to output data to the standard output
device (screen).
Standard I/O operations
The sep separator is used between the values. It
defaults into a space character.
After all values are printed, end is printed. It defaults
into a new line.
Standard I/O operations
Input() will take the input from the user
The syntax for input() is

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.

 The keyword is followed by the function name and parentheses


(( )).
 After the parentheses a colon (:) is placed.
 Parameters or arguments that the function accept are placed within
parentheses.
 The first statement of a function can be an optional statement - the
docstring describe what the function does.
 The code block within the function is properly indented to form the
block code.
 A function may have a return[expression] statement. That is, the
return statement is optional.
Syntax

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:

The return statement is used for two things.


• Return a value to the caller
• To end and exit a function and go back to its caller
Function Arguments
We can call a function by using the following types of formal
arguments −
•Required arguments
•Keyword arguments
•Default arguments
•Variable-length arguments
Required Arguments
 In the required arguments, the arguments are passed to a function in
correct positional order.
 Also, the number of arguments in the function call should exactly match
with the number of arguments specified in the function definition
 Examples:
Keyword Arguments
When we call a function with some values, the values are
assigned to the arguments based on their position.
 Python also allow functions to be called using keyword
arguments in which the order (or position) of the arguments
can be changed.
The values are not assigned to arguments according to their
position but based on their name (or keyword).
Keyword arguments are beneficial in two cases.
 First, if you skip arguments.
Second, if in the function call you change the order of
parameters.
Keyword Arguments
Example:
Variable-length Arguments
 In some situations, it is not known in advance how many arguments will
be passed to a function. In such cases, Python allows programmers to
make function calls with arbitrary (or any) number of arguments.
 When we use arbitrary arguments or variable length arguments, then the
function definition use an asterisk (*) before the parameter name. The
syntax for a function using variable arguments can be given as,
Example:
Default Arguments
 Python allows users to specify function arguments that can have default
values. This means that a function can be called with fewer arguments
than it is defined to have.
 That is, if the function accepts three parameters, but function call
provides only two arguments, then the third parameter will be assigned
the default (already specified) value.
 The default value to an argument is provided by using the assignment
operator (=). Users can specify a default value for one or more arguments.

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.

When the above code is executed, it produces the following


result −
Packages in Python
• A package is a hierarchical file directory structure that has modules
and other packages within it. Like modules, you can very easily
create packages in Python.
• Every package in Python is a directory which must have a special
file called __init__.py
• For example, to create a package called MyPackage, create a
directory called MyPackage having the module MyModule and the
__init__.py file.
• Now, to use MyModule in a program, you must first import it.
• This can be done in two ways.
• import MyPackage.MyModule
or
from MyPackage import MyModule
Globals(), Locals(), And Reload()
 The globals() and locals() functions are used to return the names in
the global and local namespaces.
 The result of these functions is of course, dependent on the
location from where they are called. For example,
 If locals() is called from within a function, names that can be
accessed locally from that function will be returned.
 If globals() is called from within a function, all the names that can
be accessed globally from that function is returned.
 Reload()- When a module is imported into a program, the code in
the module is executed only once. If you want to re-execute the
top-level code in a module, you must use the reload() function.
This function again imports a module that was previously
imported.
Docstring
Python docstrings are the string literals that appear
right after the definition of a function, method, class,
or module.
It’s specified in source code that is used, like a
comment, to document a specific segment of code.
Unlike conventional source code comments, the
docstring should describe what the function does, not
how.
The docstrings are declared using ”’triple single
quotes”’ or “””triple double quotes””” just below the
class, method or function declaration. All functions
should have a docstring.
Docstring
The docstrings can be accessed using the __doc__
method of the object or using the help function.
Docstrings for the built-in print() function
 The documentation of the print() function is present as
the __doc__ attribute of this function.
Docstrings of Python module
Docstrings for Python Functions
Docstrings for Python Classes
The docstrings for classes should summarize its
behavior and list the public methods and instance
variables.
The subclasses, constructors, and methods should each
have their own docstrings.
print(Person.__doc__)
Using the help() Function for Docstrings
We can also use the help() function to read the docstrings
associated with various objects.
help(Person)
Documentation Strings
 Docstrings (documentation strings) serve the same purpose as that
of comments, as they are designed to explain code.
 However, they are more specific and have a proper syntax.

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

You might also like