- High level language
- Dynamically typed
- Interpreted language
- Simple and easy to understand the code
Let's start python interpreter by typing command python in terminal
[chandankumar@workstation workshop]$ python Python 2.7.8 (default, Nov 10 2014, 08:19:18) [GCC 4.9.2 20141101 (Red Hat 4.9.2-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>>
Let us print your name in python using print function
>>> print "Hey! My name is chandan kumar." Hey! My name is chandan kumar. >>>
Let us write a comment in python using #
>>> # This is a comment ... >>> # print "hello world" ... >>> # Anything written after pound sign will be ignored by python ... >>>
Let us define a varible, Every variable has a name which is referenced by a value.
Hey! remember you donot need to declare the type of a varibale
>>> a = 100 >>> a 100 >>> b = 12.0 >>> b 12.0 >>> c = "hello" >>> c 'hello'
The data type of a variable will be dynamically changed once we changed the value. We can check the type of a varible using type function.
>>> a 100 >>> type(a) <type 'int'> >>> a = 1.2 >>> type(a) <type 'float'> >>> a = "chandan" >>> type(a) <type 'str'> >>>
To understand more, we can check the memory address of a variable using id function
>>> a 'chandan' >>> id(a) 140235241212256 >>> a = 12 >>> id(a) 33206352 >>> a = 1.2 >>> id(a) 33277600 >>>
We can define multiple variable in a single line a.ka. multiple assignment in a single line
>>> first_number, second_number = 4, 5 >>> first_number 4 >>> second_number 5 >>>
Hey! have some fun in python
>>> a, b = 5, 100 >>> a, b = b, a >>> a 100 >>> b 5 >>>
Wooh! i have swapped two numbers in a single line
We can print many things in a single line using commas
>>> a = "my test class" >>> b = 12 >>> print a, b my test class 12 >>> print "%s %d" % (a, b) my test class 12
Let do some number crunching
>>> 10 + 2 12 >>> 10 -2 8 >>> 10 * 2 20 >>> 10 / 2 5 >>> 10.0 / 2 5.0 >>> 10 / 2.0 5.0 >>> 5 % 3 2 >>> 3 ** 2 9 >>> 3 ** 4 81 >>>
+, -, , /, %, * are arithmetic operator
operator + operand makes an expression
let us solve a bodmass problem.
>>> 10 * 2 - 3 / (3 -4) + 7 30 >>>
let us use more some operators
>>> 3 > 4 False >>> 3 >= 4 False >>> 5 < 3 False >>> 5 <= 5 True >>> 5 == 4 False >>> 'hello' == "Hello" False >>> 'hello' != "Hello" True
>, >=, <, <=, ==, != are relational operators.
let try some more operations
>>> a = 30 >>> a 30 >>> a += 10 >>> a 40 >>> a -= 15 >>> >>> a 25 >>> a *= 0 >>> >>> a 0 >>>
These are shorthand operators.
Let us try some logical operator
>>> 10 and 20 20 >>> 20 and 10 10 >>> 10 or 20 10 >>> 20 or 10 20 >>> -1 or 0 -1 >>> 0 and -1 0 >>> 0 or -1 -1 >>> -1 and 0 0
Whitespaces are very important in python, 1 space = identation
Good Practice : give one identation between operator and operand.
indentation at the begining of line will throw indentation error
>>> name = "ramesh" >>> a = 1 File "<stdin>", line 1 a = 1 ^ IndentationError: unexpected indent >>> a = 1 >>> a 1 >>>
PROBLEM 1
Let us write a program to convert Fahrenheit temprature to degree celsius
c = (f-32) * 5 / 9
we can check the conditions using if, else, elif
in python () is replaced by : and {} is replaced by identation
- Best practice : Never mix tabs with spaces
- set 1 tab = 4 spaces in your editor Always give proper identation while using conditional, loops , functions, classes
if-else
>>> # A program to check whether a number is even or odd: ... >>> a = 123 >>> >>> if a % 2 == 0: ... print "%d is even" % a ... else: ... print "%d is odd" % a ... 123 is odd >>>
let us try some nested if-else
>>> # A program to check whether a number is positive, negative or zero ... >>> a = -50 >>> if a == 0: ... print "%d is equal to ZERO." % a ... elif a > 0: ... print "%d is Positive" % a ... else: ... print "%d is Negative" % a ... -50 is Negative >>>
To make the code reusable, we use functions
>>> def add(): ... a, b = 2, 3 ... print a + b ... >>> add() 5 >>> >>> >>> # pass parameters to a function ... >>> def add(a, b): ... print a + b ... >>> add(2, 3) 5 >>> # the above functions does not return anything ... >>> a = add(2, 3) 5 >>> a >>> def add(a, b): ... return a + b ... >>> a = add(2, 3) >>> a 5 >>>
PROBLEM 2 Write a function which will tell whether a number is even or odd.
Python provides some inbuilt data structures
Like: List, tuples, dictionaries
data structure : a way to structure data in order use it and manipulate it.
List : a collection of items seperated by commas in between two square brakets.
items may be string, int or float.
>>> a = [1, "hello", 1.2 , "py101", "krace", "sayan", "food", 234] >>> a [1, 'hello', 1.2, 'py101', 'krace', 'sayan', 'food', 234] >>> >>> >>> type(a) <type 'list'> >>>
Each list has a items having index value starting from 0 to [length of list] -1
len function is used to find the length.
>>> a [1, 'hello', 1.2, 'py101', 'krace', 'sayan', 'food', 234] >>> len(a) 8
We can access the element of a list through its index number.
>>> a [1, 'hello', 1.2, 'py101', 'krace', 'sayan', 'food', 234] >>> # access first element of a ... >>> a[0] 1 >>> # access an element at index 4 ... >>> a[4] 'krace' >>> # access last element of a ... >>> a[-1] 234 >>> # retrive element from 2 to 5 ... >>> a[2:5] [1.2, 'py101', 'krace'] >>> >>> # retrive all element except 1 and last ... >>> a[1:-1] ['hello', 1.2, 'py101', 'krace', 'sayan', 'food'] >>> # retrive all elements except last one ... >>> a[0:-1] [1, 'hello', 1.2, 'py101', 'krace', 'sayan', 'food'] >>> a[1:5:2] ['hello', 'py101'] >>> # a[i:j:k] returns elements from i to j with step k ...
Let us try some more inbuilt function associated with list
>>> # append an element in the list --> it will add an element in the last in a list ... >>> a.append('sayan') >>> a [1, 'hello', 1.2, 'py101', 'krace', 'sayan', 'food', 234, 'sayan'] >>> # how many time an element repeated in a list ... >>> a.count('sayan') 2 >>> a.count(1.2) 1 >>> # find whether an item is present in list or not ... >>> 'krace' in a True >>> # find the index of a item in a list ... >>> a.index('krace') 4 >>> # insert a new item in a list at 4th position ... >>> a.insert(4, 'chandan') >>> a [1, 'hello', 1.2, 'py101', 'chandan', 'krace', 'sayan', 'food', 234, 'sayan'] >>> # remove an item from list ... >>> a.remove('sayan') >>> a [1, 'hello', 1.2, 'py101', 'chandan', 'krace', 'food', 234, 'sayan'] >>> # del an item from a list ... >>> del a[3] >>> a [1, 'hello', 1.2, 'chandan', 'krace', 'food', 234, 'sayan'] >>> # we can extend a list ... >>> b = [1, 2, "belgaum"] >>> a.extend(b) >>> a [1, 'hello', 1.2, 'chandan', 'krace', 'food', 234, 'sayan', 1, 2, 'belgaum'] >>> # let us reverse the list ... >>> a.reverse() >>> a ['belgaum', 2, 1, 'sayan', 234, 'food', 'krace', 'chandan', 1.2, 'hello', 1] >>> # let us sort the list ... >>> a.sort() >>> a [1, 1, 1.2, 2, 234, 'belgaum', 'chandan', 'food', 'hello', 'krace', 'sayan'] >>> # let us update the value at particular index ... >>> a[4] = 'Chandan Kumar' >>> a [1, 1, 1.2, 2, 'Chandan Kumar', 'belgaum', 'chandan', 'food', 'hello', 'krace', 'sayan'] >>>
With list we can manipulate data, they are mutable.
Suppose we need to retrive items in a way whose cannot be changed, they are immutable Here comes the concept of tuples. like retriving data from database whose position or order are fixed.
Tuples - a collection of comma seperated values with closed brackets
Let us start playing with tuples
>>> # let us create a tuple ... >>> z = ('chandan', '24', 5.6, 'pune', 'speaker') >>> type(z) <type 'tuple'> >>> >>> # let us find length ... >>> len(z) 5 >>> # we can retrive the element just like list ... >>> z[3] 'pune' >>> c = (1, 2, 1, "hello", "test") >>> # let us count repated element ... >>> c.count(1) 2 >>> c.count("hello") 1 >>> # let find index of hello ... >>> c.index("hello") 3 >>> >>> # let us manipulate with tuples ... >>> c[3] = 4 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> # let us try deleting an item ... >>> del c[2] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion >>> c (1, 2, 1, 'hello', 'test') >>>
Next data structure is dictionary
Dictionary: an english word with so many meaning. just like that dictionary has unique keys and respective values. dict = {'key': value}
values may be a list, tuple, string , int or float.
Let us create a dictionary and start playing with it.
>>> # let us create a dictionary ... >>> t = {'name': 'chandan', 'age': 24, 'subject': ['os', 'database', 'python']} >>> t {'age': 24, 'name': 'chandan', 'subject': ['os', 'database', 'python']} >>> type(t) <type 'dict'> >>> >>> # retrive an item using from dict using key ... >>> t['name'] 'chandan' >>> # update the value ... >>> t['name'] = 'sayan' >>> t {'age': 24, 'name': 'sayan', 'subject': ['os', 'database', 'python']} >>> >>> # view all keys of a dict ... >>> t.keys() ['age', 'name', 'subject'] >>> # view all values ... >>> t.values() [24, 'sayan', ['os', 'database', 'python']] >>> # update the dict ... >>> t.update({'hobby': 'cricket'}) >>> t {'hobby': 'cricket', 'age': 24, 'name': 'sayan', 'subject': ['os', 'database', 'python']} >>> >>> # delete an element from dic ... >>> del t['age'] >>> t {'hobby': 'cricket', 'name': 'sayan', 'subject': ['os', 'database', 'python']} >>>
Let us learn about strings
We can represent strings using single, double or triple quotes Let's try out
>>> >>> # string with single quotes ... >>> 'hello world' 'hello world' >>> "Hello world" 'Hello world' >>> >>> # long string will be displayed using triple quotes ... >>> a = """Hey! i am writing a long statement, it uses triple quotes to show it,""" >>> a 'Hey! i am writing a long statement, it uses triple quotes to show it,' >>> # let us cancate two strings ... >>> b = "i am joining you" >>> a + b 'Hey! i am writing a long statement, it uses triple quotes to show it,i am joining you' >>> >>> # let us try some inbuilt functions associated with strings ... >>> a = "chandan kumar" >>> a.title() 'Chandan Kumar' >>> a.upper() 'CHANDAN KUMAR' >>> b = a.upper() >>> b 'CHANDAN KUMAR' >>> b.lower() 'chandan kumar' >>> a.swapcase() 'CHANDAN KUMAR' >>> a.capitalize() 'Chandan kumar' >>> d = "123" >>> d.isdigit() True >>> a.title() 'Chandan Kumar' >>> a.istitle() False >>> a.islower() True >>> a.isupper() False >>> a 'chandan kumar' >>> a.find('h') 1 >>> a.find('a') 2 >>> a.replace('a', 'A') 'chAndAn kumAr' >>> # let try split and join ... >>> stat = "Hey ! now i know python" >>> stat.split(" ") ['Hey', '!', 'now', 'i', 'know', 'python'] >>> data = stat.split(" ") >>> data ['Hey', '!', 'now', 'i', 'know', 'python'] >>> '_'.join(data) 'Hey_!_now_i_know_python' >>> a = "www.foss.in" >>> a.strip('.in') 'www.foss' >>> a = "kumar chandan" >>> "kumar" in a True >>> a.startswith('c') False >>> a.endswith('an') True >>>
- for loop
- it iterates over a sequence [list, dict, strings, tuples]
- for <interating value> in squence:
- do something
>>> # for loop in list ... >>> a = ["hello", "date", 1, 2, 4] >>> a ['hello', 'date', 1, 2, 4] >>> for i in a: ... print i ... hello date 1 2 4 >>> for i in a: ... print i, ... hello date 1 2 4 >>> >>> # Range function it will return a list of integers from 0 to n-1 ... >>> range(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> # let us print 1 to 10 in a single line ... >>> for i in range(1, 11): ... print i, ... 1 2 3 4 5 6 7 8 9 10 >>> d = {1:'name', 2:'data', 3:'faces'} >>> d {1: 'name', 2: 'data', 3: 'faces'} >>> for i, j in d.iteritems(): ... print i, j ... 1 name 2 data 3 faces >>> a = "chandankumar" >>> for i in a: ... print i ... c h a n d a n k u m a r >>> >>> # list comprension ... >>> [i ** 2 for i in range(10, 21)] [100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
To read or write a file we need to open it. We can open a file in three modes: r - to read a file (default mode) w - overwrites the content, if file does not exists, it create it. a - append mode
>>> # let us create a file irc.txt ... >>> fobj = open('irc.txt', 'w') >>> fobj.write("Sayan\n") >>> fobj.write("Chandan\n") >>> fobj.write("Krace\n") >>> fobj.write("Vijay\n") >>> fobj.close() >>> >>> # let us again open that file and read the content ... >>> fobj = open('irc.txt', 'r') >>> fobj.read() 'Sayan\nChandan\nKrace\nVijay\n' >>> fobj.read() '' >>> fobj.close() >>> fobj = open('irc.txt', 'r') >>> data = fobj.read() >>> data 'Sayan\nChandan\nKrace\nVijay\n' >>> data.split('\n') ['Sayan', 'Chandan', 'Krace', 'Vijay', ''] >>> # once operation is done, we need to close the file. ... >>> fobj.close() >>>
python libraries containing functions and method to use a module we need to import it.
Let us try some module.
>>> # let us use math module ... >>> import math >>> math.sqrt(123) 11.090536506409418 >>> math.pi 3.141592653589793 >>> >>> # we use os module to interact with system ... >>> import os >>> # let us find current directory name ... >>> os.getcwd() '/home/chandankumar/Downloads/workshop' >>> current_dir = os.getcwd() >>> # let us list files of this directory ... >>> os.listdir(current_dir) ['py101.pdf', 'topics.txt', 'irc.txt', 'py101.rst'] >>> >>> # find the size of a datatype ... >>> a = "hello" >>> import sys >>> sys.getsizeof(a) 42 >>>
When we write code we always encountered with errors and exceptions.
try, except, finally keywords is used to handle exceptions.
Let us checkout
>>> a = 10 >>> b = "hello" >>> # let us handle this exception ... >>> try: ... a + b ... except TypeError: ... print "Something went wrong" ... Something went wrong >>> >>> # let us try finally ... >>> try: ... a + b ... except TypeError: ... print "Something went wrong" ... finally: ... print type(a), type(b) ... Something went wrong <type 'int'> <type 'str'> >>> # we use finally keyword for cleanup
It is a blueprint of an object here comes the concept of object oriented programming. in python everything is object
>>> # let us create a class ... >>> class foo(): ... print "hello" ... hello >>> # let us create a class ... >>> class foo(): ... a = 10 ... b = 20 ... >>> # let us that class ... >>> p = foo() >>> p <__main__.foo instance at 0x7f8b02a98950> >>> # it is an object of that class ... >>> # we can check methods available with in class using dir function ... >>> dir(p) ['__doc__', '__module__', 'a', 'b'] >>> >>> class calculator(): ... def __init__(self, a, b): ... self.a = a ... self.b = b ... def add(self): ... return self.a + self.b ... def sub(self): ... return self.a - self.b ... >>> p = calculator() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __init__() takes exactly 3 arguments (1 given) >>> # it requires arguments. ... >>> p = calculator(2, 3) >>> dir(p) ['__doc__', '__init__', '__module__', 'a', 'add', 'b', 'sub'] >>> p.add() 5 >>> p.sub() -1 >>>
Book to read: http://pymbook.readthedocs.org/en/latest/index.html
Problems to Practice : http://www.cse.msu.edu/~cse231/PracticeOfComputingUsingPython/