SlideShare a Scribd company logo
Swarup Kr Ghosh
MIS Group
IIM Calcutta
swarupg1@gmail.com
 History
 Why is it called Python?
 Features and Philosophy
 Installing and Running of Python
 Applications
 Who uses python today?
 Python Interactive Shell
 Basic data types and operator on Python
4/5/2015 2Swarup Kr Ghosh
 Its Implementation was started in December 1989 in
CWI ( Centrum Wiskunde & Informatica) in
Netherlands
 Invented by Guido van Rossum, early 90s (Feb‟91)
 It is successor of ABC Programming Language
 Python 2.0 was released in October 2000, with
many new features including a full garbage
collector and Unicode
 Python 3.0 was released in December 2008.
 Open sourced from the beginning.
4/5/2015 3Swarup Kr Ghosh
 Name should be short, unique, interesting and
something mysterious
 A published scripts from ”Monty Python‟s Flying
Circus”
◦ a BBC comedy series from the seventies
 So the language called Python
4/5/2015 4Swarup Kr Ghosh
“Python is an experiment in
how much freedom
programmers need. Too
much freedom and nobody
can read another's code; too
little and expressive-ness is
endangered.”
- Guido van Rossum
4/5/2015 5Swarup Kr Ghosh
 Open Source
 Coherence
◦ not hard to read, write and maintain
 power
 scope
◦ rapid development + large systems
 objects
 integration
◦ hybrid systems
4/5/2015 6Swarup Kr Ghosh
 Scripting-Extension Language
◦ Object-Oriented scripting language
 Class, Object (instances of classes), Encapsulation, Abstraction, Inheritance,
Polymorphism
 Multi paradigm language
◦ Object Oriented, Structure Programming, Functional Programming
 Classes, module and exception
 Runs on many different Operating System
◦ No compiling and linking
 Simple, shorter and more flexible
◦ No type declarations
 Automatic memory management
◦ Garbage collection
4/5/2015 7Swarup Kr Ghosh
 Fewer restriction and rules
◦ Without using brackets
 Interactive and dynamic in nature
◦ Run time program construction
 System tools, GUIs, persistence, databases
 Modules and package
◦ Code can be grouped
 IDLE
◦ Bundled development environment
 elements from C++, Modula-3 (modules), ABC
 same family as Perl, Tcl, Scheme, REXX, BASIC dialects
4/5/2015 8Swarup Kr Ghosh
 Python is pre-installed on most Unix systems, including
Linux and MAC OS X
 The pre-installed version may not be the most recent
one (2.7.9 and 3.4.3 as of July‟14)
 Download from http://python.org/download/
 Python comes with a large library of standard modules
 There are several options for an IDE
◦ IDLE – works well with Windows
◦ Emacs with python-mode or your favorite text editor
4/5/2015 9Swarup Kr Ghosh
4/5/2015 10Swarup Kr Ghosh
4/5/2015 11Swarup Kr Ghosh
 IDLE is an Integrated Development Environment for Python, typically
used on Windows
 Multi-window text editor with syntax highlighting, auto-completion,
smart indent and other.
 Python shell with syntax highlighting
 Integrated debugger with
stepping, persistent
break points, and call stack
visibility
4/5/2015 12Swarup Kr Ghosh
 Substitute of C, C++, C#, Objective C, Java
 Serve as scripting language
◦ Web application
 Data mapper
 Text mining
◦ NLP
 Used in AI Programming (Prolog, Exsys Corvid)
 Bioinformatics
◦ Using library Biopython and Astropy
 Scientific and Mathematical computing
◦ Using library NumPy, SciPy, Matplotlib etc
 Information security
 Image and video processing
4/6/2015 13Swarup Kr Ghosh
 Google: web search system & app engine web.
 You Tube video sharing service.
 ‘Bit Torrent’ peer-to-peer file sharing.
 ‘Maya’ 3D modeling and animation system.
 NASA uses python for cryptography & intelligence
system.
 Intel, Cisco, Hewlett-Packard, Seagate, Qualc-
omm, and IBM for Hardware testing.
 ‘iRobot‟ uses Python to develop commercial and
military robotic devices.
4/6/2015 14Swarup Kr Ghosh
 Learning Python by Mark Lutz, 5th Edition
 Python Essential by David Beazley
 A Python Book: Beginning Python, Advanced
Python, and Python Exercises by Dave Kuhlman
 https://wiki.python.org/moin/PythonBooks
 https://www.python.org/about/gettingstarted/
 http://www.learnpython.org/
 http://www.tutorialspoint.com/python/
4/6/2015 15Swarup Kr Ghosh
4/6/2015 16Swarup Kr Ghosh
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600
32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
 Python prompts with „>>>‟
 To exit Python: CTRL-D
