Learn python
Upcoming SlideShare
Loading in...5
×
 

Learn python

on

  • 3,622 views

Learn python in linux and kick start your career

Learn python in linux and kick start your career

Statistics

Views

Total Views
3,622
Views on SlideShare
3,604
Embed Views
18

Actions

Likes
6
Downloads
201
Comments
1

1 Embed 18

http://gianniskarlis.wordpress.com 18

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • super....!!!
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • - needs Software Freedom Day@Alexandria University
  • Write most useful links for beginners starting
  • Write something more interactive

Learn python Learn python Presentation Transcript

  • Programming at the speed of light Pythonism Kracekumar.R [email_address]
  • Agenda
    • What is Python ???
    • Why Python ???
    • Syntax Walkthroughs
    • Linux and Python
  • What is Python ???
    • What is Python ???
    • Why Python ???
    • Syntax Walkthroughs
    • Linux and Python
  • History
    • Created by Guido von Rossum in 1990 (BDFL)
    • named after Monty Python's Flying Circus
    • http://www.python.org/~guido/
    • Blog http://neopythonic.blogspot.com/
    • Now works for Google
  • What is Python ???
    • general-purpose high-level programming language, often used as a scripting language.
    • interpreted, interactive, object-oriented.
    • incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes, automatic memory management.
    • remarkable power with very clear syntax.
    • has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++.
  • What is Python ???
    • supports multiple programming paradigms (primarily object oriented, imperative, and functional)
    • portable: runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, OS/2, FreeBSD Solaris, OS/2, Amiga,AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acorn RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE and even PocketPC !
  • What is Python ???
    • Developed and supported by a large team of volunteers - Python Software Foundation
    • Major implementations: CPython, Jython, Iron Python, PyPy
      • CPython - implemented in C, the primary implementation
      • Jython - implemented for the JVM
      • Pypy - implemented in Python
      • IronPython - implemented in C#, allows python to use the .NET libraries
  • Why Python ???
    • What is Python ???
    • Why Python ???
    • Syntax Walkthroughs
    • Linux and Python
  • Why Python ???
    • Readability, maintainability, very clear readable syntax
    • Fast development and all just works the first time...
    • very high level dynamic data types
    • Dynamic typing and automatic memory management
    • Free and open source
      • Implemented under an open source license. Freely usable and distributable, even for commercial use.
    • Simplicity , Great first language
    • Availability (cross-platform)
    • Interactivity (interpreted language)
  • Why Python ???
    • GUI support – GUIs typically developed with Tk
    • Strong introspection capabilities
    • Intuitive object orientation
    • Natural expression of procedural code
    • Full modularity, supporting hierarchical packages
    • Exception­based error handling
    • The ability to be embedded within applications as a scripting interface
    • Scalable – can play nicely with other languages
  • Batteries Included
    • The Python standard library is very extensive
      • regular expressions, codecs
      • date and time, collections, threads and mutexs
      • OS and shell level functions (mv, rm, ls)
      • Support for SQLite and Berkley databases
      • zlib, gzip, bz2, tarfile, csv, xml, md5, sha
      • logging, subprocess, email, json
      • httplib, imaplib, nntplib, smtplib
      • and much, much more ...
  • Python Libraries
    • Biopython - Bioinformatics
    • SciPy - Linear algebra, signal processing
    • NumPy - Fast compact multidimensional arrays
    • PyGame - Game Development
    • Visual Python - real-time 3D output
    • Django - High-level python Web framework
    • and much more ...
  • E.g. Projects with Python
    • Websites: Google, YouTube, Yahoo Groups & Maps, CIA.gov
      • Appengine: http://code.google.com/appengine/
      • ” Google: Python has been an important part of Google since the beginning.”, Peter Norvig.
      • Python application servers and Python scripting to create the web UI for BigTable (their database project)
    • Systems: NASA, LALN, CERN, Rackspace
      • Nasa Nebula http://nebula.nasa.gov/about
    • Games: Civilization 4, Quark (Quake Army Knife)
    • Mobile phones: Nokia S60 (Symbian), PythonCE
    • P2P: BitTorrent
  • Cont . . .
    • Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.
    • EVE Online, a Massively Multi player Online Game (MMOG), makes extensive use of Python.
    • iRobot uses Python to develop commercial robotic devices.
  • What can you do with Python
    • Systems Programming
    • GUI
    • Internet Scripting
    • Database Programming
    • Numeric and Scientific Programming
    • Natural language analysis
  • What people say about Python ?
    • I can remember many Python idioms because
    they're simpler. That's one more reason I program faster [in Python]. I still have to look up how to open a file every time I do it in Java. In fact, most things in Java require me to look something up. --Bruce Eckel
  • Cont . . .
    • Python ... is compact -- you can hold its entire
    feature set (and at least a concept index of its libraries) in your head. -- Eric S. Raymond
  • Syntax Walkthroughs
    • What is Python ???
    • Why Python ???
    • Syntax Walkthroughs
    • Linux and Python
  • Talk is cheap. Show me the code. Linus Torvaldus
  • Hello World
    • Python 2.6
    • Python 3.0
    print (“Hello World”) print “Hello World”
  • Starting python
    • Open terminal and Enter python and hit enter
    Something like this kracekumar@kracekumar-laptop:~$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
  • Interactive shell
    • >>> 2+3
    • 5
    • >>> 2*3
    • 6
    • >>> 2/3
    • 0
    • >>> 2//3
    • 0
  • Interactive Shell cont . . .
    • >>> 2.0/3.0
    • 0.66666666666666663
    • >>> 2.0/3
    • 0.66666666666666663
    • >>> 2/3.0
    • 0.66666666666666663
    • >>> 2-3
    • -1
  • Interactive shell Cont . . .
    • >>> complex(3,4)
    • (3+4j)
    • >>> 5+4j+5+6j
    • (10+10j)
    • >>> pow(4,5)
    • 1024
    • >>> 4**5
    • 1024
  • Math More
    • >>> 3%4
    • 3
    • >>> long(34.999999)
    • 34L
    • >>> int(34.9999)
    • 34
    • >>> str(5)
    • '5'
  • Still more Interactive shell
    • >>> chr(45)
    • '-'
    • >>> ord('a')
    • 97
    You can do more in interactive shell ,But you might be bored,so Lets start writing small scripts
  • First program
    • Open first.py
    • Run python first.py ,Your program will be interpreted and python will produce .pyc in memory .
    • .pyc =>python compiled
    • Duck typed programming language
  • Interactive Shell (Revisited)
    • >>> b='0x123'
    • >>> type(b)
    • <type 'str'>
    • >>> b=23
    • >>> type(b)
    • <type 'int'>
    • >>> c=32L
    • >>> type(c)
    • <type 'long'>
  • Cont . . .
    • >>> c=2**890
    • >>> c
    • 8254602048994769474255309139320571976856989469314398783249386078541779727448825929287769623244643560854287421769642635607536680617229461519539671538483430889193541937484454440136429963694163141453503639190799818814812942074243152169349951543234944945149040326527156224L
    • >>> len(str(c))
    • 268
    • Str() =>Find string length
  • String
    • >>> name='krace'
    • >>> name1=&quot;krace&quot;
    • >>> name2=&quot;&quot;&quot;krace&quot;&quot;&quot;
    • >>> name3='''krace'''
    • >>> name
    • 'krace'
    • >>> name1
    • 'krace'
    • >>> name2
    • 'krace'
    • >>> name3
    • 'krace'
  • Importing in built modules
    • Open try_import .py
    • Strings
    • >>> name=&quot;kracekumar&quot;
    • >>> name[1:]
    • 'racekumar'
    • >>> name[:1]
    • 'k'
    • >>> name[:5]
    • 'krace'
    • >>> name[:-5]
    • 'krace'
  • Strings are immutable
    • >>> name[0]=&quot;a&quot;
    • Traceback (most recent call last):
    • File &quot;<stdin>&quot;, line 1, in <module>
    • TypeError: 'str' object does not support item assignment
    • >>> name
    • 'kracekumar'
    • >>> name=&quot;K&quot;+name[1:]
    • >>> name
    • 'Kracekumar'
    • Above is a small hack to change the first character value in the name
  • Slicing
    • >>> name[1:5]
    • 'race'
    • >>> name + &quot; likes linux &quot; #concatenation
    • 'Kracekumar likes linux '
    • >>> name.startswith('k')
    • False
    • >>> name.upper()
    • 'KRACEKUMAR'
  • Python introspection
    • Python introspection lets you to find all builtin functions,classes etc. . .
    • >>> dir()
    • ['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b', 'c', 'name', 'name1', 'name2', 'name3', 'sys']
    • dir(anyname) =>will yield all the supported functions.
  • In Built help
    • help(anyname)
    • >>> help(a)
    no Python documentation found for '123' #here no documentation is available so you won't find
    • help(sys)
    Find the magic here :)
  • Data structure
    • 3 in built data structure
    • List => a=[1,”linux”,2,”Free Bsd”]
    • Tuple => b=(1,”apple”,mango)#mango is not quoted because here it refers variable
    • Dictionary =>dict={”name”:”kracekumar”,”email”:” [email_address] ”,”coll”:”Amrita”}
    • Don't worry guys you have array but i will introduce later
  • Data structure
    • >>> a
    • [1, 'linux', 2, 'Free Bsd']
    • >>> b
    • (1, 'apple', 'mango')
    • >>> dict
    • {'coll': 'Amrita', 'name': 'kracekumar', 'email': 'kracethekingmaker@gmail.com'}
    • List is not linked list here
    • You can have string ,int,float in list,tuple,dictionary
  • Data structure in python
    • >>> type(a)
    • <type 'list'>
    • >>> type(b)
    • <type 'tuple'>
    • >>> type(dict)
    • <type 'dict'>
    • Tuple is immutable
  • Cont . . .
    • >>> a[1]
    • 'linux'
    • >>> a[1]=&quot;UBuntu&quot;
    • >>> a[1]
    • 'UBuntu'
    • >>> a
    • [1, 'UBuntu', 2, 'Free Bsd']
  • Cont . . .
    • >>> b[1]
    • 'apple'
    • >>> b[1]=&quot;pine apple&quot;
    • Traceback (most recent call last):
    • File &quot;<stdin>&quot;, line 1, in <module>
    • TypeError: 'tuple' object does not support item assignment
    • >>> b
    • (1, 'apple', 'mango')
  • Dictionary
    • >>> dict
    • {'coll': 'Amrita', 'name': 'kracekumar', 'email': 'kracethekingmaker@gmail.com '}
    • coll =>is key and 'Amrita' =>value
    • All key should be unique
    • >>> dict['coll']=&quot;ASE&quot;
    • >>> print dict
    • {'coll': 'ASE', 'name': 'kracekumar', 'email': 'kracethekingmaker@gmail.com'}
    • >>> dir(dict)
  • Dictionary functions
    • dir() and help() will help you to know more about list tuple
    • dir(dict)
    Try
    • has_key()
    • Pop()
    • Items()
    • Slicing holds for list and tuples
  • Control Flow if guess == number: #do something elif guess < number: #do something else else : #do something else while True : #do something #break when done break else : #do something when the loop ends for i in range( 1 , 5 ): print (i) else : print ( 'The for loop is over' ) #1,2,3,4 for i in range( 1 , 5 , 2 ): print (i) else : print ( 'The for loop is over' ) #1,3
  • Program
    • Wap to find a no is prime or not
    • List comprehension
    • E.g >>> x=[y for y in range(0,20) if y%2 == 0]
    • >>> x
    • [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
    • Alternate way to do
    • Open list_comp.py
    • Dictionaries,list,tuple can be nested
  • Functions
    • Order is important unless using the name
    • Default arguments are supported
    def sayHello (): print ( 'Hello World!' ) def foo (name, age, address) : pass foo( 'Tim' , address= 'Home' , age= 36 ) def greet (name= 'World' )
  • Functions
    • Variable length args acceptable as a list or dict
    def total (initial= 5 , *numbers, **keywords): count = initial for number in numbers: count += number for key in keywords: count += keywords[key] return count print (total( 10 , 1 , 2 , 3 , vegetables= 50 , fruits= 100 ))
  • Functions def printMax (x, y): '''Prints the maximum of two numbers. The two values must be integers.''' x = int(x) # convert to integers, if possible y = int(y) if x > y: r eturn x else : r eturn y printMax( 3 , 5 )
  • Last important thing about variable
    • >>> a=[1,2,3]
    • >>> b=a
    • >>> a[0]=4
    • >>> b
    • [4, 2, 3]
    • >>> a
    • [4, 2, 3]
    • If you want to have copy of a list use slice or import copy(use dir and find out)
  • File Handling
    • Wap to read input from user and write back to file . =>fav_movie.py
    • Wap to read set of numbers and write to file and read the file and add all the nos.=>pickling.py
    • Swap 3 nos
  • Practice problem
    • Get a particular line from a file = >get_particular_line.py
    • Get a list of zip file content and its size =>zip_length.py
    • Get current system name and ip=>details.py
    • Generate a random password using python
  • Modules
    • Any python file is considered a module
    • Modules can be imported or run by themselves
    if __name__ == '__main__' : print ( 'This program is being run by itself' ) else : print ( 'I am being imported from another module' )
  • Recursion
    • >>> def mysum(L):
    • ... if not L:
    • ... return 0
    • ... else:
    • # Call myself
    • ... return L[0] + mysum(L[1:])
    • >>> mysum([1, 2, 3, 4, 5])
    • 15
  • OOPs
    • Python OOP is easy and simple
    • Class classname:
      • Def name():
    Objects
      • instance=classname()
      • Note no new keyword
      • first_class.py
      • Isinstance()
      • issubclass()
  • Inbuilt functions
    • hasattr(obj,attr)
    • getattr(obj,attr)=>retrieves attr value
    • setattr(obj,attr,val)=>set attr value
    • delattr(obj,attr)
    • first_class.py
    • add_book.py
  • More Resources
    • http://wiki.python.org/moin/BeginnersGuide
    • http://www.python.org/doc/faq/
    • Learn Python in 10 minutes: http://www.poromenos.org/tutorials/python
    • Byte of Python: http://www.swaroopch.com/notes/Python
    • Dive Into Python: http://diveintopython.org/
    • Google
  • Any Questions ???
  • Thank You