3 Python 3 Lecture 1-2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Python

- An Introduction

M. Shubhakanta Singh
Department of Physics, Manipur University
Why Python?
• Python is Object Oriented, Open source, Flexible and easy to
learn.
• It has a rich set of libraries and tools
• It has a huge community base(for queries and answers)
• Interactive, Modular, Dynamic, Portable, Extensible to C &C++
• Code readability (in fewer steps compare to Java or C++)
• Python is dynamically typed language, so the variables are
defined automatically.
Why software development companies prefer Python?
-Gaming, Web frameworks and applications, language
development, graphic design applications
• Integration Feature – Jython, Cython, etc
• Data science – Python, R, C++
• Google has made it one of its Official languages.
• Yahoo search engine
Dr. M. Shubhakanta Singh
Topics to be covered
• Python Environments : IDLE & Enthought Canopy/Spyder
• Basics of Python:
– Keywords & Identifiers
– Operators & Expressions
– Managing Input & Output operations
– Functions
– Decision making & Branching
– Decision making & Looping
• Python Sequences:
– Lists
–Tuples
• Python Dictionaries
• File managements
Dr. M. Shubhakanta Singh
Some Integrated Development
Environments (IDLEs) for Python
Environment Variable Web Site
IDLE The standard Python environment http://www.python.org/idle

Pythonwin Windows-oriented environment http://www.python.org/download/windows


ActivePython Feature-packed; contains http://www.activestate.com
Pythonwin IDE
Komodo Commercial IDE http://www.activestate.com3
Wingware Commercial IDE http://www.wingware.com
BlackAdder Commercial IDE and (Qt) GUI Builder http://www.thekompany.com
Boa Constructor Free IDE and GUI builder http://boa-constructor.sf.net
Anjuta Versatile IDE for Linux/UNIX http://anjuta.sf.net
Arachno Python Commercial IDE http://www.python-ide.com
Code Crusader Commercial IDE http://www.newplanetsoftware.com
Code Forge Commercial IDE http://www.codeforge.com
Eclipse Popular, flexible, open source IDE http://www.eclipse.org
eric Free IDE using Qt http://eric-ide.sf.net
KDevelop Cross-language IDE for KDE http://www.kdevelop.org
VisualWx Free GUI builder http://visualwx.altervista.org
wxDesigner Commercial GUI builder http://www.roebling.de
wxGlade Free GUI builder http://wxglade.sf.net
Enthought scientific and analytic Python packages https://www.enthought.com/products/canopy
Canopy + GUI Builder
Anaconda most popular Python packages + GUI https://www.continuum.io/downloads
Builder Dr. M. Shubhakanta Singh
Important differences between Python 2.x and
Python 3.x

 Division Operator In Python 2.x


>>> 7/3
print function 2 (no decimal part)
>>> -7/3
Unicode -3

xrange In Python 3.x


Error Handling
>>> 7/3
2.3333

__future__module
>>> -7/3
-2.3333
>>> -7//3
-3 ??? Why ???
Dr. M. Shubhakanta Singh
Important differences between Python 2.x and
Python 3.x
In Python 2.x print is a keyword
 Division Operator
but it is replaced by a print()
print function function in Python 3.x
However, parentheses work in
Unicode Python 2.x if a space is added
xrange after print keyword because the
interpreter evaluates it as an
Error Handling expression.
In Python 2.x:
__future__module print “Hello world”
print (“Hello World”)
In Python 3.x:
print (“Hello World”)
Dr. M. Shubhakanta Singh
Important differences between Python 2.x and
Python 3.x
In Python 2.x: implicit str type is ASCII whereas

 Division Operator print (type(" String by Default"))


in Python 3.x implicit str type is Unicode.

print (type(b" String by Default. "))


print function Output in Python 2.x:
<type ‘str’>

Unicode <type ‘str’> # Bytes is same as str


Output in Python 3.x:

xrange
<class ‘str’>
<class ‘bytes’> # Bytes and str are different

Error Handling
Python 2.x also supports Unicode:
print (type(" String by Default"))
print (type(u" String by Default. "))

__future__module <type ‘str’>


Output in Python 2.x:

<type ‘unicode’> # Unicode and str are different


Output in Python 3.x:
<class ‘str’>
<class ‘str’> # Unicode and str are same.
# print (type(b "String with Byte ")) ERROR!!!
Dr. M. Shubhakanta Singh
What is Unicode?

UNICODE: Universal Character Encoding.

In Python 2.x has ASCII str() types, separate


Unicode but it doesn't have byte type.
But in Python 3.x we have Unicode (utf-8: 8
means it uses 8-bit block to represent a
character) strings and also 2 byte array with
strings, because both are different for Python
3.x
Dr. M. Shubhakanta Singh
Important differences between Python 2.x and
Python 3.x
In Python 2.x:

 Division Operator
If we need to iterate over the same sequence
multiple times we prefer range() function as it

print function
provides a static list. xrange() reconstructs the
sequence every time.
The advantage of xrange() is, it saves memory

Unicode
when the task is to iterate over a large range.
In Python 3.x:

xrange
The range() function now does what xrange()
function does in Python 2.x. This helps us to
keep our code portable from Python 2.x to

Error Handling Python 3.x.


for x in range(1,6):