You can type things directly into a running Python session:
>>> a=7
>>> a
7
>>> b=8
>>> b
8
>>> a+b
15
>>>
4/6/2015 17Swarup Kr Ghosh
>>> 2+3*4
14
>>> 2**8
256
>>> print(2**8)
256
>>> print(2**100)
1267650600228229401496703205376
>>>print “Hello world”
Hello world
>>> a="Hello world"
>>> a
'Hello world'
>>> len(a) #„len‟- Length of String
11
4/6/2015 18Swarup Kr Ghosh
>>> help(len)
Return the number of items of a sequence or collection.
Similarly >>>help(exit)
>>> name="Andrew"
>>> name=name+'!!!!'
>>> print("Hello", name)
Hello Andrew!!!!
4/6/2015 19Swarup Kr Ghosh
Object Type Examples literals/ creation
Numbers 1234, 3.141, 2+3j, 001101, Decimal(), Fraction()
Strings „Spam‟, “Bob‟s”, b'ax01c„, u'spxc4m„(unicode)
Lists [1,[2,three],4.5], list(range(10))
Tuples (1, „spam‟, 4, „U‟), tuple(„spam‟)
Dictionaries {„user‟: „scott‟, „pswd‟:12345}, dict=(hours=10)
Files Open(„wave.txt‟), open(r 'C:bin', 'wb')
Sets set('abc'), {'a', 'b', 'c'}
Other Data type Boolean
4/6/2015 20Swarup Kr Ghosh
 Arithmetic Operators: +, - ,* ,/,//, %
◦ Special use of „+’ for string concatenation
◦ Special use of „*’ for string repetition
◦ Special use of „–’ for set difference
◦ Special use of % for string formatting (as with printf in C)
◦ „//‟ use for floor division
 Assignment: = and comparison ==
 Logical operators are words (and, or, not)
 The basic printing command is print
 The first assignment to a variable creates it
◦ Variable types don‟t need to be declared
◦ Python figures out the variable types on its own
4/6/2015 21Swarup Kr Ghosh
 Integers (default for numbers)
z = 5+2 # Answer is 7
z=5%2 # Answer is 1
z=5//2 # Answer is 2
 Floats
x = 5/2 # Answer is 2.5
 Strings
◦ Can use “” or „‟ to specify
◦ “abc” „abc‟ (Same thing)
 Unmatched can occur within the string
“matt‟s”
 Use triple double-quotes for multi-line strings or strings
than contain both „and “ inside of them:
“““a„b“c”””
4/6/2015 22Swarup Kr Ghosh
 Integer, float, fraction, complex number, binary, octal,
hexadecimal
>>> 3.1415 * 2
6.283
 Module: just package of additional tool
◦ Math()
>>> import math
>>> math.pi #pi is method
3.141592653589793
>>> math.sqrt(85)
9.219544457292887
◦ Random()
>>> import random
>>> random.random()
0.7082048489415967
>>> random.choice([1, 2, 3, 4])
1
Methods: sqrt(), pow(), round(), trunc(), floor()
4/6/2015 23Swarup Kr Ghosh
4/6/2015 24Swarup Kr Ghosh
Operators Symbols
Arithmetic: +, -, *, /, **, //, %
Logical: and, or, not
Relational: >, <, >=, <=, ==, !=
Bitwise: &, |, ^, ~
Shifting: << (LS), >> (RS)
Membership X in y, x not in y
Object identity X is y, x is not y
Slicing X[i:j:k]
Call(fun, method, class) X(….)
Tuple ( )
List [ ]
Dictionary { }
4/5/2015 25Swarup Kr Ghosh
4/6/2015 26Swarup Kr Ghosh
 E.g. 2+3J
>>> 1J*1J
(-1+0j)
>>> 2+3J*3
(2+9j)
>>> (2+3J)*3
(6+9j)
>>>
4/6/2015 27Swarup Kr Ghosh
 Binary: 0b01010, 0b10001, 0b111111
 Octal: 0o172, 0o03507, 0o53702
 Hexa: 0xFF, 0xff, 0x1abc
>>> 0b0010
2
>>> 0o145
101
>>> 0o172
122
>>> 0xff
255
>>> 0xFF
255
>>> 0x1abc
6844
4/5/2015 28Swarup Kr Ghosh
>>> 0o1,0o20,0o377
(1, 16, 255)
>>> 0b01, 0b10000,0b1111111
(1, 16, 127)
>>> oct(64),bin(64),hex(64)
('0o100', '0b1000000', '0x40')
>>> int('64'), int('100',8),int('40',16),int('1000000',2)
(64, 64, 64, 64)
>>> '{0:o}, {1:x}, {2:b}'.format(64, 64, 64)
'100, 40, 1000000'
>>> '%o, %x, %x, %X' % (64, 64, 255, 255)
'100, 40, ff, FF„
>>> x=0xfffffff #By using method
>>> x
268435455
>>> bin(x)
'0b1111111111111111111111111111'
>>> oct(x)
'0o1777777777'
4/5/2015 29Swarup Kr Ghosh
 Fraction: Numerator, denominator (x/y)
 Module: fractions
