python an-intro v2

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

Upload: arulalan-t

Post on 05-Dec-2014

3.456 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Python an-intro v2

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

Page 2: Python an-intro v2

Python is a Programming Language

Page 3: Python an-intro v2

There are so many 

Programming Languages.

Why Python?

Page 4: Python an-intro v2
Page 5: Python an-intro v2
Page 6: Python an-intro v2

Python is simple and beautiful

Page 7: Python an-intro v2

Python is Easy to Learn

Page 8: Python an-intro v2

Python is Free Open Source Software

Page 9: Python an-intro v2

Can Do

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

● Games● NLP

● ...

Page 10: Python an-intro v2

  H i s t o r y

Page 11: Python an-intro v2

Guido van Rossum   Father of Python            1991

Page 12: Python an-intro v2

                 Perl  Java  Python   Ruby    PHP            1987       1991           1993      1995

Page 13: Python an-intro v2

What is

Python?

Page 14: Python an-intro v2

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: Python an-intro v2

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: Python an-intro v2

     Object Oriented Programming            Classes

         Methods

         Inheritance

         Modules

         etc.,  

Page 17: Python an-intro v2

    Examples!

Page 18: Python an-intro v2
Page 19: Python an-intro v2

print    “Hello World”

Page 20: Python an-intro v2

         No Semicolons !

Page 21: Python an-intro v2

          Variables

  colored_index_cards

Page 22: Python an-intro v2

No Need to Declare Variable Types !

      Python Knows Everything !

Page 23: Python an-intro v2

value = 10

print value

value = 100.50

print value

value = “This is String ”

print   value * 3     # Oh !

Page 24: Python an-intro v2

Input

Page 25: Python an-intro v2

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

print "Hello" , name , "Welcome"

Page 26: Python an-intro v2

         Indentation

Page 27: Python an-intro v2

You have to follow the Indentation Correctly.

Otherwise,

Python will beat you !

Page 28: Python an-intro v2
Page 29: Python an-intro v2

 Discipline 

   Makes  

    Good 

Page 30: Python an-intro v2

Flow

Page 31: Python an-intro v2

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

print “Done\n”

Page 32: Python an-intro v2

  Loop

Page 33: Python an-intro v2

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

Page 34: Python an-intro v2

Q) Print Multiplication Table of user defined number upto N times.

Get both number & N from the User

Hint : Use may use For / While Loop

Page 35: Python an-intro v2

Soln) Print Multiplication Table of user defined number upto N times.

no = int(raw_input(“Enter number ”))N = int(raw_input(“Enter N value ”)) for i in range(1, N + 1):

  print “%d x %d = %d” % (i, no, i*no)

Page 36: Python an-intro v2

number = 23running = Truewhile running :        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 37: Python an-intro v2

Q) What is the core purpose of while loop ?

Page 38: Python an-intro v2

Q) What is the core purpose of while loop ?

Ans)  when the loop has to stop w.r.t certain condition/s. 

So the no of loops in “while loop” is dynamic / undefined one.

Page 39: Python an-intro v2

Lets have some break

Page 40: Python an-intro v2

Lets continue

Page 41: Python an-intro v2

Array

Page 42: Python an-intro v2

                List = Array

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

Page 43: Python an-intro v2

                List = Array

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

numbers[0]>>> zero 

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

          >>> three

Page 44: Python an-intro v2

  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 45: Python an-intro v2

                Sort List

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

Page 46: Python an-intro v2

                Sort List

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

primes.sort()

Page 47: Python an-intro v2

                Sort List

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

primes.sort()

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

Page 48: Python an-intro v2

                Sort List

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

names.sort()

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

names.reverse()

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

Page 49: Python an-intro v2

                Mixed List

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

names[1]+10>>> 20

names[2].upper()

>>> ARUL

Page 50: Python an-intro v2

         Append on List

numbers = [ 1,3,5,7]

numbers.append(9)

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

Page 51: Python an-intro v2

    Tuples                                                             immutable

Page 52: Python an-intro v2

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

name.append('Selva')

Error : Can not modify the tuple

Tuple is immutable type

Page 53: Python an-intro v2

    String

Page 54: Python an-intro v2

name = 'Arul'

name[0]>>>'A'

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

Page 55: Python an-intro v2

name = 'This is python string'

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

comma = 'Shrini,Arul,Suresh'

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

split

Page 56: Python an-intro v2

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

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

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