__future__module
print (x)
for x in xrange(1,6):
print (x)
Output in Python 2.x:
12345
12345
Output in Python 3.x: ‘xrange’ is not defined
Dr. M. Shubhakanta Singh
Important differences between Python 2.x and
Python 3.x

 Division Operator In Python 2.x:


try:

print function trying_to_check_error


except NameError, err:

Unicode
print (err, 'Error Caused')

In Python 3.x:
xrange try:
trying_to_check_error
Error Handling except NameError as err:
print (err, 'Error Caused')

__future__module

Dr. M. Shubhakanta Singh


Important differences between Python 2.x and
Python 3.x

 Division Operator Example 1: In Python 2.x


from __future__ import division

print function a= 14/4


print (a)

Unicode
Output:
3.5 (which is compatible with Python 3.x)
Example 1: In Python 2.x
xrange from __future__ import print_function
print('abc', 'def', '123', sep=' + ')

Error Handling
Output:
abc + def + 123 (which is compatible with

__future__module
Python 3.x)

Dr. M. Shubhakanta Singh


Python 3 – IDLE
(Integrated Development Environments)

Dr. M. Shubhakanta Singh


Python – IDLE
(Integrated Development Environments)

Dr. M. Shubhakanta Singh


Python – Shell

Dr. M. Shubhakanta Singh


Python – Shell as Calculator

Long data type is no more used


in Python 3.x

Dr. M. Shubhakanta Singh


ENTHOUGHT CANOPY

Dr. M. Shubhakanta Singh


ENTHOUGHT CANOPY - EDITOR

Run -> Ctrl + R


Restart Kernel -> Ctrl + .

Dr. M. Shubhakanta Singh


Canopy Command Prompt-Python

Dr. M. Shubhakanta Singh


One simple Python Program

• Interchanging of two numbers:


- programming logics
- basic idea of using comments (single &
double quotes)
- declaration of variables
- print statements(including comma)
- with two different methods

Dr. M. Shubhakanta Singh


Python – Keywords and Identifiers
Reserve Keywords:
and as assert break class
continue def del elif else
except exec False finally for
from global if import in
is lambda None not or
pass print raise return True
try while yield nonlocal with

Identifiers: >>> import keyword


x = 123 >>> print keyword.kwlist

assert = 123 Dr. M. Shubhakanta Singh


Rules for Identifiers
The following rules must be follow when we define an identifier.

 First character must be an alphabet or underscore.


 Must consist of only letters, digits or underscore
 Keywords can’t use as an identifier
 Must not contain whitespace.

Some examples of VALID identifiers are :


Value value avg_ht sum1
product
Some of the INVALID identifiers are:
1sum (distance) 3rd %per
avg val def lambda rs$

Dr. M. Shubhakanta Singh


Data Types
Data Type Attribute Example
Numeric Types
Integer Implemented with C longs 1234, 987243
Float Implemented with C doubles 2378.67543, 18922.8765
Long integer Size is limited with the system resources 7653897654L

Complex It has real and imaginary parts, which are 12 + 45.78 j


each of floating point numbers. 12 + 45.78 J

Sequence Types
String A sequence of characters. Immutable (not ‘This is a string’
changeable in - place). It can be “This is also a string”
represented by single quotes or double
quotes.
List Mutable (changeable) sequence of data [1, 2, 3]
types. List elements may be of same or [1.2, 4, ‘c’]
different data types. [4.5, 6.7, 7.8]
Tuple An immutable sequence of data types. It (1, 2, 3)
works just like a list. (1.2, 4, ‘c’)
(4.5, 6.7, 7.8)
Dictionary A list of items indexed by keys. It has a { 1: 3, 2 : 8, 3 :10}
value corresponding to its key. {‘a’ : 11, ‘b’ : 22}
Dr. M. Shubhakanta Singh {2 : ‘d’, 5 :’k’, 6 : ‘t’}
Data Types in Python 3.x

Dr. M. Shubhakanta Singh


Operators and Expressions

Python operators can be classified into a


number of categories. They include:
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators

Dr. M. Shubhakanta Singh


Arithmetic operators
Operator Meaning
* Multiplication
** Exponentiation
/ Division
// Pure integer division
% Modulo Division
+ Addition or unary plus
- Subtraction or unary minus
 Bitwise operator(XOR)
>>>6 % 4 >>> (-3) ** 2 >>> 10 // 4.0
2 9 2.0
>>> 3 ** 5 >>> 10 / 4
243 2 (Python 2.x)
2.5 (Python 3.x – By default)
>>> -3 ** 2 >>> 10 / 4.0
-9 2.5
Dr. M. Shubhakanta Singh
Arithmetic Operations
• In Python 2.x  Ordinary integers can’t be larger than 2147483647 (or smaller than -2147483648).
• But in Python 3.x, here is no limit
Integers can handle big numbers
• >>> 1987163987163981639186 * 198763981726391826
394976626432005567613000143784791693636
Mixed Mode Operations:
• >>> x = 12 + 34
>>> type (x) • >>> z = 12 + 34L
<type ‘int’>
>>>type(z)
• >>> y = 12 + 34.45 <type ‘long’> • >>> c = (12 + 34j) + 34L
>>> type(y) >>> type(c)
<type ‘float’> • >>> z1 = 12.45 + 34L <type ‘complex’>
>>>type(z1)
• >>> int (12.43 + 45)
57
<type ‘float’>

• >>>int(12.34)/int(4.67)
3

Dr. M. Shubhakanta Singh

You might also like