Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Day 1String, Control Flow, Data Structure                                       Day 1
StringIntroductionString MethodsMulti-line StringString FormatingUnicode StringIterating, Searching, Comparison           ...
String : IntroductionPython has a built-in string class named "str"A "raw" string literal is prefixed by an rPython string...
String : Methodss.lower(), s.upper()s.strip()s.isalpha(), s.isdigit(), s.isspace()s.find(other)s.replace(old, new)s.split(...
String : Multi-LineDeclare String  Using Single Quotes ()  Using Double Quotes (")  Using Triple Quotes ( or """)raw = rth...
String : Formatingstr.format(*args, **kwargs)% operator  text = ("%d little pigs come out or Ill %s and %s and    %s" % (3...
String : UnicodeDefine Unicode string  ustring = uA unicode u018e string xf1  type(ustring)     <type unicode>Unicode to U...
String : Iterating, Searching, ComparisonLoop on string  for s in str:Check existence of sting  s in str ?Comparison of 2 ...
Control FlowCondition checkingLoops  For  Whilebreak, continue, else and pass statementRange  Range(10)  Range(1, 10)  Ran...
Control Flow : Condition checking>>> x = int(raw_input("Please enter an integer: "))Please enter an integer: 42>>> if x < ...
Control Flow : for loop>>> # Measure some strings:... a = [cat, window, defenestrate]>>> for x in a:...   print x, len(x)....
Control Flow : break, continue and elseLoop statements may have an else clause;it is executed when the loop terminates thr...
Control Flow : for …. elsefor n in range(2, 10):...   for x in range(2, n):...     if n % x == 0:...           print n, eq...
Control Flow : passThe pass statement does nothingPass in loops  >>> while True:  ...   pass # Busy-wait for keyboard inte...
Control Flow : passEmpty Method  >>> def initlog(*args):  ...   pass # Remember to implement this!  ...                   ...
Control Flow : range>>> range(5, 10)  [5, 6, 7, 8, 9]>>> range(0, 10, 3)  [0, 3, 6, 9]>>> range(-10, -100, -30)  [-10, -40...
Data StructurePython built-in types  Tuple  List  DictUsage  List Methods  Dict Methods  Dict Formatting                  ...
Data Structure : tupleTuples, like strings, are immutable:it is not possible to assign to the individual items   of a tupl...
Data Structure : tuple reverse assignmentCreating Tuple>>> t = 12345, 54321, hello!>>> type(t)<type tuple>>>> t(12345, 543...
Data Structure : listPython has a great built-in list type named "list"lst = [], <type list>Create a new list  colors = [r...
Data Structure : working with listL is t B u ild U plist = []         ## Start as the empty listlist.append(a) ## Use appe...
Data Structure : list methods>>> list = [larry, curly, moe]>>> list.append(shemp)               ## append elem at end>>> l...
Data Structure : iterations over listUsing for loop  for var in list>>> squares = [1, 4, 9, 16]>>> sum = 0>>> for num in s...
Data Structure : dictPythons efficient key/value hash table structure is called a "dict"The contents of a dict can be writ...
Data Structure : creating dict## Can build up a dict by starting with the the empty dict {}## and storing key/value pairs ...
Data Structure : Iteration on key or value## By default, iterating over a dict iterates over its keys.## Note that the key...
Data Structure: Iteration on key and value## This loop syntax accesses the whole dict by looping## over the .items() tuple...
Data Structure : del an itemvar = 6del var # var no more!list = [a, b, c, d]del list[0]      ## Delete first elementdel li...
Data Structure : sortingThe easiest way to sort is with the sorted(list) functionThe sorted() function seems easier to use...
Data Structure : working with sorted( )S o r t in g N u m b e r sa = [5, 1, 4, 3]print sorted(a) ## [1, 3, 4, 5]print a ##...
Data Structure : Custom Sorting with keystrs = [ccc, aaaa, d, bb]print sorted(strs, key=len) ## [d, bb, ccc,  aaaa]       ...
Data Structure : Custom comparator## Say we have a list of strings we want to sort by the  last letter of the string.strs ...
Next Session ?Function  Dynamic FunctionsObject Oriented  Class  Inheritance  Method Overload, OverridePython Packaging  _...
Contact me...           Mantavya Gajjar           Phone : 94263 40093      Email : mail@mantavyagajjar.in     Website : ww...
Upcoming SlideShare
Loading in …5
×

Python Day1

2,619 views

Published on

Python Training at Guja

Published in: Technology, Education
  • Be the first to comment

Python Day1

  1. 1. Day 1String, Control Flow, Data Structure Day 1
  2. 2. StringIntroductionString MethodsMulti-line StringString FormatingUnicode StringIterating, Searching, Comparison Day 1
  3. 3. String : IntroductionPython has a built-in string class named "str"A "raw" string literal is prefixed by an rPython strings are "immutable"Characters in a string can be accessed using[index]Unlike Java, the + does not automatically convertnumbers or other types to string form Day 1
  4. 4. String : Methodss.lower(), s.upper()s.strip()s.isalpha(), s.isdigit(), s.isspace()s.find(other)s.replace(old, new)s.split(delim)s.join(list)s.center(width[, fillchar]) Day 1
  5. 5. String : Multi-LineDeclare String Using Single Quotes () Using Double Quotes (") Using Triple Quotes ( or """)raw = rthistn and thatmulti = r"""It was the best of times.It was the worst of times.""" Day 1
  6. 6. String : Formatingstr.format(*args, **kwargs)% operator text = ("%d little pigs come out or Ill %s and %s and %s" % (3, huff, puff, blow down)) %(language)s has %(number)03d quote types. % {"language": "Python", "number": 2}String = Whats your name? Day 1
  7. 7. String : UnicodeDefine Unicode string ustring = uA unicode u018e string xf1 type(ustring) <type unicode>Unicode to UTF-8 nstr = ustring.encode(utf-8) type(nstr) <type str>UTF-8 to Unicode Day 1
  8. 8. String : Iterating, Searching, ComparisonLoop on string for s in str:Check existence of sting s in str ?Comparison of 2 strings == <= >= != Day 1
  9. 9. Control FlowCondition checkingLoops For Whilebreak, continue, else and pass statementRange Range(10) Range(1, 10) Range(0, 10, 3) Day 1
  10. 10. Control Flow : Condition checking>>> x = int(raw_input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:... x=0... print Negative changed to zero... elif x == 0:... print Zero... elif x == 1: Day 1
  11. 11. Control Flow : for loop>>> # Measure some strings:... a = [cat, window, defenestrate]>>> for x in a:... print x, len(x)...>>> for x in a[:]: # make a slice copy of the entire list Day 1
  12. 12. Control Flow : break, continue and elseLoop statements may have an else clause;it is executed when the loop terminates through exhaustion of the list - (with for)when the condition becomes false - (with while)not when the loop is terminated by a break statement Day 1
  13. 13. Control Flow : for …. elsefor n in range(2, 10):... for x in range(2, n):... if n % x == 0:... print n, equals, x, *, n/x... break... else:... # loop fell through without finding a factor... print n, is a prime number Day 1
  14. 14. Control Flow : passThe pass statement does nothingPass in loops >>> while True: ... pass # Busy-wait for keyboard interrupt (Ctrl+C)Empty Class >>> class MyEmptyClass: ... pass ... Day 1
  15. 15. Control Flow : passEmpty Method >>> def initlog(*args): ... pass # Remember to implement this! ... Day 1
  16. 16. Control Flow : range>>> range(5, 10) [5, 6, 7, 8, 9]>>> range(0, 10, 3) [0, 3, 6, 9]>>> range(-10, -100, -30) [-10, -40, -70]>>> a = [Mary, had, a, little, lamb]>>> for i in range(len(a)): ... print i, a[i] Day 1
  17. 17. Data StructurePython built-in types Tuple List DictUsage List Methods Dict Methods Dict Formatting Day 1
  18. 18. Data Structure : tupleTuples, like strings, are immutable:it is not possible to assign to the individual items of a tuple>>> t = 12345, 54321, hello!>>> t[0]12345>>> t(12345, 54321, hello!) Day 1
  19. 19. Data Structure : tuple reverse assignmentCreating Tuple>>> t = 12345, 54321, hello!>>> type(t)<type tuple>>>> t(12345, 54321, hello!)Reverse Operation>>> x, y, z = t Day 1
  20. 20. Data Structure : listPython has a great built-in list type named "list"lst = [], <type list>Create a new list colors = [red, blue, green] print colors[0] ## red print colors[2] ## green print len(colors) ## 3Assignment of list b = colors ## Does not copy the list Day 1
  21. 21. Data Structure : working with listL is t B u ild U plist = [] ## Start as the empty listlist.append(a) ## Use append() to add elementslist.append(b)L is t S lic e slist = [a, b, c, d]print list[1:-1] ## [b, c] Day 1
  22. 22. Data Structure : list methods>>> list = [larry, curly, moe]>>> list.append(shemp) ## append elem at end>>> list.insert(0, xxx) ## insert elem at index 0>>> list.extend([yyy, zzz]) ## add list of elems at end>>> print list ## [xxx, larry, curly, moe, shemp, yyy, zzz] Day 1
  23. 23. Data Structure : iterations over listUsing for loop for var in list>>> squares = [1, 4, 9, 16]>>> sum = 0>>> for num in squares:>>> … sum += num>>> … print sum ## 30 Day 1
  24. 24. Data Structure : dictPythons efficient key/value hash table structure is called a "dict"The contents of a dict can be written as a series of key:value pairse.g. dict = {key1:value1, key2:value2, ... }The "empty dict" is just an empty pair of curly braces {}Looking up or setting a value in a dict uses square brackets. e.g. dict[foo] Day 1
  25. 25. Data Structure : creating dict## Can build up a dict by starting with the the empty dict {}## and storing key/value pairs into the dict like this:## dict[key] = value-for-that-keydict = {}dict[a] = alphadict[g] = gammadict[o] = omega Day 1
  26. 26. Data Structure : Iteration on key or value## By default, iterating over a dict iterates over its keys.## Note that the keys are in a random order.for key in dict: print key## prints a g o## Exactly the same as abovefor key in dict.keys(): print key Day 1
  27. 27. Data Structure: Iteration on key and value## This loop syntax accesses the whole dict by looping## over the .items() tuple list, accessing one (key, value)## pair on each iteration.for k, v in dict.items():print k, >, v## a > alpha o > omega g > gamma Day 1
  28. 28. Data Structure : del an itemvar = 6del var # var no more!list = [a, b, c, d]del list[0] ## Delete first elementdel list[-2:] ## Delete last two elementsprint list ## [b] Day 1
  29. 29. Data Structure : sortingThe easiest way to sort is with the sorted(list) functionThe sorted() function seems easier to use compared to sort()The sorted() function can be customized though optional argumentsThe sorted() optional argument reverse=TrueCustom Sorting With key= Day 1
  30. 30. Data Structure : working with sorted( )S o r t in g N u m b e r sa = [5, 1, 4, 3]print sorted(a) ## [1, 3, 4, 5]print a ## [5, 1, 4, 3]S o r t in g S t r in gstrs = [aa, BB, zz, CC]print sorted(strs) ## [BB, CC, aa, zz] (case sensitive) Day 1
  31. 31. Data Structure : Custom Sorting with keystrs = [ccc, aaaa, d, bb]print sorted(strs, key=len) ## [d, bb, ccc, aaaa] Day 1
  32. 32. Data Structure : Custom comparator## Say we have a list of strings we want to sort by the last letter of the string.strs = [xc, zb, yd ,wa]## Write a little function that takes a string, and returns its last letter.## This will be the key function (takes in 1 value, returns 1 value).def MyComparator(s): Day 1
  33. 33. Next Session ?Function Dynamic FunctionsObject Oriented Class Inheritance Method Overload, OverridePython Packaging __init__.py Day 1
  34. 34. Contact me... Mantavya Gajjar Phone : 94263 40093 Email : mail@mantavyagajjar.in Website : www.opentechnologies.in Follow on Twitter : @mantavyagajjar Day 1

×