>>>from fractions import Fraction
>>> Fraction(2,3)
Fraction(2, 3)
>>> y=Fraction(4,6)
>>> print(y)
2/3
>>> a=Fraction(1,3) #operations on fractions
>>> b=Fraction(2,3)
>>> a+b
Fraction(1, 1)
>>> a-b
Fraction(-1, 3)
>>> a/b
Fraction(1, 2)
4/5/2015 30Swarup Kr Ghosh
>>> Fraction(6,12)
Fraction(1, 2)
# automatically simplifed
>>> Fraction('.25')
Fraction(1, 4)
>>> Fraction('1.25')
Fraction(5, 4)
>>> Fraction('.25')+Fraction('1.25')
Fraction(3, 2)
>>> Fraction(5,0)
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
Fraction(5,0)
File "C:Python34libfractions.py", line 167, in __new__
raise ZeroDivisionError('Fraction(%s, 0)' % numerator)
ZeroDivisionError: Fraction(5, 0)
4/5/2015 31Swarup Kr Ghosh
 Precision and scale:
>>> 1/3
0.3333333333333333
>>> from decimal import Decimal
>>> 1/3
0.3333333333333333
>>> import decimal
>>> decimal.getcontext().prec=2
>>> Decimal(1)/Decimal(3)
Decimal('0.33')
>>> (1/3)+(6/12)
0.8333333333333333
>>> decimal.Decimal(str(1/3)) + decimal.Decimal(str(6/12))
Decimal('0.83')
4/5/2015 32Swarup Kr Ghosh
 Module: set
>>> x=set('abcde')
>>> y=set('bdxyz')
>>> x
{'a', 'd', 'b', 'c', 'e'}
>>> y
{'x', 'd', 'b', 'z', 'y'}
>>> x|y #Union
{'d', 'e', 'y', 'c', 'x', 'a', 'b', 'z'}
>>> x&y # Intersection
{'d', 'b'}
>>> x-y # Set Difference
{'a', 'e', 'c'}
>>> x^y # Symmetric difference
{'e', 'y', 'c', 'x', 'a', 'z'}
>>> x>y,x<y #Superset, Subset
(False, False)
4/5/2015 33Swarup Kr Ghosh
 Different way of set operations:
>>> s=set('spam')
>>> s
{'p', 's', 'a', 'm'}
>>> s={'s','p','a','m'}
>>> s
{'m', 'a', 'p', 's'}
>>> s.add('alot') # Add members in set
>>> s
{'m', 'a', 'p', 's', 'alot'}
>>> {1, 2, 3}.union([3, 4])
{1, 2, 3, 4}
>>> {1, 2, 3}.union({3, 4})
{1, 2, 3, 4}
>>> {1, 2, 3}.union(set([3, 4]))
{1, 2, 3, 4}
>>> {1, 2, 3}.intersection((1, 3, 5))
{1, 3}
>>> {1, 2, 3}.issubset(range(-5, 5))
True
4/5/2015 34Swarup Kr Ghosh
Different way of set operations:
>>>{x**2 for x in [1,2,3,4]}
{16, 1, 9, 4}
>>> {x for x in 'spam'} # Same as: set('spam')
{'m', 's', 'p', 'a'}
>>> {c * 4 for c in 'spam'} # Set of collected expression
{'pppp', 'aaaa', 'ssss', 'mmmm'}
>>> {c * 4 for c in 'spamham'}
{'pppp', 'aaaa', 'hhhh', 'ssss', 'mmmm'}
>>> S = {c * 4 for c in 'spam'}
4/5/2015 35Swarup Kr Ghosh
>>> x = 4.5
>>> y = x
>>> y += 3
>>> x
4.5
>>> y
7.5
x 4.5
y
x 4.5
y 7.5
4/5/2015 36Swarup Kr Ghosh
 Whitespace is meaningful in Python:
especially indentation and placement of newlines
 Use a newline to end a line of code
◦ Use  when must go to next line prematurely
 No braces { } to mark blocks of code in Python
◦ Use consistent indentation instead
◦ The first line with less indentation is outside of the block
◦ The first line with more indentation starts a nested block
 Often a colon (:) appears at the start of a new
block.
E.g. for function and class definitions.
4/5/2015 37Swarup Kr Ghosh
 Binding a variable in Python means setting a name to
hold a reference to some object
◦ Assignment creates references, not copies
 Variable creation:
◦ A variable (i.e., name), like „a‟, is created when code first
assigns it a value.
 Variable types:
◦ A variable never has any type information or constraints
associated with it. The notion of type lives with objects, not
names
◦ Variables are generic in nature
 Variable use:
◦ When a variable appears in an expression, it is immediately
replaced with the object that it currently refers to
4/5/2015 38Swarup Kr Ghosh
 Names in Python do not have an intrinsic type, objects
have types
◦ Python determines the type of the reference
automatically based on the data object assigned to it.
 You create a name the first time it appears on the left
