Becoming a Pythonist

617 views

Published on

A small guide for python beginners

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
617
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Becoming a Pythonist

  1. 1. Becoming a PythonistBecoming a Pythonist
  2. 2. What is Python?Python is a high-level, interpreted, interactive and object oriented-scripting languagePython is a case sensitive programming languageVery clear syntax + large and comprehensive standard libraryCan run on many platform: Windows, Linux, Mactonish
  3. 3. History of PythonCreated in 1990 by Guido Von RossumPython is derived from many other languages, including ABC,Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and otherscripting languages.
  4. 4. Why Python? Python is robust Python is flexible Designed to be easy to learn and use Clean, clear syntax Very few Keywords Highly Portable Python reduces time to market Python is free
  5. 5. Productivity Reduced development timecode is 2-10x times shorter than C, C++, Java Improved Program MaintenanceCode is extremely readable Less TrainingLanguage is very easy to learn
  6. 6. What is it used for? Web Scripting Database applications GUI Applications Steering scientific Applications XML Processing Gaming, Images, Serial Ports, Robots and More..
  7. 7. Python Vs Java Code 5-10 times more concise Dynamic typing Much Quicker DevelopmentNo compilation PhaseLess typing Yes, it runs slowerBut development is faster Python with Java - Jython
  8. 8. AdvantagesReadabilityIt Is Simple to Get SupportFast to LearnReusabilitySoftware qualityDeveloper ProductivityProgram PortabilitySupport LibrariesEnjoyment
  9. 9. Interactive “Shell” Great for learning the language Great for experimenting with the library Type statements or expressions at prompt: $python>>> print “Hello, World”Hello, World>>>
  10. 10. Variable Types Int a=1 a=1 a=2 a=2 Int b = a b=a
  11. 11. Basic DatatypesIntegers (default for numbers)z = 5 / 2 # Answer is 2, integer division.Floatsx = 3.456StringsCan use “” or ‘’ to specify. “abc” ‘abc’ (Same thing.)“““a‘b“c”””BooleanTrue and False
  12. 12. Whitespace and Comment There are no braces to indicate blocks of code for class andfunction definitions or flow control Standard indentation is 4 spaces or one tab# First commentif True:print "True"else:print "False"
  13. 13. Look at a sample of code…x = 34 - 23 # A comment.y = “Hello” # Another one.z = 3.45if z == 3.45 or y == “Hello”:x = x + 1y = y + “ World” # String concat.print xprint y>>> 12>>> Hello World
  14. 14. String Operations>>> “hello”.upper()‘HELLO’>>> print “%s xyz %d” % (“abc”, 34)abc xyz 34>>> names = [“Ben", “Chen", “Yaqin"]>>> ", ".join(names)‘Ben, Chen, Yaqin‘>>> " ".join(names)BenChenYaqin
  15. 15. Lists Lists are similar to arrays in C It can store same data type as well as different data type.list = [ abcd, 786 , 2.23, john, 70.2 ]>>> list[0]abcd>>> len(list)5>>> [1,2,3]+[4,5,6][1,2,3,4,5,6]>>> range(1,5)[1,2,3,4]
  16. 16. Built-in List Functions & Methods:list = [dora, 55, ram, 355.8]>>> list.append(obj) : list.append(guru) → [dora, 55, ram, 355.8,guru]>>>list.count(obj) : list.count(ram) →1>>>list.index(obj) : list.index(55) → 1>>>list.remove(obj) : list.remove(355.8) → [dora, 55, ram, guru]>>>list.reverse() : list.reverse() → [guru, ram, 55, dora]>>>list.pop() : list.pop() → [guru, ram, 55]>>>list[0:2] : list[0:2] → [guru, ram]
  17. 17. Tuples Tuples are sequences, just like lists. Tuples cannot be updated read-only lists>>>tuple = ( abcd, 786 , 2.23, john, 70.2 )>>> tuple[0]abcd>>> len(tuple)5>>> (1,2,3)+(4,5,6)(1,2,3,4,5,6)>>>min(tuple)2.23
  18. 18. Dictionary Dictionaries consist of pairs of keys and their correspondingvalues. Duplicate key is not allowed. Keys must be immutable. Dictionaries are indexed by keys.>>> dict = {Name: Zara, Age: 7, Class: First};>>>dict[Name]Zara>>>del dict[Name]{Age: 7, Class: First}>>>len(dict)2
  19. 19. Built-in Dictionary Functionsdict = {Name: Zara, Age: 7, Class: First};>>> dict.copy() : dict1 = dict.copy() → {Name: Zara, Age:7, Class: First};>>>dict.clear() : dict1.clear() →{}>>>dict.get(key) : dict.get(Age) → 7>>>dict.has_key(key) : dict.has_key(Age) → True>>>dict.items() : dict.items() → [(Age, 7), (Name,Zara), (Class, First)]>>>dict.keys() : dict.keys() →[Age, Name, Class]>>>dict.update(dict2) : dict.update(dict2)>>>dict.values() : dict.values() → [7, Zara, First]
  20. 20. Python LoopsFor Loop :for n in range(1, 4):print "This is the number"While Loop:n = 3while n > 0:print n, "is a nice number."n = n – 1
  21. 21. Defining a Functiondef sum(numbers):"""Finds the sum of the numbers in a list."""total = 0for number in numbers:total = total + numberreturn total>>>sum(range(1, 5))>>>10
  22. 22. Classes Classes usually have methods. Methods are functions whichalways take an instance of the class as the first argument.>>> Class Foo:... def __init__(self):... self.member = 1... def get_member(self):... return self.member...>>> f = Foo()>>> f.get_member()>>> 1
  23. 23. Python Modules Collection of stuff in foo.py file A module is a file consisting of Python code A module can define functions, classes, and variables. import mathcontent = dir(math)[__doc__, __file__, __name__, acos, asin, atan, atan2, ceil, cos,cosh, degrees, e, exp, fabs, floor, fmod, frexp, hypot, ldexp,log,log10, modf, pi, pow, radians, sin, sinh, sqrt, tan, tanh]
  24. 24. Packages in Python Collection of modules in directory Must have __init__.py and contains subpackages. Consider a file Pots.py available in Phone directory.Phone/Isdn.py file having function Isdn()Phone/G3.py file having function G3() # Now import your Phone Package(__init__.py).import PhonePhone.Pots()Phone.Isdn()Phone.G3()
  25. 25. Python Exceptions Handling An exception is a Python object that represents an error. When a Python script raises an exception, it must either handlethe exception immediately otherwise it would terminate andcome out. try:----except Exception :---else:--- try:---finally:---
  26. 26. Web Frameworks for Python Collection of packages or modules which allow developers towrite Web applications Zope2 Web2py Pylons TurboGears Django
  27. 27. Thank You

×