Lesson1 python an introduction

99
Python – An Introduction Arulalan.T [email protected] Centre for Atmospheric Sciences Indian Institute of Technology Delhi

description

Document under Creative Common

Transcript of Lesson1 python an introduction

Page 1: Lesson1 python an introduction

Python – An [email protected] for Atmospheric Sciences Indian Institute of Technology Delhi

Page 2: Lesson1 python an introduction

Python is a Programming Language

Page 3: Lesson1 python an introduction

There are so many 

Programming Languages.

Why Python?

Page 4: Lesson1 python an introduction
Page 5: Lesson1 python an introduction
Page 6: Lesson1 python an introduction

Python is simple and beautiful

Page 7: Lesson1 python an introduction

Python is Easy to Learn

Page 8: Lesson1 python an introduction

Python is Free Open Source Software

Page 9: Lesson1 python an introduction

Can Do

● Text Handling● System Administration● GUI programming● Web Applications● Database Apps● Scientific Applications

● Games● NLP

● ...

Page 10: Lesson1 python an introduction

  H i s t o r y

Page 11: Lesson1 python an introduction

Guido van Rossum   Father of Python            1991

Page 12: Lesson1 python an introduction

                 Perl  Java  Python   Ruby    PHP            1987       1991           1993      1995

Page 13: Lesson1 python an introduction

What is

Python?

Page 14: Lesson1 python an introduction

Python is...

A dynamic,open source programming language with a focus onsimplicity and productivity. It has anelegant syntax that is natural to

read and easy to write.

Page 15: Lesson1 python an introduction

Quick and Easy

Intrepreted Scripting Language

Variable declarations are unnecessary

Variables are not typed

Syntax is simple and consistent

Memory management is automatic

Page 16: Lesson1 python an introduction

     Object Oriented Programming            Classes

         Methods

         Inheritance

         Modules

         etc.,  

Page 17: Lesson1 python an introduction

    Examples!

Page 18: Lesson1 python an introduction
Page 19: Lesson1 python an introduction

print    “Hello World”

Page 20: Lesson1 python an introduction

         No Semicolons !

Page 21: Lesson1 python an introduction

         Indentation

Page 22: Lesson1 python an introduction

You have to follow the Indentation Correctly.

Otherwise,

Python will beat you !

Page 23: Lesson1 python an introduction
Page 24: Lesson1 python an introduction

 Discipline 

   Makes  

    Good 

Page 25: Lesson1 python an introduction

          Variables

  colored_index_cards

Page 26: Lesson1 python an introduction

No Need to Declare Variable Types !

      Python Knows Everything !

Page 27: Lesson1 python an introduction

value = 10

print value

value = 100.50

print value

value = “This is String”

print      value * 3

Page 28: Lesson1 python an introduction

Input

Page 29: Lesson1 python an introduction

name = raw_input(“What is Your name?”)

print "Hello" , name , "Welcome"

Page 30: Lesson1 python an introduction

Flow

Page 31: Lesson1 python an introduction

if score >= 5000 : print “You win!”elif score <= 0 : print “Game over.”else: print “Current score:”,score

print “Done\n”

Page 32: Lesson1 python an introduction

  Loop

Page 33: Lesson1 python an introduction

for  i   in   range(1, 5):        print    ielse:        print    'The for loop is over'

Page 34: Lesson1 python an introduction

number = 23

while True :        guess = int(raw_input('Enter an integer : '))        if  guess == number :                print 'Congratulations, you guessed it.'                running = False         elif  guess < number :                print 'No, it is a little higher than that.'        else:                print 'No, it is a little lower than that.'

print  'Done'

Page 35: Lesson1 python an introduction

Array

Page 36: Lesson1 python an introduction

                List = Array

numbers = [ "zero", "one", "two", "three", "FOUR" ]  

Page 37: Lesson1 python an introduction

                List = Array

numbers = [ "zero", "one", "two", "three", "FOUR" ]

numbers[0]>>> zero 

numbers[4]                                 numbers[­1]>>> FOUR                                  >>> FOUR                         numbers[­2]

          >>> three

