http://127.0.0.1:8001/BasicPython1.slides.
html
Basics of Python
by Kaustubh Vaghmare
(IUCAA, Pune)
E-mail: kaustubh[at]iucaa[dot]ernet[dot]in
1 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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.
2 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Assumptions!!!
You are not new to programming.
(Will freely throw jargon around!)
You are new to Python!
3 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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)
4 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Our First Program!
5 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
In [1]: 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
What can we learn from this simple program?
6 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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
a,b = 5,6
More complicated forms introduced in Python 3.
7 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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
8 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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.
9 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
[ Interactive Shell Demo ]
10 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
[ Introduction to iPython ]
11 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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)
12 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Integers
In [2]: 8 ** 2 # Exponentiation
Out[2]: 64
In [3]: 23**100 # Auto-upgrade to "LONG INT" Notice the L!
Out[3]: 1488619150636303939379155658655975423198711965380136868657698
8209222433278539331352152390143277346804233476592179447310859
520222529876001L
In [4]: 5 / 2, 5%2 # Quotient-Remainder Revisited.
Out[4]: (2, 1)
13 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Floats
In [5]: 5.0 * 2, 5*2.0 # Values upgraded to "higher data type".
Out[5]: (10.0, 10.0)
In [6]: 5**0.5 # Yes, it works! Square-root.
Out[6]: 2.23606797749979
In [7]: 5 / 4.0 # No longer a quotient.
Out[7]: 1.25
In [47]: 5 % 4.0, 5 % 4.1 # Remainder, yes!!!
Out[47]: (1.0, 0.9000000000000004)
14 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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!
15 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
In [9]: import math
x = 45*math.pi/180.0
math.sin(x)
Out[9]: 0.7071067811865475
In [10]: math.sin( math.radians(45) ) # nested functions
Out[10]: 0.7071067811865475
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!?!?
16 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
In [11]: 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']
In [12]: 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).
17 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Strings
There are three methods of defining strings.
In [13]: a = "John's Computer" # notice the '
In [14]: b = 'John said, "This is my computer."' # notice the "
In [15]: a_alt = 'John\'s Computer' # now you need the escape sequence
\
In [16]: b_alt = "John said, \"This is my computer.\"" # again escape s
equence.
18 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
In [17]: long_string = """Hello World!
I once said to people, "Learn Python!"
And then they said, "Organize a workshop!" """
In [18]: long_string_traditional = 'Hello World! \n\nI once said to peo
ple, "Learn Python!" \
\n\nAnd then they said, "Organize a workshop!" '
Can be used to dynamically build scripts, both Python-based and
other "languages".
Used for documenting functions/modules. (To come later!)
19 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
String Arithmetic
In [19]: s1 = "Hello" ; s2 = "World!"
In [20]: string_sum = s1 + s2
print string_sum
HelloWorld!
In [21]: string_product = s1*3
print string_product
HelloHelloHello
In [22]: print s1*3+s2
HelloHelloHelloWorld!
20 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
String is a sequence!
In [23]: a = "Python rocks!"
In [24]: a[0], a[1], a[2] # Positions begin from 0 onwards.
Out[24]: ('P', 'y', 't')
In [25]: a[-1], a[-2], a[-3] # Negative indices - count backwards!
Out[25]: ('!', 's', 'k')
In [26]: len(a) # Measures length of both sequence/unordered collection
s!
Out[26]: 13
21 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Sequences can be sliced!
In [27]: a[2:6] # elements with indices 2,3,4,5 but not 6
Out[27]: 'thon'
In [28]: a[8:-2] # indices 8,9 ... upto 2nd last but not including it.
Out[28]: 'ock'
In [29]: a[:5] # Missing first index, 0 assumed.
Out[29]: 'Pytho'
In [30]: a[5:] # Missing last index, len(a) assumed.
Out[30]: 'n rocks!'
22 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Crazier Slicing
In [31]: a[1:6:2],a[1],a[3],a[5] # Indices 1, 3, 5
Out[31]: ('yhn', 'y', 'h', 'n')
In [32]: a[::2] # beginning to end
Out[32]: 'Pto ok!'
In [33]: a[::-1] # Reverse slicing!
Out[33]: '!skcor nohtyP'
In [34]: a[1:6:-1] # In a[i:j:-1], changes meaning of i and j
Out[34]: ''
23 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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.
ObjectName.MethodName(arguments)
OK, let's see some string methods in action!
24 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
String Methods
In [35]: a = " I am a string, I am an object, I am immutable! "
In [36]: a.title()
Out[36]: ' I Am A String, I Am An Object, I Am Immutable! '
In [37]: a.split(",")
Out[37]: [' I am a string', ' I am an object', ' I am immutable! '
]
In [38]: a.strip() # Remove trailing and leading whitespaces.
Out[38]: 'I am a string, I am an object, I am immutable!'
25 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
Strings are Immutable!
In [39]: print a # Check the value!
I am a string, I am an object, I am immutable!
In [40]: a.title() # Transform string to title case ... really?
Out[40]: ' I Am A String, I Am An Object, I Am Immutable! '
In [41]: print a # Nothing changed! Strings are immutabe.
I am a string, I am an object, I am immutable!
26 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
In [42]: b = a.title() # String methods return strings instead.
In [43]: print b
I Am A String, I Am An Object, I Am Immutable!
In [44]: 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
27 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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']
28 of 29 Thursday 16 October 2014 03:50 PM
http://127.0.0.1:8001/BasicPython1.slides.html
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.
29 of 29 Thursday 16 October 2014 03:50 PM