Python
Python
What is Python ?
Python is a clear and powerful object-oriented programming
language.
https://www.python.org/
Features
• Easy to Learn
• High Level Language
• Code development speed
• Compact and easy to remember syntax
• No compilation
• Library (or module) for everything
• Huge Library
• Used heavily in the field of
• Data science
• Machine learning
• Scientific computing
Python libraries and
frameworks are popular:
Compilation
• Compilation is the process in which the source code
is translated into the target language, where the
target language is sometimes machine-readable
code and in other times it serves as the input to
another compiler or interpreter.
• It takes the entire program at a time as the input.
• The code is translated once into object code and can
be run many times.
• It will not execute the machine-readable code it
produced; this is simply a translation step.
• It is the step done before the program execution
process.
Interpretation
1.It takes the source code, parse it and reacts based on the
instruction specified.
2.The source code is translated into some kind of
intermediate representation and executes it.
3.Executes the compiled code that is done by the compiler
previously.
In the last 2 cases the compiler is part of the interpreter
system.
Both Compilation and Interpretation
How does python codes gets executed
Steps involved when you run your Python code,
1.The compiler receives the source code.
The compiler checks the syntax of each line in the source code.
2.If the compiler encounters an error, it halts the translation process with an
error message (Syntax error).
3.Else if the instruction is well formatted, then it translates the source code
to Bytecode.
4.Bytecode is sent to the Python Virtual Machine (PVM)
5.Bytecode along with the inputs and Library modules is given as the input
to the PVM.
How does python codes gets executed
Some of the Implementations of Python
default Python interpreter
The Jython project provides implementations of Python in Java,
providing to Python the benefits of running on the JVM and
access to classes written in Java.
Integrated development environment (IDE)
Anaconda is bundle of some
popular python packages and a
package manager called conda
(similar to pip)
Some of the popular anaconda
packages are, numpy, scipy,
jupyter, nltk, scikit-learn, etc.
Conda is package manager similar
to pip. Conda allows you to install
non-python library dependencies
such as Hierarchical Data Format
version 5 (HDF5), Math Kernel
Library (MKL), LLVM etc. With pip
you can only install python
dependencies.
Jupyter notebook used to be called
ipython notebook before
Jupyter notebook is a web application that
allows you to run live code, embed
visualization, explanatory text all in one place
Important Link
• http://jupyter.org/
• Notebook gallery
Variable
• Refer to your class notes
Rules
• Every variable name should start with alphabets or underscore (_).
• No Reserved keyword
Examples
Do Don’t
• A • and
• a • 15name
• name • $city
• name15 • Full$Name
• _city • Full Name
• Full_name
• FullName
Data type
• Datatype represents the type of data stored into a variable or memory
• Types of data type
• Built-in data type
• User defined data type
Numeric Type / Number
Following are the Numeric Data type:-
Int
Float
Complex
Character
There is no concept of char data type in Python to represent individual
character.
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Syntax:- input([prompt])
prompt is a string or message, representing a default message before input. It is optional
Ex:-
name = input( )
name = input(“Your Name: ”)
If Statement
It is used to execute an instruction or block of instructions only if a condition is fulfilled.
Syntax: -
First the condition is tested, If the condition is True
if (condition):
statement then the statements given after
Rest of the Code colon (:) are executed
if (condition):
statement1 Block of statement/ Group of statements/ Suite
statement2
Rest of the Code
If there is single statement it can be written in one line.
Ex:- if (condition): Statement
Nested If Statement
Syntax :
if (condition):
block of statements
if(condition):
block of statements
if(condition):
block of statements
if(condition):
block of statements
Rest of the code
If Else Statement
if… else statement is used when a different sequence of instructions is to be executed
depending on the logical value(True/False) of the condition evaluated.
Syntax: -
if(condition):
Statement 1
if(condition):
Statement 2
Statement 1
else:
else:
Statement 3
Statement 2
Statement 4
Rest of the Code
Rest of the Code
Nested If Else Statement
if(condition_1): if(condition_1):
if(condition_2): if(condition_2):
Statement 1 Statement 1
else:
else: Statement 2
Statement 2 else:
else: if(condition_3):
Statement 3 Statement 3
else:
Rest of the Code Statement 4
Rest of the Code
if elif Statement
To show a multi-way decision based on several conditions, we use if elif statement.
if (condition_1):
Statement 1
elif (condition_2):
Statement 2
elif (condition_3):
Statement 3
elif (condition_n):
Statement n
Rest of the Code
if elif else Statement
To show a multi-way decision based on several conditions, we use if elif else statement.
if (condition_1):
Statement 1
elif (condition_2):
Statement 2
elif (condition_3):
Statement 3
elif (condition_n):
Statement n
else:
Statements x
Rest of the Code
Loop Control Statements
Loop control statements are used when a section of code may either be
executed a fixed number of times, or while some condition is true.
• While
• For
while Loop
The while loop keeps repeating an action until an associated condition returns false.
while (True):
Statement
if(condition):
break
Rest of the Code
Nested While Loop
while(condition):
Statements
while(condition):
Statements
Statements
Rest of Code
range( ) Function
range() function is used to generate a sequence of integers starting from 0 by default,
and increments by 1 by default, till j-1.
Syntax:-
range(start, stop, stepsize)
*Stop – Ending position. The range of integers stops one element prior to stop. If stop is
j then it will stop at exact j-1
Ex:- a = [ ]
Tuple
Tuple – A tuple contains a group of elements which can be same or different types.
Tuples are immutable.
It is similar to List but Tuples are read-only which means we can not modify it’s
element.
Tuples are used to store data which should not be modified.
It occupies less memory compare to list.
Tuples are represented using parentheses ( ).
Ex:- a = (10, 20, -50, 21.3, ‘python’)
Creating Empty Tuple
Syntax:- tuple_name = ( )
Ex:- a = ( )
Set Type
A set is an unordered collection of elements much like a set in mathematics.
The order of elements is not maintained in the sets. It means the elements may not
appear in the same order as they are entered into the set.
A set does not accept duplicate elements.
Set is mutable so we can modify it.
Sets are unordered so we can not access its element using index.
Sets are represented using curly brackets { }
a = {10, 20, 30, “python”, “Raj”, 40}
Creating Empty Set
We can create an empty set using set( ) function.
a = set()
Dictionary
A Dictionary represents a group of elements in the form of key value pairs.
Dictionary in Python is an unordered collection.
Dictionaries are mutable so we can modify it’s item, without changing their identity.
Dictionaries are represented using curly bracket { }.
Ex:-
stu = {101: ‘Rahul’, 102: ‘Raj’, 103: ‘Sonam’ }
fees= {‘rahul’:2000, ‘raj’:3000, ‘sonam’:8000}
Creating an Empty Dictionary
Syntax:- dict_name = { }
Ex:- fees = { }
Function
Function
A function is a block of code that performs a specific task.
Type of Functions:-
• Built-in Function
Ex: - print( ), upper( ) etc
• User-defined Function
Advantage of Function
• Write once and use it as many time as you need. This provides code
reusability.
• Function facilitates ease of code maintenance.
• Divide Large task into many small task so it will help you to debug code
• You can remove or add new feature to a function anytime.
Function Definition
We can define a function using def keyword followed by function name with parentheses.
Syntax : -
def Function_name ( ):
Local Variable
block of statement
Function Body
return (variable or expression)
Syntax : -
def Function_name (para1, para2, …):
Local Variable
block of statement
Function Body
return (variable or expression)
Ex: -
a = 10
add ( ) add(a)
add (20)
add(10.56)
add(“python”)
Type of Actual Arguments
• Positional Arguments
• Keyword Arguments
• Default Arguments
• Variable Length Arguments
• Keyword Variable Length Arguments
Modules
Module
A module is a file containing group of variables, methods, function and classes etc.
They are executed only the first time the module name is encountered in an import
statement.
The file name is the module name with the suffix .py appended.
Ex:- mymodule.py
Type of Modules:-
• User-defined Modules
• Built-in Modules
Ex:- array, math, numpy, sys
How to use Module
import statement is used to import modules.
Syntax:-
import module_name
import module_name as alias_name
from module_name import function_name1, function_name2,……, function_nameN
from module_name import var_name1, var_name2,……, var_nameN
from module_name import var_name, f_name, class_name, method_name……,
from module_name import class_name1, class_name2,……, class_nameN
Syntax:- module_name.function_name()
Ex:-
cal.add(10, 20)
When 2 modules having same function name then
cal.sub(20, 10)
This import module is good approach to use.
add = cal.add
add(10, 20)
Converting ipynb into py
• Importing or including an .ipynb file directly into another .ipynb file is not a
built-in feature of Jupyter Notebooks.
• Convert to Python Script: First, convert the source .ipynb file into a Python script
using the nbconvert command-line tool. This will create a .py file containing the
code cells from the notebook.
jupyter nbconvert --to script source_notebook.ipynb
• Import the Python Script: In your target .ipynb file, you can import the generated
.py script as if it were a regular Python module.
import source_notebook
papermill or nbinclude
Numpy
• Refer to your class notes
Pandas
• Refer to your class notes
Matplotlib
• Refer to your class notes