join

Page 57: Python an-intro v2

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

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

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

Page 58: Python an-intro v2

Dictionary

Page 59: Python an-intro v2

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

>>> menu[“idly”]2.50

>>> menu[100] ”Hundred”

>>> menu.get(“tea”, None)None

Page 60: Python an-intro v2

uwind = { “latitude” : (-90, 90), “longitude” : (0, 360), “level” : 850, “time” : “2013-07-17”, “units” : None}

uwind.keys()uwind.values()for key, value in uwind.iteritems():

print key, ' = ', value

Page 61: Python an-intro v2

Q) So tell me now,      'what is the use of dictionary ?'

Page 62: Python an-intro v2

Q) So tell me now,      'what is the use of dictionary ?'

Do you know dictionary can take even a function as value in it.

Page 63: Python an-intro v2

      Function

Page 64: Python an-intro v2

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

# End of function

sayHello() # call the function

Page 65: Python an-intro v2

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

Page 66: Python an-intro v2

def getMax(a, b):        if a > b:                return a

  print “I will not be printed”     # end of if a > b:    

        return b# end of def getMax(a, b):

mymax = getMax(3, 4) print mymax

Page 67: Python an-intro v2

Q) Write a function to print the passed argument number is even or odd... 

Page 68: Python an-intro v2

Q) Write a function to print the passed argument number 

is even or odd... 

def printEvenOrOdd(no):print “The passed no “, no, if no % 2 == 0:  # condition

print “ is even”else:

print “ is odd”

printEvenOrOdd(10)

Page 69: Python an-intro v2

Using in built Modules

Page 70: Python an-intro v2

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

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

Page 71: Python an-intro v2

#!/usr/bin/pythonimport os

os.listdir('/home/arulalan')

os.mkdir('/home/arulalan/Fun')

print dir(os)

Page 72: Python an-intro v2

Making Our Own Modules

Page 73: Python an-intro v2

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

version = '0.1'

# End of mymodule.py

Page 74: Python an-intro v2

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

import mymodule

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

Page 75: Python an-intro v2

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

sayhi()print 'Version', version

Page 76: Python an-intro v2

Class

Page 77: Python an-intro v2

class Person:        pass # An empty block

p = Person()

print p

Classes

Page 78: Python an-intro v2

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

p = Person()

p.sayHi()

Classes

Page 79: Python an-intro v2

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 80: Python an-intro v2

                            Inheritance

Classes

Page 81: Python an-intro v2

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 82: Python an-intro v2

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 83: Python an-intro v2

File Handling

Page 84: Python an-intro v2

File Writing

Page 85: Python an-intro v2

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 86: Python an-intro v2

Q) How can we write CSV files ?

f = open('nos.csv', 'w') # open for 'w'ritingfor no in range(10):

f.write(str(no) + ',' + str(no * no) + '\n')f.close() 

Page 87: Python an-intro v2

File Reading

Page 88: Python an-intro v2

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

print linef.close() 

Page 89: Python an-intro v2

THE END                                                    of code :­)

Page 90: Python an-intro v2

How to learn ?                                                    

Page 91: Python an-intro v2

Python – Shell

                                                    

● Interactive Python● Instance Responce● Learn as you type

Page 92: Python an-intro v2

bpythonipython

                                                    

} teach you very easily

Page 93: Python an-intro v2

Python can communicate                  With                Other            Languages

Page 94: Python an-intro v2

           C           +       Python

Page 95: Python an-intro v2
Page 96: Python an-intro v2

        Java           +       Python

Page 97: Python an-intro v2
Page 98: Python an-intro v2

     GUI        With    Python

Page 99: Python an-intro v2
Page 100: Python an-intro v2

                 Glade                    +                Python                    +                 GTK                    =              GUI APP

Page 101: Python an-intro v2

GLADE

Page 102: Python an-intro v2

Using Glade + Python

Page 103: Python an-intro v2

Web Web

Page 104: Python an-intro v2

        Web Frame Work in Python

Page 105: Python an-intro v2
Page 106: Python an-intro v2
Page 107: Python an-intro v2

Python / CDAT Tips Blog Links

http://pyaos.johnny­lin.com/?page_id=10

http://pyaos.johnny­lin.com/?page_id=807

http://www.johnny­lin.com/cdat_tips/

http://pyaos.johnny­lin.com/

Page 108: Python an-intro v2
Page 109: Python an-intro v2