Page 38: Lesson1 python an introduction

  Multi Dimension List

numbers = [ ["zero", "one"],["two", "three", "FOUR" ]]

numbers[0]>>> ["zero", "one"] 

numbers[0][0]                       numbers[­1][­1]>>> zero                                  >>> FOUR                         len(numbers)

          >>> 2

Page 39: Lesson1 python an introduction

                Sort List

primes = [ 11, 5, 7, 2, 13, 3 ]

Page 40: Lesson1 python an introduction

                Sort List

primes = [ 11, 5, 7, 2, 13, 3 ]

primes.sort()

Page 41: Lesson1 python an introduction

                Sort List

primes = [ 11, 5, 7, 2, 13, 3 ]

primes.sort()

>>> [2, 3, 5, 7, 11, 13]

Page 42: Lesson1 python an introduction

                Sort List

names = [ "Shrini", "Bala", "Suresh", "Arul"]

names.sort()

>>> ["Arul", "Bala","Shrini","Suresh"]

names.reverse()

>>> ["Suresh","Shrini","Bala","Arul"]

Page 43: Lesson1 python an introduction

                Mixed List

names = [ "Shrini", 10, "Arul", 75.54]

names[1]+10>>> 20

names[2].upper()

>>> ARUL

Page 44: Lesson1 python an introduction

                Mixed List

names = [ "Shrini", 10, "Arul", 75.54]

names[1]+10>>> 20

names[2].upper()

>>> ARUL

Page 45: Lesson1 python an introduction

         Append on List

numbers = [ 1,3,5,7]

numbers.append(9)

>>> [1,3,5,7,9]

Page 46: Lesson1 python an introduction

    Tuples                                                             immutable

Page 47: Lesson1 python an introduction

names = ('Arul','Dhastha','Raj')

name.append('Selva')

Error : Can not modify the tuple

Tuple is immutable type

Page 48: Lesson1 python an introduction

    String

Page 49: Lesson1 python an introduction

name = 'Arul'

name[0]>>>'A'

myname = 'Arul' + 'alan'>>> 'Arulalan'

Page 50: Lesson1 python an introduction

name = 'This is python string'

name.split(' ')>>>['This','is','python','string']

comma = 'Shrini,Arul,Suresh'

comma.split(',')>>> ['Shrini','Arul','Suresh']

split

Page 51: Lesson1 python an introduction

li = ['a','b','c','d']s = '­'

new = s.join(li)>>> a­b­c­d

new.split('­')>>>['a','b','c','d']

join

Page 52: Lesson1 python an introduction

'small'.upper()>>>'SMALL'

'BIG'.lower()>>> 'big'

'mIxEd'.swapcase()>>>'MiXwD'

Page 53: Lesson1 python an introduction

Dictionary

Page 54: Lesson1 python an introduction

menu = { “idly” : 2.50, “dosai” : 10.00, “coffee” : 5.00, “ice_cream” : 5.00, 100 : “Hundred”}

menu[“idly”]2.50

menu[100]Hundred

Page 55: Lesson1 python an introduction

      Function

Page 56: Lesson1 python an introduction

def sayHello():        print 'Hello World!' # block belonging of fn

# End of function

sayHello() # call the function

Page 57: Lesson1 python an introduction

def printMax(a, b):        if a > b:                print a, 'is maximum'        else:                print b, 'is maximum'printMax(3, 4) 

Page 58: Lesson1 python an introduction

Using in built Modules

Page 59: Lesson1 python an introduction

#!/usr/bin/python# Filename: using_sys.pyimport time

print 'The sleep started'time.sleep(3)print 'The sleep finished'

Page 60: Lesson1 python an introduction

#!/usr/bin/pythonimport os

os.listdir('/home/arulalan')

os.walk('/home/arulalan')

Page 61: Lesson1 python an introduction

Making Our Own Modules

Page 62: Lesson1 python an introduction

#!/usr/bin/python# Filename: mymodule.pydef sayhi():        print “Hi, this is mymodule speaking.”

