Basics of Python
by Kaustubh Vaghmare
(IUCAA, Pune)
E-mail: kaustubh[at]iucaa[dot]ernet[dot]in
http://127.0.0.1:8001/BasicPython1.slides.html
1 of 29
Thursday 16 October 2014 03:50 PM
Topics to be Covered
(Not in any specific order.)
Basic I/O in Python
Data Types in Python
Programming Philosophy
Under The Hood
Conditionals
Loops
Basics of Objects and Methods
etc.
http://127.0.0.1:8001/BasicPython1.slides.html
2 of 29
Thursday 16 October 2014 03:50 PM
Assumptions!!!
You are not new to programming.
(Will freely throw jargon around!)
You are new to Python!
http://127.0.0.1:8001/BasicPython1.slides.html
3 of 29
Thursday 16 October 2014 03:50 PM
Python 2 or 3?
Python's key strength lies in its libraries.
These are not ready / optimized for Python 3 yet.
But they soon(!) will be! (Almost are!)
Keep track of progress & Migrate!
http://ptgmedia.pearsoncmg.com/imprint_downloads/informit
/promotions/python/python2python3.pdf
http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master
/tutorials/key_differences_between_python_2_and_3.ipynb
https://pypi.python.org/pypi (select Python 3 Packages on the left)
http://127.0.0.1:8001/BasicPython1.slides.html
4 of 29
Thursday 16 October 2014 03:50 PM
Our First Program!
http://127.0.0.1:8001/BasicPython1.slides.html
5 of 29
Thursday 16 October 2014 03:50 PM
In [1]:
What can we learn from this simple program?
a = 3
b = 5
c = a+b
d = a-b
q, r = a/b, a%
b # Yes, this is allowed!
# Now, let's print!
print "Hello World!"
# We just had to do this, did we not?
print "Sum, Difference = ", c, d
print "Quotient and Remainder = ", q, r
Hello World!
Sum, Difference = 8 -2
Quotient and Remainder = 0 3
http://127.0.0.1:8001/BasicPython1.slides.html
6 of 29
Thursday 16 October 2014 03:50 PM
Dynamic Typing
We don't declare variables and types in advance. (dynamic typing)
Variables created when first assigned values.
Variables don't exist if not assigned. (strong typing)
Commenting
Everything after # is a comment and is ignored. Comment freely
"print" statement
Replaced by a print() function in Python 3.
Tuple unpacking assignments
More complicated forms introduced in Python 3.
a,b = 5,6
http://127.0.0.1:8001/BasicPython1.slides.html
7 of 29
Thursday 16 October 2014 03:50 PM
Other Things
Behavior of / and % operators with integer types. (/ changes in
Python 3)
No termination symbols at end of Python statements.
Exception to the above...
a = 3; b = 5
http://127.0.0.1:8001/BasicPython1.slides.html
8 of 29
Thursday 16 October 2014 03:50 PM
Under the Hood
No explicit compiling/linking step. Just run... $ python First.py
Internally, program translated into bytecode (.pyc files)
The "translation + execution" happens line-by-line
Implications of "line-by-line" style
N lines will be executed before error on N+1th line haults program!
An interactive shell.
http://127.0.0.1:8001/BasicPython1.slides.html
9 of 29
Thursday 16 October 2014 03:50 PM
[ Interactive Shell Demo ]
http://127.0.0.1:8001/BasicPython1.slides.html
10 of 29
Thursday 16 October 2014 03:50 PM
[ Introduction to iPython ]
http://127.0.0.1:8001/BasicPython1.slides.html
11 of 29
Thursday 16 October 2014 03:50 PM
The First Tour of the Data Types
Numbers - Integers
Numbers - Floats
(Exploration of math module)
Strings
(Methods of Declaring Strings)
(Concept of Sequences)
(Concept of Slicing)
(Concept of Mutability)
(Introduction of Object.Method concepts)
http://127.0.0.1:8001/BasicPython1.slides.html
12 of 29
Thursday 16 October 2014 03:50 PM
Integers
In [2]:
In [3]:
In [4]:
8 ** 2
# Exponentiation
Out[2]:
64
23**100
# Auto-upgrade to "LONG INT" Notice the L!
Out[3]:
1488619150636303939379155658655975423198711965380136868657698
8209222433278539331352152390143277346804233476592179447310859
520222529876001L
5 / 2, 5%
2 # Quotient-Remainder Revisited.
Out[4]:
(2, 1)
http://127.0.0.1:8001/BasicPython1.slides.html
13 of 29
Thursday 16 October 2014 03:50 PM
Floats
In [5]:
In [6]:
In [7]:
In [47]:
5.0 * 2, 5*2.0
# Values upgraded to "higher data type".
Out[5]:
(10.0, 10.0)
5**0.5
# Yes, it works! Square-root.
Out[6]:
2.23606797749979
5 / 4.0
# No longer a quotient.
Out[7]:
1.25
5 % 4.0, 5 % 4.1
# Remainder, yes!!!
Out[47]:
(1.0, 0.9000000000000004)
http://127.0.0.1:8001/BasicPython1.slides.html
14 of 29
Thursday 16 October 2014 03:50 PM
Math Module
A module can be thought of as a collection of related functions.
To use a module,
import ModuleName
To use a function inside a module, simply say
ModuleName.Function(inputs)
Let's see the math module in action!
http://127.0.0.1:8001/BasicPython1.slides.html
15 of 29
Thursday 16 October 2014 03:50 PM
In [9]:
In [10]:
There are about 42 functions inside Math library! So, where can one get a
quick reference of what these functions are, what they do and how to use
them!?!?
import math
x = 45*math.pi/180.0
math.sin(x)
Out[9]:
0.7071067811865475
math.sin( math.radians(45) )
# nested functions
Out[10]:
0.7071067811865475
http://127.0.0.1:8001/BasicPython1.slides.html
16 of 29
Thursday 16 October 2014 03:50 PM
In [11]:
In [12]:
print dir(math)
# Prints all functions associated with Math mo
dule.
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin
', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'co
s', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'f
abs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma',
'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10'
, 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sq
rt', 'tan', 'tanh', 'trunc']
help(math.hypot)
Help on built-in function hypot in module math:
hypot(...)
hypot(x, y)
Return the Euclidean distance, sqrt(x*x + y*y).
http://127.0.0.1:8001/BasicPython1.slides.html
17 of 29
Thursday 16 October 2014 03:50 PM
Strings
There are three methods of defining strings.
In [13]:
In [14]:
In [15]:
In [16]:
a = "John's Computer"
# notice the '
b = 'John said, "This is my computer."'
# notice the "
a_alt = 'John
\'s Computer'
# now you need the escape sequence
\
b_alt = "John said,
\"This is my computer.
\""
# again escape s
equence.
http://127.0.0.1:8001/BasicPython1.slides.html
18 of 29
Thursday 16 October 2014 03:50 PM
In [17]:
In [18]:
Can be used to dynamically build scripts, both Python-based and
other "languages".
Used for documenting functions/modules. (To come later!)
long_string = """Hello World!
I once said to people, "Learn Python!"
And then they said, "Organize a workshop!" """
long_string_traditional = 'Hello World!
\n\nI once said to peo
ple, "Learn Python!"
\
\n\nAnd then they said, "Organize a workshop!" '
http://127.0.0.1:8001/BasicPython1.slides.html
19 of 29
Thursday 16 October 2014 03:50 PM
String Arithmetic
In [19]:
In [20]:
In [21]:
In [22]:
s1 = "Hello" ; s2 = "World!"
string_sum = s1 + s2
print string_sum
HelloWorld!
string_product = s1*3
print string_product
HelloHelloHello
print s1*3+s2
HelloHelloHelloWorld!
http://127.0.0.1:8001/BasicPython1.slides.html
20 of 29
Thursday 16 October 2014 03:50 PM
String is a sequence!
In [23]:
In [24]:
In [25]:
In [26]:
a = "Python rocks!"
a[0], a[1], a[2]
# Positions begin from 0 onwards.
Out[24]:
('P', 'y', 't')
a[-1], a[-2], a[-3]
# Negative indices - count backwards!
Out[25]:
('!', 's', 'k')
len(a)
# Measures length of both sequence/unordered collection
s!
Out[26]:
13
http://127.0.0.1:8001/BasicPython1.slides.html
21 of 29
Thursday 16 October 2014 03:50 PM
Sequences can be sliced!
In [27]:
In [28]:
In [29]:
In [30]:
a[2:6]
# elements with indices 2,3,4,5 but not 6
Out[27]:
'thon'
a[8:-2]
# indices 8,9 ... upto 2nd last but not including it.
Out[28]:
'ock'
a[:5]
# Missing first index, 0 assumed.
Out[29]:
'Pytho'
a[5:]
# Missing last index, len(a) assumed.
Out[30]:
'n rocks!'
http://127.0.0.1:8001/BasicPython1.slides.html
22 of 29
Thursday 16 October 2014 03:50 PM
Crazier Slicing
In [31]:
In [32]:
In [33]:
In [34]:
a[1:6:2],a[1],a[3],a[5]
# Indices 1, 3, 5
Out[31]:
('yhn', 'y', 'h', 'n')
a[::2]
# beginning to end
Out[32]:
'Pto ok!'
a[::-1]
# Reverse slicing!
Out[33]:
'!skcor nohtyP'
a[1:6:-1]
# In a[i:j:-1], changes meaning of i and j
Out[34]:
''
http://127.0.0.1:8001/BasicPython1.slides.html
23 of 29
Thursday 16 October 2014 03:50 PM
Objects and Methods - A Crude
Introduction
An object can be thought of a construct in the memory.
It has a well defined behavior with respect to other objects. (2*3 is allowed,
"a"*"b" is not!)
The properties of the object, the operations that can be performed all are
pre-defined.
A method is a function bound to an object that can perform specific
operations that the object supports.
OK, let's see some string methods in action!
ObjectName.MethodName(arguments)
http://127.0.0.1:8001/BasicPython1.slides.html
24 of 29
Thursday 16 October 2014 03:50 PM
String Methods
In [35]:
In [36]:
In [37]:
In [38]:
a = " I am a string, I am an object, I am immutable! "
a.title()
Out[36]:
' I Am A String, I Am An Object, I Am Immutable! '
a.split(",")
Out[37]:
[' I am a string', ' I am an object', ' I am immutable! '
]
a.strip()
# Remove trailing and leading whitespaces.
Out[38]:
'I am a string, I am an object, I am immutable!'
http://127.0.0.1:8001/BasicPython1.slides.html
25 of 29
Thursday 16 October 2014 03:50 PM
Strings are Immutable!
In [39]:
In [40]:
In [41]:
print a
# Check the value!
I am a string, I am an object, I am immutable!
a.title()
# Transform string to title case ... really?
Out[40]:
' I Am A String, I Am An Object, I Am Immutable! '
print a
# Nothing changed! Strings are immutabe.
I am a string, I am an object, I am immutable!
http://127.0.0.1:8001/BasicPython1.slides.html
26 of 29
Thursday 16 October 2014 03:50 PM
In [42]:
In [43]:
In [44]:
b = a.title()
# String methods return strings instead.
print b
I Am A String, I Am An Object, I Am Immutable!
a[3] = "x"
# Immutability implies no in-place changes.
-------------------------------------------------------------
--------------
TypeError
Traceback (most rec
ent call last)
<ipython-input-44-b0d08958dc31> in <module>()
----> 1 a[3] = "x" # Immutability implies no in-place changes
.
TypeError: 'str' object does not support item assignment
http://127.0.0.1:8001/BasicPython1.slides.html
27 of 29
Thursday 16 October 2014 03:50 PM
Getting Help
In [45]:
print dir(a)
# a is a string object.
['__add__', '__class__', '__contains__', '__delattr__', '__do
c__', '__eq__', '__format__', '__ge__', '__getattribute__', '
__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__
hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__'
, '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex_
_', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__siz
eof__', '__str__', '__subclasshook__', '_formatter_field_name
_split', '_formatter_parser', 'capitalize', 'center', 'count'
, 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'form
at', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'is
space', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstr
ip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpa
rtition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startsw
ith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zf
ill']
http://127.0.0.1:8001/BasicPython1.slides.html
28 of 29
Thursday 16 October 2014 03:50 PM
In [46]:
help(a.find)
Help on built-in function find:
find(...)
S.find(sub [,start [,end]]) -> int
Return the lowest index in S where substring sub is found
,
such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notat
ion.
Return -1 on failure.
http://127.0.0.1:8001/BasicPython1.slides.html
29 of 29
Thursday 16 October 2014 03:50 PM