side of an assignment expression:
x = 3
 A reference is deleted via garbage collection after any
names bound to it have passed out of scope
4/5/2015 39Swarup Kr Ghosh
 If you try to access a name before it‟s been
properly created you‟ll get an error.
>>> y
Traceback (most recent call last):
File "<pyshell#16>", line 1, in -toplevely
NameError: name „y' is not defined
>>> y = 3
>>> y
3
4/5/2015 40Swarup Kr Ghosh
 You can also assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
4/5/2015 41Swarup Kr Ghosh
 Names are case sensitive and cannot start with a
number
 Contain letters, numbers, and underscores
◦ Bob, Bob _, bob _2, _bob_, bob_2, bob
 There are some reserved words:
and, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise,
return, try, while
4/5/2015 42Swarup Kr Ghosh
 Start comments with #, rest of line is ignored
 Can include a “documentation string” as the first
line of a new function or class you define
 Development environments, debugger, and other
tools use it
def my_function(x, y):
“““This is the docstring. This
function does blah blah blah.”””
# The code would go here...
4/5/2015 43Swarup Kr Ghosh
 Assignment manipulates references:
◦ x = y does not make a copy of the object y references
◦ x = y makes x reference the object y references
 There is a lot going on when we type:
x = 3
◦ First, an integer 3 is created and stored in memory
◦ A name x is created
◦ An reference to the memory location storing the 3 is then
assigned to the name x
4/5/2015 44Swarup Kr Ghosh
 So: When we say that the
value of x is 3
 we mean that x now
refers to the integer 3
4/6/2015 45Swarup Kr Ghosh
 The data 3 we created is of type integer. In Python,
the data types integer, float, and string (and tuple) are
immutable
 This doesn‟t mean we can‟t change the value of „a‟,
i.e. change what „a‟ refers to …
 For example, we could increment a:
>>> a = 1
>>> b=a
>>> a = a + 1
>>> print a
2
>>> print b
1
4/6/2015 46Swarup Kr Ghosh
a
1
b
a
1b
a = 1
a = a+1
b = a
a
1
2
old reference deleted
by assignment (a=...)
new int object created
by add operator (1+1)
4/5/2015 47Swarup Kr Ghosh
n -> newline
t -> tab
 -> backslash
w -> word character
d -> digit
s -> white space
S -> non-white space
4/5/2015 48Swarup Kr Ghosh
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'math', 'random']
>>>dir(re)
['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE',
'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE',
'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__',
'__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', '__version__', '_alphanum_bytes',
'_alphanum_str', '_cache', '_cache_repl', '_compile',
'_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx',
'compile', 'copyreg', 'error', 'escape', 'findall', 'finditer', 'fullmatch',
'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub',
'subn', 'sys', 'template']
4/5/2015 49Swarup Kr Ghosh
4/5/2015 50Swarup Kr Ghosh

More Related Content

PPTX
PART 1 - Python Tutorial | Variables and Data Types in Python
PDF
PDF
Python Programming
PPTX
PART 9 - Python Tutorial | While Loop In Python With Examples
PPTX
Introduction to numpy Session 1
PPTX
PART 7 - Python Tutorial | Dictionaries In Python With Examples
PPTX
PART 4 - Python Tutorial | If Else In Python With Examples
PPTX
Beginning Python Programming
PART 1 - Python Tutorial | Variables and Data Types in Python
Python Programming
PART 9 - Python Tutorial | While Loop In Python With Examples
Introduction to numpy Session 1
PART 7 - Python Tutorial | Dictionaries In Python With Examples
PART 4 - Python Tutorial | If Else In Python With Examples
Beginning Python Programming

What's hot (20)

PPTX
Operators in Python
PDF
Introduction to python
PPTX
STRINGS IN PYTHON
PPTX
Python basics
PDF
Python unit 2 as per Anna university syllabus
PPTX
PART 3 - Python Tutorial | For Loop In Python With Examples
PPT
Introduction to Python
PPT
Stack and heap allocation
PPTX
Introduction to Data Structures and Linked List
PDF
Ensayo
PPT
Data structure.ppt
PPTX
Part 2 - Python Tutorial | Introduction to Lists
PDF
Git training v10
PDF
Python Basics | Python Tutorial | Edureka
PDF
Teach a Dog to REST
DOCX
DSA- Unit III- STACK AND QUEUE
PPTX
Remnux tutorial-1 Statically Analyse Portable Executable(PE) Files
PPTX
Back patching
PPT
Python Control structures
PDF
Python Basics
Operators in Python
Introduction to python
STRINGS IN PYTHON
Python basics
Python unit 2 as per Anna university syllabus
PART 3 - Python Tutorial | For Loop In Python With Examples
Introduction to Python
Stack and heap allocation
Introduction to Data Structures and Linked List
Ensayo
Data structure.ppt
Part 2 - Python Tutorial | Introduction to Lists
Git training v10
Python Basics | Python Tutorial | Edureka
Teach a Dog to REST
DSA- Unit III- STACK AND QUEUE
Remnux tutorial-1 Statically Analyse Portable Executable(PE) Files
Back patching
Python Control structures
Python Basics
Ad

