Why Python ?

When we already know languages like C, C++, Java etc...

Very important advantages (among many) :

  • Its faster to write a solution in Python!
  • Code is extremly readable
  • Its very easy to learn
  • Many utilities come with the language directly.

Don't Believe me ?

Lets write a small program

Hello World program

  •       #include <iostream.h>
          int main()
          {
            cout << "Hello World";
            return 0;
          }
  •       public class HelloWorld {
              public static void main(String[] args) {
                  System.out.println("Hello, World");
              }
          }
  •       print 'Hello World.'  # Are you serious ? Just one line ?

Lets run the program

  • Using Python Interpreter
    • $ python
      Python 2.7.2 (default, Oct 11 2012, 20:14:37)
      [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
      Type "help", "copyright", "credits" or "license" for more information.
      >>> print 'Hello World.'
      Hello World.
      >>>
  • Using Python script
    • $ cat hello.py
      print 'Hello World.'
      $ python hello.py
      Hello World.
                    

Now that you are partially convinced.....

Lets dig deep into Python

Numbers, and related operators

>>> 3 + 2
5
>>> 5 * 3
15
>>> 5 - 2
3
>>> 5 ** 4
625
>>> 5 / 9
0
>>> 5 / 9.0
0.5555555555555556
>>> 5 % 2
1
>>> type(4)
<type 'int'>
>>> type(5/9.0)
<type 'float'>

Assignments

  • Dynamic Typing
    • No explicit Type declarations are required.
    • Type checking is done at Run-Time
>>> students_count = 50
>>> total_groups = 10
>>> num_of_students_in_each_group = students_count / total_groups
>>> num_of_students_in_each_group
5
      
Useful Tip :

For God sakes, lets not have x = 5 or i = 10.

Define variable names with meaning I say!

Strings

  • String assignment
    >>> greeting = 'hello!'
    >>> print greeting
    hello!
          
  • Multi-line strings
    >>> text = '''the quick brown fox jumped on me (yes thats me, not the
    ... lazy cat) and ate my lunch. I dont know why! The Gods must be crazy I say!'''
    >>>
          
  • Concatentation
    >>> 'Ramesh! ' + 'Suresh! ' + 'Can you give me your Five-Star'
    'Ramesh! Suresh! Can you give me your Five-Star ?'
          

Printing Strings

  • >>> name = 'Ramesh'
    >>> print 'Good Morning %s' % name
    Good Morning Ramesh
          
  • >>> print 'Good Morning {0}'.format(name)
    Good Morning Ramesh
          

Conditional statements

  • >>> 10 > 20
    False
    >>> 20 > 4
    True
    >>> 10 / 20 > 2  # Don't confuse yourself and others. Use brackets I say!
    False
    >>> x = 10
    >>> 3 < x < 15
    True
          

If Conditions

  • >>> friend = 'Ramesh'
    >>> if friend == 'Ramesh':
    ...     print 'Play Games Together'
    ... elif friend == 'Dad':
    ...     print 'Give Coffee'
    ... else:
    ...     print 'Not invited'
    Play Games Together
          

Lists

A Data Structure to contain multiple items. Similar to an Array.

  • >>> shopping_items = ['Milk', 'Dosa Mix', 'Chicken', 'Soap']
    >>> greetings = [5, 4, 3, 2, 1, 'Happy New Year!']
    >>> type(greetings)
    <type 'list'>
    
  • >>> greetings.append(2014)  # Lists are mutable
    >>> help(list)  # Gives a detailed description of all operations on a list
  • >>> greetings[5]
    'Happy New Year!'
    >>> greetings[-1]
    2014
    >>> greetings[2:]
    [3, 2, 1, 'Happy New Year!', 2014]
    

Tuples

A Non-mutable Data Structure to contain multiple items.

  • >>> greetings = (5, 4, 3, 2, 1, 'Happy New Year!', 2014)
    
  • >>> type(greetings)
    <type 'tuple'>
    >>> help(greetings)  # or help(tuple) to know more about "tuple"
    

Functions

A piece of logic to be associated with a name

  • >>> def greet_me():
    ...     print 'Hello Students'
    ...
    >>> greet_me()
    Hello Students
              
  • >>> def square_me(number):
    ...     return number * number
    ...
    >>> square_me(10)
    100
              

Built-in Handy functions

  • len(sequence)
  • min(sequence)
  • max(sequence)
  • range(number)
  • map(handle, sequence)
  • reduce(handle, sequence)
  • type(object)
  • help(object)
  • dir(object)
  • Many more and many many more!

Methods

Similar to functions but actually work on objects

  • The object (i.e., instance of the class) is passed implicitly to the method
  • The method has access to all the data contained within the class
    • >>> class Student(object):
      ...     def __init__(self, name):
      ...         self.name = name
      ...     def print_name(self):
      ...         print self.name
      ...
      >>>
      
    • >>> stud = Student(name='Ramesh')
      >>> stud.print_name()
      Ramesh

For loop

Just to loop through a sequence of items to do something with them

  • There is no i=0, i++ business thankfully :D
  • >>> shopping_items = ['Milk', 'Dosa Mix', 'Chicken', 'Soap']
    >>> for item in shopping_items:
    ...     print 'I am buying %s' % item
    ...
    I am buying Milk
    I am buying Dosa Mix
    I am buying Chicken
    I am buying Soap

List comprehensions

An ultra simple/concise way to create lists

  • >>> shopping_items = [('Milk', 2), ('Dosa Mix', 1), ('Soap', 3)]
  • >>> [item[1] for item in shopping_items]  # Is that a single line for loop?
    [2, 1, 3]

String Operations

  • String can act as a Sequence
    • Access characters using indexes
    • You can iterate over the characters using a for loop
    • string.split()
      • >>> 'Husband Wife'.split()
        ['Husband', 'Wife']
    • separator.join(sequence)
      • >>> ' '.join(['Husband', 'Wife'])  # Together forever :D
        'Husband Wife'
    • string[::-1]
      • >>> 'Husband Wife'[::-1]  # Is that a string reverse ?
        'efiW dnabsuH'

Working with Files

  • Reading File Content
    • $ cat hello_world.py
      print 'Hello World'
      print 'How many times I have to wish the world "Hello" ? '
      print 'Atleast a million times'
    • >>> hello_file = open('hello_world.py')
      >>> for line in hello_file:
      ...     print line
      ...
      print 'Hello World'
      
      print 'How many times I have to wish the world "Hello" ? '
      
      print 'Atleast a million times brother!'
      
      >>>
      

Writing Content to Files

  • >>> hello_file = open('hello_world.py', 'w')
    >>> extra_lines = ['Why ? ', 'I am Gajini. ']
    >>> for line in extra_lines:
    ...     hello_file.write(line)
    ...
    >>> hello_file.close()  # This is good!
  • $ cat hello_world.py
    Why ? I am Gajini. 

Closing Files in a better way

  • Understanding with aka Context Manager
  • >>> with open('hello_world.py', 'a') as hello_file:
    ...      hello_file.write('Oye Gajini, Your camera is stolen. Ayyo!!!!!')
    ...
            
  • $ cat hello_world.py
    Why ? I am Gajini. Oye Gajini, Your camera is stolen. Ayyo!!!!!
            

Few important Modules

time, os, datetime

  • time module
    • >>> import time
      >>> time.time()  # An easy way to profile code blocks
      1376666540.631406
  • os module
    • >>> import os
      >>> os.environ
  • datetime module
    • >>> import datetime
      >>> datetime.date.today()
      datetime.date(2013, 8, 17)

Many more important Modules

  • sys
  • urllib, urllib2
  • csv
  • re
  • math
  • itertools
  • xml
  • pdb
  • hashlib
  • argparse
  • logging
  • unittest
  • json

dictionaries

Most powerful data-structure on the planet!

  • Similar to associative arrays in other languages
  • Nothing but an unordered set of key:value pairs
    • >>> student = {'name': 'Nanda', 'roll': 522, 'edu': 'Engineering'}
      >>> type(student)
      <type 'dict'>
    • >>> student.keys()
      ['edu', 'name', 'roll']
      >>> student.values()
      ['Engineering', 'Nanda', 522]
      >>> student.items()
      [('edu', 'Engineering'), ('name', 'Nanda'), ('roll', 522)]
      

Dict

Can Behave like a List too!

  • Like in a List, we can index elements by their keys
    • >>> student['name']
      'Nanda'
      >>> student['edu']
      'Engineering'
  • Using Keys to loop through the data
    • >>> 'name' in student
      True
      >>> for field in student:
      ...     print field, student[field]
      ...
      edu Engineering
      name Nanda
      roll 522

Resources for further reading

>>> Thank You!