Learn Python The Hard Way                   Utkarsh Sengar  Contents taken from © Copyright 2010, Zed A. Shaw.
Resources• Learn Python The Hard Way, 2nd Edition  – http://bit.ly/python-lug (Free online)  – Paperback book costs $15.99...
It’s Easy. 5 most important things:  – Do Not Copy-Paste  – Code  – Practice  – Practice  – Practice
Prerequisites Python v2.5 +   python Any text editor.   gEdit (Linux)   TextMate (OSX) Settings   Tabs Width: 4   ...
TODO: today   Total of 52 chapters   We will cover: 1-22, 28-35, 39-42   Basic constructs, data structures, OOP   Solv...
Lets code…..       etherPadhttp://ip-address:9001
But first……..Pip, pep8, iPython• pip install simplejson  – For python packages in Python package index• pep8 script.py  – ...
comments   Single line comments only   # (an octothorpe) notifies beginning   Ends with a newline
Printing statements   print is builtin function   Usage: print ”Hello, world!”   Appends a newline automatically   To ...
Basic math   * / % + - < > <= >=   Same as C operator precedence   / does a integer division   Example:       print "...
More operators• Basic ones: + - * / %• Try:  – x // y  – abs(x)  – int(x), long(x), float(x)  – complex(re, im)  – c.conju...
variables   No need of types   Duck typing       cars = 100       space_in_car = 4.0       result = cars + space_in_c...
Variables and printing   Can use placeholders in print statements       print ”lets talk about %s” % my_name       prin...
Text (String)   There are 3 types of notation   Single quotes, double quotes, multiline text   Multiline text stores th...
Booleans   True and False   Can use in print with placeholders as well   Anything that has a value is true, anything li...
Input   There are two functions: input(), raw_input()   raw_input() contains string and input() could    contain object ...
Working with python prog files   Any arguments passed to python prog files is    stored in argv   Zero based arguments, ...
Working with files   open(filename, mode) : returns file handle   read() : to read the whole file   readline() and read...
functions   def keyword to declare a function   Arguments dont need function type   Can skip return value   No return ...
functions cont…   def print_none():pass   def print_one(arg1):        print ”got one arg: %s” % arg1   def print_two(ar...
Logics   and, or, not, ==, !=, >, >=, <, <=   and returns last value which makes the    statement true   or returns fir...
Data Structures   List: [1, 2, 3, 2]   Tuples: (1, 2, 3, 2)   Set: {1,2,3}   Dictionary: {’name’ : ’utkarsh’, ’age’ : ...
Lists and loops   Lists: [1, 2, 3]       append(elem), extend(list), insert(idx, elem), rem        ove(x), pop(i), count...
Lists and loops   for element in list:        print element   for i in range(i):        print i   for i, val in enumera...
Lists and loops   Lists from strings:       a = ”A B C D E F”.split()        #[A, B, C, D, E, F’]        a.pop()        ...
Dictionaries   {name: Roopesh’, ’age’ : 42}   Key-value pairs / lookup table   Can be accessed with a[name]   Can add ...
Classes and Objects   Class keyword, inherits from object   Constructor: def __init__   All methods take first arg as t...
Classes and Objects   Instantiating classes with ClassName() syntax   There is no new keyword   Some examples in code g...
Class exampleclass MyClass:   answer = 42   def a_method(self):     print “I am a method”instance = MyClass ()instance.a_m...
List comprehensions (bonus)   [each for each in range(100) if each % 2 == 0]   [some_func(each) for each in range(100)]...
Handling ExceptionsTry:    … do some handlingexcept Error as e:    print efinally:    … do some final clean up
Problem 1Write a function char_freq() that takes a stringand builds a frequency listing of the characterscontained in it. ...
Problem 2In cryptography, a Caesar cipher is a very simple encryption techniques in which eachletter in the plain text is ...
Homework Integer to Romannumerals converter
Want more?• Go here:  – 15 Exercises to Know A Programming Language:    Part 1  – http://www.knowing.net/index.php/2006/06...
A lot more…   List comprehensions, decorators, lambdafunctions, effective unit tests, network and web                  pro...
At the end……“Ill say that learning to create software changesyou and makes you different. Not better orworse, just differe...
Upcoming SlideShare
Loading in...5
×

Python Workshop - Learn Python the Hard Way

2,307

Published on

The contents of this PPT

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

  • Be the first to like this

No Downloads
Views
Total Views
2,307
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
74
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • http://guide.python-distribute.org/installation.html
  • Chart: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
  • Python Workshop - Learn Python the Hard Way

    1. 1. Learn Python The Hard Way Utkarsh Sengar Contents taken from © Copyright 2010, Zed A. Shaw.
    2. 2. Resources• Learn Python The Hard Way, 2nd Edition – http://bit.ly/python-lug (Free online) – Paperback book costs $15.99 – http://learncodethehardway.org• Google python class: – http://code.google.com/edu/languages/google- python-class/• MIT Open courseware: – http://academicearth.org/courses/introduction-to- computer-science-and-programming
    3. 3. It’s Easy. 5 most important things: – Do Not Copy-Paste – Code – Practice – Practice – Practice
    4. 4. Prerequisites Python v2.5 +  python Any text editor.  gEdit (Linux)  TextMate (OSX) Settings  Tabs Width: 4  Insert spaces instead of tabs Your Mind.
    5. 5. TODO: today Total of 52 chapters We will cover: 1-22, 28-35, 39-42 Basic constructs, data structures, OOP Solve two simple python problems. Homework: Another problem. What did you think?
    6. 6. Lets code….. etherPadhttp://ip-address:9001
    7. 7. But first……..Pip, pep8, iPython• pip install simplejson – For python packages in Python package index• pep8 script.py – Python style guide. Your best friend• Python Easter egg – import this• Ipython• Open pydocs : docs.python.org/library/index.html
    8. 8. comments Single line comments only # (an octothorpe) notifies beginning Ends with a newline
    9. 9. Printing statements print is builtin function Usage: print ”Hello, world!” Appends a newline automatically To avoid new line, use a comma (,) Usage: print ”Hello”, print ”roopesh”
    10. 10. Basic math * / % + - < > <= >= Same as C operator precedence / does a integer division Example:  print "Hens", 25 + 30 / 6  print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6  print "What is 5 - 7?", 5 – 7  print "Is it greater or equal?", 5 >= -2
    11. 11. More operators• Basic ones: + - * / %• Try: – x // y – abs(x) – int(x), long(x), float(x) – complex(re, im) – c.conjugate() – pow(x, y) or x ** y
    12. 12. variables No need of types Duck typing  cars = 100  space_in_car = 4.0  result = cars + space_in_car  cars_not_driven = cars Can assign one var to another Tip: type(cars)
    13. 13. Variables and printing Can use placeholders in print statements  print ”lets talk about %s” % my_name  print "There are %d types of people." % 10  print "Those who know %s and those who %s." % (binary, do_not) Also can use names for placeholders  print ”my name is %(name)s” % {name: my_name}
    14. 14. Text (String) There are 3 types of notation Single quotes, double quotes, multiline text Multiline text stores the text, whitespaces and escape characters as well  val = ’hello world’  val = ”hello again!”  val = ”Hello n World !!”  val = ”””no need to ’escape’ anything – ”ok?” ”””  Interesting functions: upper(), lower(), title(), swapcase(),strip()
    15. 15. Booleans True and False Can use in print with placeholders as well Anything that has a value is true, anything like 0, zero length string, zero length list or dictionary is false val = ’Hi my friend’ if val: print ”yo!” If ’Hi’ in val: print ’this keeps getting better!’
    16. 16. Input There are two functions: input(), raw_input() raw_input() contains string and input() could contain object  first = raw_input("Please enter your age ") second = input("Please enter your age again")  print "You said you are", first print "Then you said you are", second  Try again, pass 40+2 in second
    17. 17. Working with python prog files Any arguments passed to python prog files is stored in argv Zero based arguments, first one is always script name  import sys print sys.argv[0] print sys.argv[1]  Run: python file.py 4
    18. 18. Working with files open(filename, mode) : returns file handle read() : to read the whole file readline() and readlines(): to read each line write(data) : writes to file close() : to close the file handle  from sys import argv script, filename = argv txt = open(filename, r+) #r or w print "Heres your script %r:" % script print "Heres your file %r:" % filename print txt.read() txt.write(42) txt.close()
    19. 19. functions def keyword to declare a function Arguments dont need function type Can skip return value No return implies it returns a None value  Always do: x is None and not, x == None  None is similar to null To take unlimited number of arguments: use *arg as argument, it is packing method for arguments
    20. 20. functions cont… def print_none():pass def print_one(arg1): print ”got one arg: %s” % arg1 def print_two(arg1, arg2): print ”got two args: %s, %s” %(arg1, arg2) def print_two_2(*args): print args return args
    21. 21. Logics and, or, not, ==, !=, >, >=, <, <= and returns last value which makes the statement true or returns first value which makes the statement false Both are short-circuit operator  test = True result = test and Test is True or Test is False
    22. 22. Data Structures List: [1, 2, 3, 2] Tuples: (1, 2, 3, 2) Set: {1,2,3} Dictionary: {’name’ : ’utkarsh’, ’age’ : 42}
    23. 23. Lists and loops Lists: [1, 2, 3]  append(elem), extend(list), insert(idx, elem), rem ove(x), pop(i), count(i), sort(), reverse(),len(l) Tuples: (1, 2, 3) Difference:  lists are mutable,  tuples are immutable  Ideally lists should have same data types
    24. 24. Lists and loops for element in list: print element for i in range(i): print i for i, val in enumerate(list): print i, val sorted_list = sorted(list) sort(list) List comprehensions for ease of use (later..)
    25. 25. Lists and loops Lists from strings:  a = ”A B C D E F”.split() #[A, B, C, D, E, F’] a.pop() .join(a) #joins lists to form a string List slicing: list[start:end]  a[0:len(a)]  a[:4]  a[3:]  a[-1]
    26. 26. Dictionaries {name: Roopesh’, ’age’ : 42} Key-value pairs / lookup table Can be accessed with a[name] Can add new values with same syntax a[city] = San Jose Can remove an item with del del a[city] Add a bunch using: dict.update(another_dict)
    27. 27. Classes and Objects Class keyword, inherits from object Constructor: def __init__ All methods take first arg as the instance of class Denoted with word self Any number of args have to follow self def func(self, val)
    28. 28. Classes and Objects Instantiating classes with ClassName() syntax There is no new keyword Some examples in code given. To override operators, override functions like __eq__, __lt__, __gt__, __lte__ etc
    29. 29. Class exampleclass MyClass: answer = 42 def a_method(self): print “I am a method”instance = MyClass ()instance.a_method()hasattr(MyClass, “answer”)
    30. 30. List comprehensions (bonus) [each for each in range(100) if each % 2 == 0] [some_func(each) for each in range(100)] iter(list) produces a list iterator Gives ability to get next item with iterator.next() When iterator gets exhausted, it produces StopIteration exception
    31. 31. Handling ExceptionsTry: … do some handlingexcept Error as e: print efinally: … do some final clean up
    32. 32. Problem 1Write a function char_freq() that takes a stringand builds a frequency listing of the characterscontained in it. Represent the frequency listingas a Python dictionary.Try it with something likechar_freq("abbabcbdbabdbdbabababcbcbab”)
    33. 33. Problem 2In cryptography, a Caesar cipher is a very simple encryption techniques in which eachletter in the plain text is replaced by a letter some fixed number of positions down thealphabet. For example, with a shift of 3, A would be replaced by D, B would becomeE, and so on. The method is named after Julius Caesar, who used it to communicatewith his generals. ROT-13 ("rotate by 13 places") is a widely used example of a Caesarcipher where the shift is 13. In Python, the key for ROT-13 may be represented bymeans of the following dictionary:key ={a:n, b:o, c:p, d:q, e:r, f:s, g:t, h:u, i:v, j:w, k:x, l:y, m:z, n:a, o:b, p:c, q:d, r:e, s:f, t:g, u:h, v:i, w:j, x:k, y:l, z:m, A:N, B:O, C:P, D:Q, E:R, F:S, G:T, H:U, I:V, J:W, K:X, L:Y, M:Z, N:A, O:B, P:C, Q:D, R:E, S:F, T:G, U:H, V:I, W:J, X:K, Y:L, Z:M}Your task in this exercise is to implement an encoder/decoder of ROT-13. Once youredone, you will be able to read the following secret message:Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!
    34. 34. Homework Integer to Romannumerals converter
    35. 35. Want more?• Go here: – 15 Exercises to Know A Programming Language: Part 1 – http://www.knowing.net/index.php/2006/06/16/ 15-exercises-to-know-a-programming-language- part-1
    36. 36. A lot more… List comprehensions, decorators, lambdafunctions, effective unit tests, network and web programming, Some popular modules likeurlib, simplejson, ElementTree and lxml for xmlparsing, SQLAlchemy, sciPy, NumPy, mechanize
    37. 37. At the end……“Ill say that learning to create software changesyou and makes you different. Not better orworse, just different.”“The world needs more weird people who knowhow things work and who love to figure it all out.” ~ Zed ShawSource: http://learnpythonthehardway.org/book/advice.html
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×