Basic Python 1
Basic Python 1
html
Basics of Python
by Kaustubh Vaghmare
(IUCAA, Pune)
E-mail: kaustubh[at]iucaa[dot]ernet[dot]in
Topics to be Covered
(Not in any specific order.)
Assumptions!!!
You are not new to programming.
(Will freely throw jargon around!)
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!)
http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master
/tutorials/key_differences_between_python_2_and_3.ipynb
In [1]: a = 3
b = 5
c = a+b
d = a-b
q, r = a/b, a%b # Yes, this is allowed!
Hello World!
Sum, Difference = 8 -2
Quotient and Remainder = 0 3
Dynamic Typing
Commenting
Everything after # is a comment and is ignored. Comment freely
"print" statement
Replaced by a print() function in Python 3.
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
[ Introduction to iPython ]
Strings
(Concept of Sequences)
(Concept of Slicing)
(Concept of Mutability)
Integers
In [2]: 8 ** 2 # Exponentiation
Out[2]: 64
Out[3]: 1488619150636303939379155658655975423198711965380136868657698
8209222433278539331352152390143277346804233476592179447310859
520222529876001L
Out[4]: (2, 1)
Floats
Out[6]: 2.23606797749979
Out[7]: 1.25
Math Module
import ModuleName
To use a function inside a module, simply say
ModuleName.Function(inputs)
Out[9]: 0.7071067811865475
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!?!?
In [12]: help(math.hypot)
hypot(...)
hypot(x, y)
Strings
There are three methods of defining strings.
In [15]: a_alt = 'John\'s Computer' # now you need the escape sequence
\
String Arithmetic
In [20]: string_sum = s1 + s2
print string_sum
HelloWorld!
HelloHelloHello
HelloHelloHelloWorld!
String is a sequence!
Out[26]: 13
Out[27]: 'thon'
In [28]: a[8:-2] # indices 8,9 ... upto 2nd last but not including it.
Out[28]: 'ock'
Out[29]: 'Pytho'
Crazier Slicing
Out[34]: ''
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.
ObjectName.MethodName(arguments)
String Methods
In [36]: a.title()
In [37]: a.split(",")
In [43]: print b
-------------------------------------------------------------
--------------
TypeError Traceback (most rec
ent call last)
<ipython-input-44-b0d08958dc31> in <module>()
----> 1 a[3] = "x" # Immutability implies no in-place changes
.
Getting Help
In [46]: help(a.find)
find(...)
S.find(sub [,start [,end]]) -> int
Return -1 on failure.