Lect2 Slides
Lect2 Slides
Lect2 Slides
b = 5
c = a+b
d = a-b
Hello World!
Sum, Difference = 7 -3
Dynamic Typing
We do not declare variables and types in advance. (dynamic typing)
Variables created when first assigned values.
Variables do not exist if not assigned. (strong typing)
Commenting
Everything after # is a comment and is ignored. Comment freely. A comment can be on
its own line or following a line of code.
"print" statement
Used to print output of any kind. We will use this built-in function of Python often.
a = 3; b = 5
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
Strings
Concept of Sequences
Concept of Slicing
Concept of Mutability
Out[5]: 64
Out[6]: 221598697564115095916538315188172875314354600282592890206517191909967025172536
308830343071583454849289814240677195547664161196197773103139821259127019202606
635932853150774379161903661721108884741902313128449334671098765711668174784729
026178087482963822180304753020435752001
Out[7]: (2.5, 1)
Out[9]: 2.23606797749979
Out[10]: 1.25
To use a module,
import ModuleName
ModuleName.Function(inputs)
x = 60*math.pi/180.0
math.sin(x)
Out[12]: 0.8660254037844386
Out[13]: 0.8660254037844386
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 [14]: print (dir(math)) # Prints all functions associated with Math module.
hypot(...)
5.0
Strings
There are three methods of defining strings.
In [18]: a_alt = 'John\'s Computer' # now you need the escape sequence \
In [21]: long_string_traditional = 'Hello World! \n\nI once said to people, "Learn Pytho
n!" \
In [23]: string_sum = s1 + s2
print (string_sum)
HelloWorld!
print (string_product)
HelloHelloHello
HelloHelloHelloWorld!
String is a sequence!
In [26]: a = "Python rocks!"
Out[29]: 13
Sequences can be sliced!
In [30]: a[2:6] # elements with indices 2,3,4,5 but not 6
Out[30]: 'thon'
In [31]: a[8:-2] # indices 8,9 ... upto 2nd last but not including it.
Out[31]: 'ock'
Out[32]: 'Pytho'
Out[37]: ''
Objects and Methods - An oversimplified
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)
In [39]: a.title()
In [40]: a.split(",")
---------------------------------------------------------------------------
<ipython-input-47-1c6b97054996> in <module>
In [49]: help(a.find)
Return -1 on failure.