version = '0.1'

# End of mymodule.py

Page 63: Lesson1 python an introduction

#!/usr/bin/python# Filename: mymodule_demo.py

import mymodule

mymodule.sayhi()print 'Version', mymodule.version

Page 64: Lesson1 python an introduction

#!/usr/bin/python# Filename: mymodule_demo2.pyfrom mymodule import sayhi, version# Alternative:                 # from mymodule import *

sayhi()print 'Version', version

Page 65: Lesson1 python an introduction

Class

Page 66: Lesson1 python an introduction

class Person:        pass # An empty block

p = Person()

print p

Classes

Page 67: Lesson1 python an introduction

class Person:        def sayHi(self):                print 'Hello, how are you?'

p = Person()

p.sayHi()

Classes

Page 68: Lesson1 python an introduction

class Person:        def __init__(self, name):

#like contstructor                                self.name = name        def sayHi(self):                print 'Hello, my name is', self.name

p = Person('Arulalan.T')

p.sayHi()

Classes

Page 69: Lesson1 python an introduction

                            Inheritance

Classes

Page 70: Lesson1 python an introduction

class A:        def  hello(self):

print  ' I am super class 'class B(A):

 def  bye(self):print  ' I am sub class '

p = B()p.hello()p.bye()

Classes

Page 71: Lesson1 python an introduction

class A:Var = 10

        def  __init__(self):self.public = 100self._protected_ = 'protected'self.__private__ = 'private'

Class B(A):pass

p = B()p.__protected__

Classes

Page 72: Lesson1 python an introduction

File Handling

Page 73: Lesson1 python an introduction

File Writing

Page 74: Lesson1 python an introduction

poem = ''' Programming is funWhen the work is doneif you wanna make your work also fun:        use Python!'''

f = file('poem.txt', 'w') # open for 'w'ritingf.write(poem) # write text to filef.close() 

Page 75: Lesson1 python an introduction

File Reading

Page 76: Lesson1 python an introduction

f= file('poem.txt','r') for line in f.readlines():

print linef.close() 

Page 77: Lesson1 python an introduction

           Database Intergration

Page 78: Lesson1 python an introduction

import psycopg2   

conn = psycopg2.connect(" dbname='pg_database' user='dbuser' host='localhost' password='dbpass' ")

cur = conn.cursor()cur.execute("""SELECT * from pg_table""")rows = cur.fetchall()print rows

cur.close()conn.close()

Page 79: Lesson1 python an introduction

import psycopg2   

conn = psycopg2.connect(" dbname='pg_database' user='dbuser' host='localhost' password='dbpass' ")

cur = conn.cursor()cur.execute("'insert into pg_table values(1,'python')"')conn.commit()

cur.close()conn.close()

Page 80: Lesson1 python an introduction

THE END                                                    of code :­)

Page 81: Lesson1 python an introduction

How to learn ?                                                    

Page 82: Lesson1 python an introduction

Python – Shell

                                                    

● Interactive Python● Instance Responce● Learn as you type

Page 83: Lesson1 python an introduction

bpythonipython

                                                    

} teach you very easily

Page 84: Lesson1 python an introduction

Python can communicate                  With                Other            Languages

Page 85: Lesson1 python an introduction

           C           +       Python

Page 86: Lesson1 python an introduction
Page 87: Lesson1 python an introduction

        Java           +       Python

Page 88: Lesson1 python an introduction
Page 89: Lesson1 python an introduction

     GUI        With    Python

Page 90: Lesson1 python an introduction
Page 91: Lesson1 python an introduction

                 Glade                    +                Python                    +                 GTK                    =              GUI APP

Page 92: Lesson1 python an introduction

GLADE

Page 93: Lesson1 python an introduction

Using Glade + Python

Page 94: Lesson1 python an introduction

Web Web

Page 95: Lesson1 python an introduction

        Web Frame Work in Python

Page 96: Lesson1 python an introduction
Page 97: Lesson1 python an introduction
Page 98: Lesson1 python an introduction
Page 99: Lesson1 python an introduction