Similar to Python lec1 (20)

PDF
05 python.pdf
PPTX
Introduction to python.pptx
PDF
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
Python Orientation
ODP
Learn python
PDF
The genesis of clusterlib - An open source library to tame your favourite sup...
PPT
Python Evolution
PPT
Sample Lab Orientation in Python orientation
ODP
PyQt Application Development On Maemo
PPTX
Python programming language presentation
PPT
Spsl iv unit final
PPT
Spsl iv unit final
PDF
PyCon Estonia 2019
PDF
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
PDF
Hacking the Kinect with GAFFTA Day 1
PDF
CrashCourse: Python with DataCamp and Jupyter for Beginners
PDF
PyCon Taiwan 2013 Tutorial
PDF
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PDF
Using SWIG to Control, Prototype, and Debug C Programs with Python
PDF
maXbox Starter 45 Robotics
05 python.pdf
Introduction to python.pptx
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Python Orientation
Learn python
The genesis of clusterlib - An open source library to tame your favourite sup...
Python Evolution
Sample Lab Orientation in Python orientation
PyQt Application Development On Maemo
Python programming language presentation
Spsl iv unit final
Spsl iv unit final
PyCon Estonia 2019
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Hacking the Kinect with GAFFTA Day 1
CrashCourse: Python with DataCamp and Jupyter for Beginners
PyCon Taiwan 2013 Tutorial
PYTHON PROGRAMMING NOTES RKREDDY.pdf
Using SWIG to Control, Prototype, and Debug C Programs with Python
maXbox Starter 45 Robotics
Ad

Recently uploaded (20)

PDF
Basic Mud Logging Guide for educational purpose
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharma ospi slides which help in ospi learning
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Insiders guide to clinical Medicine.pdf
PPTX
master seminar digital applications in india
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
Basic Mud Logging Guide for educational purpose
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPH.pptx obstetrics and gynecology in nursing
Supply Chain Operations Speaking Notes -ICLT Program
TR - Agricultural Crops Production NC III.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Structure & Organelles in detailed.
2.FourierTransform-ShortQuestionswithAnswers.pdf
VCE English Exam - Section C Student Revision Booklet
Pharma ospi slides which help in ospi learning
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Insiders guide to clinical Medicine.pdf
master seminar digital applications in india
human mycosis Human fungal infections are called human mycosis..pptx
O5-L3 Freight Transport Ops (International) V1.pdf

