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.

Introduction to python

189 views

Published on

Introduction to the Python programming language

Published in: Engineering
  • Be the first to comment

  • Be the first to like this

Introduction to python

  1. 1. Introduction to Python Marian HackMan Marinov <mm@1h.com> Chief System Architect of SiteGround.com Marian HackMan Marinov <mm@1h.com> Introduction to Python
  2. 2. Indentation rules Use only single type of indentation: tabs or spaces Indentation rules are applied per function, not per file :( Python allows you to mix spaces and tabs in different functions Never use different amount of spaces Never mix tabs and spaces PEP8 defines 4 spaces as the delimiter for Python # this is a comment Marian HackMan Marinov <mm@1h.com> Introduction to Python
  3. 3. Documentation """ Module documentation """ import module_name print(module_name.__doc__) print(module_name.func.__doc__) help(func) Marian HackMan Marinov <mm@1h.com> Introduction to Python
  4. 4. Data types Numbers - 1234, 3.1415 Strings - ’spam’, "ham’s", b’ax01c’ Lists - [1, [2, ‘three’], 4] Dicts - {‘food’: ‘jam’, ‘taste’: ‘yummy’} Tuples - (1, ‘spam’, 4, ‘U’) Sets - unordered list of unique items Files - file = open(‘doors’, ‘r’) Core - Booleans, types, None Marian HackMan Marinov <mm@1h.com> Introduction to Python
  5. 5. Variable assignments a = b = 'info' a, b, c = 42 [ a, b ] = [ "info", "data" ] Marian HackMan Marinov <mm@1h.com> Introduction to Python
  6. 6. Number definitions a = 1234 a = -23 a = 0 a = 99999999L a = 42l a = 1.54 a = 3.14e-10 a = 4E210 a = .1 a = 1. Marian HackMan Marinov <mm@1h.com> Introduction to Python
  7. 7. Number operations X << N, X >> N - bitwise left/right shift ~X - bitwise invert X ** Y == pow(x,y) int(X) long(X) float(X) pow(x, y, [,z]) Return x to the power y; if z is present, return x to the power y, modulo z Marian HackMan Marinov <mm@1h.com> Introduction to Python
  8. 8. Number short operators += -= *= %= etc. Marian HackMan Marinov <mm@1h.com> Introduction to Python
  9. 9. String definitions str = "I'm string" str = 'my string' str = """block of long text """ str = "Single" "string" "line" str = u"unicode string" str = b'ax01c' Marian HackMan Marinov <mm@1h.com> Introduction to Python
  10. 10. String formating print("my %s string" % name) print("my {0} string".format(name)) str = '{0}, {1} and {2}' str.format('beer', 'rakia', 'wiski') jolt = """ Greetings %(name)s. This is your %(count)d visit here. """ values = { 'name': 'Pesho', 'count': 13 } print (jolt % values) cmp(jolt, jil) # returns -1, 0, 1 Marian HackMan Marinov <mm@1h.com> Introduction to Python
  11. 11. String operations >>> S = "abcd1234" >>> for x in S: print(x) # char by char >>> S[0], S[-2] ('a', 3) >>> S[1:3], S[3:], S[:-2] ('bc', 'd1234', 'abcd12') >>> len(S) 8 >>> G = "kompot" >>> S + G # concatenation 'abcd1234kompot' >>> "5" in S False >>> "3" in S True Marian HackMan Marinov <mm@1h.com> Introduction to Python
  12. 12. String operations >>> B = list(S) # convert a string into list >>> line = 'new thing here' >>> cols = line.split() ['new', 'thing', 'here'] >>> new_line = "AA".join(cols) 'newAAthingAAhere' >>> new_line.replace('AA', '__') 'new__thing__here' Marian HackMan Marinov <mm@1h.com> Introduction to Python
  13. 13. List operations >>> L = [ 12, 34, 51 ] >>> len(L) 3 >>> L[2] 51 >>> L = [ 12, [ 32, 65, 41 ], 51 ] >>> len(L) 3 >>> L[1][2] 41 >>> L[1:] [[32, 65, 41], 51] Marian HackMan Marinov <mm@1h.com> Introduction to Python
  14. 14. List operations >>> L.append('55') # adds 55 to the end of the list delete and return the last val of the list >>> L.pop() >>> L.extend([82, 92]) # add multiple items to the end >>> A = [ 'for', 'not', 'bare' ] >>> A.remove('not') # removes an entry from the list >>> A.index('bare') # returns 2 >>> A.insert(1, 'com') # adds 1 to com leave only the first val of the list >>> del A[1:] Marian HackMan Marinov <mm@1h.com> Introduction to Python
  15. 15. Dictionary operations D = {} D = { "info": "nodata", "code": 23 } D = { "info": "nodata", "code": { "num": 23, "text": "missi D = dict(name="Bob", "age"=40) D = dict.fromkeys(['a', 'b']) D["info"] D["code"]["num"] "code" in D D.keys() D.values() D.items D.pop(key) eq del(D[key]) len(D) D[key] = 42 Marian HackMan Marinov <mm@1h.com> Introduction to Python
  16. 16. Tuple operations () - empty tuple >>> T = (0,) >>> T = ( 12, "311", 5 ) >>> T = 12, "311", 5 >>> T = tuple('text') ('t', 'e', 'x', 't') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  17. 17. Set operations >>> basket = {'app', 'org', 'app', 'par', 'org', 'ban'} >>> basket # show that duplicates have been removed {'org', 'ban', 'par', 'app'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False Marian HackMan Marinov <mm@1h.com> Introduction to Python
  18. 18. Set operations Demonstrate set operations on unique letters from two words >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} Marian HackMan Marinov <mm@1h.com> Introduction to Python
  19. 19. File operations output = open('file1', 'w') input = open('file1', 'r') input = open('file1', 'rb') # read binary input = open('file1') # same as above str = input.read() # reads entire file str = input.read(N) # read next N chars str = input.readline() # read a single line lines = input.readlines() #read entire file into list output.write(str) output.writelines(lines) fh.seek(N) # seek to offset N fh.close() # close a file handler for line in open('data'): print line open('f.txt', encoding='utf-8') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  20. 20. Program units Functions Modules Classes Marian HackMan Marinov <mm@1h.com> Introduction to Python
  21. 21. Control structures if-elif-else while-else for-else Marian HackMan Marinov <mm@1h.com> Introduction to Python
  22. 22. Control structures - if-elif-else if <test>: code elif <test>: code elif <test>: code else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  23. 23. Control structures - if-elif-else if 1: code A = Y if X else Z A = [Z, Y][bool(X)] >>> branch = {'spam': 5, 'ham': 3, 'other': 1.15} >>> print(branch.get('spam', 'bad value') 5 >>> print(branch.get('spam', 'bad value') 'bad value' Marian HackMan Marinov <mm@1h.com> Introduction to Python
  24. 24. Control structures - while-else while <test>: code else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  25. 25. Control structures - for-else for <statements>: code else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  26. 26. Control structures - nestead list list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in list_of_lists: for x in list: print x Marian HackMan Marinov <mm@1h.com> Introduction to Python
  27. 27. Controlling loops break continue pass the else block Marian HackMan Marinov <mm@1h.com> Introduction to Python
  28. 28. Controlling loops - break while <test>: code if <test>: break else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  29. 29. Controlling loops - continue while <test>: code if <test>: continue else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  30. 30. Controlling loops - pass while 1: pass def func1(name): pass Marian HackMan Marinov <mm@1h.com> Introduction to Python
  31. 31. Controlling loops - else while <test>: code if <test>: continue else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  32. 32. Breaking nestead loops for x in range(10): for y in range(10): print(x*y) if x*y > 50: break else: continue # executed if the loop ended normally ( break # executed if 'continue' was skipped (break) Marian HackMan Marinov <mm@1h.com> Introduction to Python
  33. 33. Breaking nestead loops for x in range(10): for y in range(10): for z in range(10): print(x,y,z) if x*y*z == 30: break else: continue break else: continue break Marian HackMan Marinov <mm@1h.com> Introduction to Python
  34. 34. Breaking nestead loops def your_outer_func(): ... def inner_func(): for x in range(10): for y in range(10): print(x*y) if x*y > 50: return inner_func() ... Marian HackMan Marinov <mm@1h.com> Introduction to Python
  35. 35. Functions def name(VARIABLES) yield vs return Marian HackMan Marinov <mm@1h.com> Introduction to Python
  36. 36. Calling functions func(value) # Keyword argument - matched by name func(name=value) # Pass all objects in sequence as individual arguments func(*sequence) # Pass all key/value pairs in dict as individual keyword ar func(**dict) x = print x('Indirect call of print') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  37. 37. Function definitions def func(name) def func(name=value) def func(*name) # args tuple/list def func(**name) # dict def func(*args, name) def func(*, name=value) Marian HackMan Marinov <mm@1h.com> Introduction to Python
  38. 38. Difference between return and yield return - returns one value and clear the state of the variables yield - return a value and save the position def gensquares(N): for i in range(N): yield i ** 2 for i in gensqares(5): print(i, end=' : ') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  39. 39. Working with modules Import From Reload Marian HackMan Marinov <mm@1h.com> Introduction to Python
  40. 40. Object Oriented Python Marian HackMan Marinov <mm@1h.com> Introduction to Python
  41. 41. zip & map map(func, *iterables) zip Marian HackMan Marinov <mm@1h.com> Introduction to Python

×