Python lec1

  • 1. Swarup Kr Ghosh MIS Group IIM Calcutta swarupg1@gmail.com
  • 2.  History  Why is it called Python?  Features and Philosophy  Installing and Running of Python  Applications  Who uses python today?  Python Interactive Shell  Basic data types and operator on Python 4/5/2015 2Swarup Kr Ghosh
  • 3.  Its Implementation was started in December 1989 in CWI ( Centrum Wiskunde & Informatica) in Netherlands  Invented by Guido van Rossum, early 90s (Feb‟91)  It is successor of ABC Programming Language  Python 2.0 was released in October 2000, with many new features including a full garbage collector and Unicode  Python 3.0 was released in December 2008.  Open sourced from the beginning. 4/5/2015 3Swarup Kr Ghosh
  • 4.  Name should be short, unique, interesting and something mysterious  A published scripts from ”Monty Python‟s Flying Circus” ◦ a BBC comedy series from the seventies  So the language called Python 4/5/2015 4Swarup Kr Ghosh
  • 5. “Python is an experiment in how much freedom programmers need. Too much freedom and nobody can read another's code; too little and expressive-ness is endangered.” - Guido van Rossum 4/5/2015 5Swarup Kr Ghosh
  • 6.  Open Source  Coherence ◦ not hard to read, write and maintain  power  scope ◦ rapid development + large systems  objects  integration ◦ hybrid systems 4/5/2015 6Swarup Kr Ghosh
  • 7.  Scripting-Extension Language ◦ Object-Oriented scripting language  Class, Object (instances of classes), Encapsulation, Abstraction, Inheritance, Polymorphism  Multi paradigm language ◦ Object Oriented, Structure Programming, Functional Programming  Classes, module and exception  Runs on many different Operating System ◦ No compiling and linking  Simple, shorter and more flexible ◦ No type declarations  Automatic memory management ◦ Garbage collection 4/5/2015 7Swarup Kr Ghosh
  • 8.  Fewer restriction and rules ◦ Without using brackets  Interactive and dynamic in nature ◦ Run time program construction  System tools, GUIs, persistence, databases  Modules and package ◦ Code can be grouped  IDLE ◦ Bundled development environment  elements from C++, Modula-3 (modules), ABC  same family as Perl, Tcl, Scheme, REXX, BASIC dialects 4/5/2015 8Swarup Kr Ghosh
  • 9.  Python is pre-installed on most Unix systems, including Linux and MAC OS X  The pre-installed version may not be the most recent one (2.7.9 and 3.4.3 as of July‟14)  Download from http://python.org/download/  Python comes with a large library of standard modules  There are several options for an IDE ◦ IDLE – works well with Windows ◦ Emacs with python-mode or your favorite text editor 4/5/2015 9Swarup Kr Ghosh
  • 12.  IDLE is an Integrated Development Environment for Python, typically used on Windows  Multi-window text editor with syntax highlighting, auto-completion, smart indent and other.  Python shell with syntax highlighting  Integrated debugger with stepping, persistent break points, and call stack visibility 4/5/2015 12Swarup Kr Ghosh
  • 13.  Substitute of C, C++, C#, Objective C, Java  Serve as scripting language ◦ Web application  Data mapper  Text mining ◦ NLP  Used in AI Programming (Prolog, Exsys Corvid)  Bioinformatics ◦ Using library Biopython and Astropy  Scientific and Mathematical computing ◦ Using library NumPy, SciPy, Matplotlib etc  Information security  Image and video processing 4/6/2015 13Swarup Kr Ghosh
  • 14.  Google: web search system & app engine web.  You Tube video sharing service.  ‘Bit Torrent’ peer-to-peer file sharing.  ‘Maya’ 3D modeling and animation system.  NASA uses python for cryptography & intelligence system.  Intel, Cisco, Hewlett-Packard, Seagate, Qualc- omm, and IBM for Hardware testing.  ‘iRobot‟ uses Python to develop commercial and military robotic devices. 4/6/2015 14Swarup Kr Ghosh
  • 15.  Learning Python by Mark Lutz, 5th Edition  Python Essential by David Beazley  A Python Book: Beginning Python, Advanced Python, and Python Exercises by Dave Kuhlman  https://wiki.python.org/moin/PythonBooks  https://www.python.org/about/gettingstarted/  http://www.learnpython.org/  http://www.tutorialspoint.com/python/ 4/6/2015 15Swarup Kr Ghosh
  • 17. Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information.  Python prompts with „>>>‟  To exit Python: CTRL-D You can type things directly into a running Python session: >>> a=7 >>> a 7 >>> b=8 >>> b 8 >>> a+b 15 >>> 4/6/2015 17Swarup Kr Ghosh
  • 18. >>> 2+3*4 14 >>> 2**8 256 >>> print(2**8) 256 >>> print(2**100) 1267650600228229401496703205376 >>>print “Hello world” Hello world >>> a="Hello world" >>> a 'Hello world' >>> len(a) #„len‟- Length of String 11 4/6/2015 18Swarup Kr Ghosh
  • 19. >>> help(len) Return the number of items of a sequence or collection. Similarly >>>help(exit) >>> name="Andrew" >>> name=name+'!!!!' >>> print("Hello", name) Hello Andrew!!!! 4/6/2015 19Swarup Kr Ghosh
  • 20. Object Type Examples literals/ creation Numbers 1234, 3.141, 2+3j, 001101, Decimal(), Fraction() Strings „Spam‟, “Bob‟s”, b'ax01c„, u'spxc4m„(unicode) Lists [1,[2,three],4.5], list(range(10)) Tuples (1, „spam‟, 4, „U‟), tuple(„spam‟) Dictionaries {„user‟: „scott‟, „pswd‟:12345}, dict=(hours=10) Files Open(„wave.txt‟), open(r 'C:bin', 'wb') Sets set('abc'), {'a', 'b', 'c'} Other Data type Boolean 4/6/2015 20Swarup Kr Ghosh
  • 21.  Arithmetic Operators: +, - ,* ,/,//, % ◦ Special use of „+’ for string concatenation ◦ Special use of „*’ for string repetition ◦ Special use of „–’ for set difference ◦ Special use of % for string formatting (as with printf in C) ◦ „//‟ use for floor division  Assignment: = and comparison ==  Logical operators are words (and, or, not)  The basic printing command is print  The first assignment to a variable creates it ◦ Variable types don‟t need to be declared ◦ Python figures out the variable types on its own 4/6/2015 21Swarup Kr Ghosh
  • 22.  Integers (default for numbers) z = 5+2 # Answer is 7 z=5%2 # Answer is 1 z=5//2 # Answer is 2  Floats x = 5/2 # Answer is 2.5  Strings ◦ Can use “” or „‟ to specify ◦ “abc” „abc‟ (Same thing)  Unmatched can occur within the string “matt‟s”  Use triple double-quotes for multi-line strings or strings than contain both „and “ inside of them: “““a„b“c””” 4/6/2015 22Swarup Kr Ghosh
  • 23.  Integer, float, fraction, complex number, binary, octal, hexadecimal >>> 3.1415 * 2 6.283  Module: just package of additional tool ◦ Math() >>> import math >>> math.pi #pi is method 3.141592653589793 >>> math.sqrt(85) 9.219544457292887 ◦ Random() >>> import random >>> random.random() 0.7082048489415967 >>> random.choice([1, 2, 3, 4]) 1 Methods: sqrt(), pow(), round(), trunc(), floor() 4/6/2015 23Swarup Kr Ghosh
  • 25. Operators Symbols Arithmetic: +, -, *, /, **, //, % Logical: and, or, not Relational: >, <, >=, <=, ==, != Bitwise: &, |, ^, ~ Shifting: << (LS), >> (RS) Membership X in y, x not in y Object identity X is y, x is not y Slicing X[i:j:k] Call(fun, method, class) X(….) Tuple ( ) List [ ] Dictionary { } 4/5/2015 25Swarup Kr Ghosh
  • 27.  E.g. 2+3J >>> 1J*1J (-1+0j) >>> 2+3J*3 (2+9j) >>> (2+3J)*3 (6+9j) >>> 4/6/2015 27Swarup Kr Ghosh
  • 28.  Binary: 0b01010, 0b10001, 0b111111  Octal: 0o172, 0o03507, 0o53702  Hexa: 0xFF, 0xff, 0x1abc >>> 0b0010 2 >>> 0o145 101 >>> 0o172 122 >>> 0xff 255 >>> 0xFF 255 >>> 0x1abc 6844 4/5/2015 28Swarup Kr Ghosh
  • 29. >>> 0o1,0o20,0o377 (1, 16, 255) >>> 0b01, 0b10000,0b1111111 (1, 16, 127) >>> oct(64),bin(64),hex(64) ('0o100', '0b1000000', '0x40') >>> int('64'), int('100',8),int('40',16),int('1000000',2) (64, 64, 64, 64) >>> '{0:o}, {1:x}, {2:b}'.format(64, 64, 64) '100, 40, 1000000' >>> '%o, %x, %x, %X' % (64, 64, 255, 255) '100, 40, ff, FF„ >>> x=0xfffffff #By using method >>> x 268435455 >>> bin(x) '0b1111111111111111111111111111' >>> oct(x) '0o1777777777' 4/5/2015 29Swarup Kr Ghosh
  • 30.  Fraction: Numerator, denominator (x/y)  Module: fractions >>>from fractions import Fraction >>> Fraction(2,3) Fraction(2, 3) >>> y=Fraction(4,6) >>> print(y) 2/3 >>> a=Fraction(1,3) #operations on fractions >>> b=Fraction(2,3) >>> a+b Fraction(1, 1) >>> a-b Fraction(-1, 3) >>> a/b Fraction(1, 2) 4/5/2015 30Swarup Kr Ghosh
  • 31. >>> Fraction(6,12) Fraction(1, 2) # automatically simplifed >>> Fraction('.25') Fraction(1, 4) >>> Fraction('1.25') Fraction(5, 4) >>> Fraction('.25')+Fraction('1.25') Fraction(3, 2) >>> Fraction(5,0) Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> Fraction(5,0) File "C:Python34libfractions.py", line 167, in __new__ raise ZeroDivisionError('Fraction(%s, 0)' % numerator) ZeroDivisionError: Fraction(5, 0) 4/5/2015 31Swarup Kr Ghosh
  • 32.  Precision and scale: >>> 1/3 0.3333333333333333 >>> from decimal import Decimal >>> 1/3 0.3333333333333333 >>> import decimal >>> decimal.getcontext().prec=2 >>> Decimal(1)/Decimal(3) Decimal('0.33') >>> (1/3)+(6/12) 0.8333333333333333 >>> decimal.Decimal(str(1/3)) + decimal.Decimal(str(6/12)) Decimal('0.83') 4/5/2015 32Swarup Kr Ghosh
  • 33.  Module: set >>> x=set('abcde') >>> y=set('bdxyz') >>> x {'a', 'd', 'b', 'c', 'e'} >>> y {'x', 'd', 'b', 'z', 'y'} >>> x|y #Union {'d', 'e', 'y', 'c', 'x', 'a', 'b', 'z'} >>> x&y # Intersection {'d', 'b'} >>> x-y # Set Difference {'a', 'e', 'c'} >>> x^y # Symmetric difference {'e', 'y', 'c', 'x', 'a', 'z'} >>> x>y,x<y #Superset, Subset (False, False) 4/5/2015 33Swarup Kr Ghosh
  • 34.  Different way of set operations: >>> s=set('spam') >>> s {'p', 's', 'a', 'm'} >>> s={'s','p','a','m'} >>> s {'m', 'a', 'p', 's'} >>> s.add('alot') # Add members in set >>> s {'m', 'a', 'p', 's', 'alot'} >>> {1, 2, 3}.union([3, 4]) {1, 2, 3, 4} >>> {1, 2, 3}.union({3, 4}) {1, 2, 3, 4} >>> {1, 2, 3}.union(set([3, 4])) {1, 2, 3, 4} >>> {1, 2, 3}.intersection((1, 3, 5)) {1, 3} >>> {1, 2, 3}.issubset(range(-5, 5)) True 4/5/2015 34Swarup Kr Ghosh
  • 35. Different way of set operations: >>>{x**2 for x in [1,2,3,4]} {16, 1, 9, 4} >>> {x for x in 'spam'} # Same as: set('spam') {'m', 's', 'p', 'a'} >>> {c * 4 for c in 'spam'} # Set of collected expression {'pppp', 'aaaa', 'ssss', 'mmmm'} >>> {c * 4 for c in 'spamham'} {'pppp', 'aaaa', 'hhhh', 'ssss', 'mmmm'} >>> S = {c * 4 for c in 'spam'} 4/5/2015 35Swarup Kr Ghosh
  • 36. >>> x = 4.5 >>> y = x >>> y += 3 >>> x 4.5 >>> y 7.5 x 4.5 y x 4.5 y 7.5 4/5/2015 36Swarup Kr Ghosh
  • 37.  Whitespace is meaningful in Python: especially indentation and placement of newlines  Use a newline to end a line of code ◦ Use when must go to next line prematurely  No braces { } to mark blocks of code in Python ◦ Use consistent indentation instead ◦ The first line with less indentation is outside of the block ◦ The first line with more indentation starts a nested block  Often a colon (:) appears at the start of a new block. E.g. for function and class definitions. 4/5/2015 37Swarup Kr Ghosh
  • 38.  Binding a variable in Python means setting a name to hold a reference to some object ◦ Assignment creates references, not copies  Variable creation: ◦ A variable (i.e., name), like „a‟, is created when code first assigns it a value.  Variable types: ◦ A variable never has any type information or constraints associated with it. The notion of type lives with objects, not names ◦ Variables are generic in nature  Variable use: ◦ When a variable appears in an expression, it is immediately replaced with the object that it currently refers to 4/5/2015 38Swarup Kr Ghosh
  • 39.  Names in Python do not have an intrinsic type, objects have types ◦ Python determines the type of the reference automatically based on the data object assigned to it.  You create a name the first time it appears on the left side of an assignment expression: x = 3  A reference is deleted via garbage collection after any names bound to it have passed out of scope 4/5/2015 39Swarup Kr Ghosh
  • 40.  If you try to access a name before it‟s been properly created you‟ll get an error. >>> y Traceback (most recent call last): File "<pyshell#16>", line 1, in -toplevely NameError: name „y' is not defined >>> y = 3 >>> y 3 4/5/2015 40Swarup Kr Ghosh
  • 41.  You can also assign to multiple names at the same time >>> x, y = 2, 3 >>> x 2 >>> y 3 4/5/2015 41Swarup Kr Ghosh
  • 42.  Names are case sensitive and cannot start with a number  Contain letters, numbers, and underscores ◦ Bob, Bob _, bob _2, _bob_, bob_2, bob  There are some reserved words: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while 4/5/2015 42Swarup Kr Ghosh
  • 43.  Start comments with #, rest of line is ignored  Can include a “documentation string” as the first line of a new function or class you define  Development environments, debugger, and other tools use it def my_function(x, y): “““This is the docstring. This function does blah blah blah.””” # The code would go here... 4/5/2015 43Swarup Kr Ghosh
  • 44.  Assignment manipulates references: ◦ x = y does not make a copy of the object y references ◦ x = y makes x reference the object y references  There is a lot going on when we type: x = 3 ◦ First, an integer 3 is created and stored in memory ◦ A name x is created ◦ An reference to the memory location storing the 3 is then assigned to the name x 4/5/2015 44Swarup Kr Ghosh
  • 45.  So: When we say that the value of x is 3  we mean that x now refers to the integer 3 4/6/2015 45Swarup Kr Ghosh
  • 46.  The data 3 we created is of type integer. In Python, the data types integer, float, and string (and tuple) are immutable  This doesn‟t mean we can‟t change the value of „a‟, i.e. change what „a‟ refers to …  For example, we could increment a: >>> a = 1 >>> b=a >>> a = a + 1 >>> print a 2 >>> print b 1 4/6/2015 46Swarup Kr Ghosh
  • 47. a 1 b a 1b a = 1 a = a+1 b = a a 1 2 old reference deleted by assignment (a=...) new int object created by add operator (1+1) 4/5/2015 47Swarup Kr Ghosh
  • 48. n -> newline t -> tab -> backslash w -> word character d -> digit s -> white space S -> non-white space 4/5/2015 48Swarup Kr Ghosh
  • 49. >>> dir() ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'random'] >>>dir(re) ['A', 'ASCII', 'DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_alphanum_bytes', '_alphanum_str', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copyreg', 'error', 'escape', 'findall', 'finditer', 'fullmatch', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template'] 4/5/2015 49Swarup Kr Ghosh