Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python Workshop

Python Workshop

Code Boola 2015

Mike Wu

April 09, 2016
Tweet

More Decks by Mike Wu

Other Decks in How-to & DIY

Transcript

  1. What’s our goal here? Hopefully you have some experience with

    programming in general! We are really going to try to keep everything at a level for newcomers! This workshop will help you: • Learn basic programming principles • Learn the syntax of Python • Just play around with some coding puzzles and demos!
  2. What is programming? The best way I heard it put

    was that programming is like a superpower. If you have an idea and you have a computer, knowing how to program is all you need to translate that idea into reality. Making a website, a self-driving car, a robot -- it’s all the same: they all start with code.
  3. Why Python? • Python is a pretty simple language and

    great for beginners.That being said, Python is really powerful! It’s one of the most popular languages. • The syntax of Python is pretty forgiving (& made kind of like English)
  4. Let’s get started: Using Cloud9 A lot of people say

    “the hardest part about learning to program is getting things to install”. Lucky for us, let’s skip all out. Go to https://c9.io/
  5. Hello World! How do you use Python? Let’s make sure

    everything installed properly! • Let’s make a new file together, called hello.py. • We can also check that python works interactively. Just type python. This creates a world where you can type in code and get results immediately! Try adding some numbers!
  6. Getting to know the Unix terminal If you haven’t seen

    this before, Unix terminal is like a really cool finder or explorer. • ls - lists all the files and folders in the current folder • pwd - returns the full path of the current folder • cd - “change directory” → use it to change to another folder. But you can also do awesome things like visit urls or run python programs. • ping google.com • python hello.py • play tetris or pong (in Emacs)
  7. Python as a fancy calculator Start Python in interactive mode.

    Type python into the Unix terminal. Python 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
  8. Python as a fancy calculator (2) >>> 2 + 2

    ⇒ 4 >>> 5 * 3 ⇒ 15 >>> 5 ** 2 ⇒ 25 >>> -10 * 2 ⇒ -20 >>> 5 % 3 ⇒ 2 This is a MOD function. It looks at the remainder when 5 is divided by 3.
  9. Variables and type casting Maybe you want to store the

    answer to a math operation. • To do that, we use variables. • In most languages, variables need to have types. For example, you need to use an integer variable to store integers, and a string variable to store strings. • In python, variables are dynamically typed, aka, you don’t need to worry about any of that. • Variable names can generally be anything you want -- there are some names to avoid that are special to python standard variables or functions.
  10. Variables and type casting (2) >>> myvariable = 2 >>>

    myvariable = 2.3 >>> myvariable = “blahblahblah” >>> newone = myvariable >>> newone
  11. Logical operators / boolean algebra There is a special type

    of objects called boolean objects. They are either True or False. Like any other thing, you can set them to variables. >>> x = 6 >>> y = False Better yet, you can design boolean operations. For example, maybe you want to know if x is greater than 5. >>> x > 5 ⇒ This will return a boolean True
  12. Logical operators / boolean algebra (2) You can do all

    kinds of boolean operations. >>> x = 10 >>> x == 10 ⇒ This will return True >>> x >= 10 ⇒ This will return True >>> x <= 10 ⇒ what do you think this will return? >>> x != 10 ⇒ This will return False >>> not x == 10 ⇒ not kind of like a negative sign. not True = False
  13. Logical operators / boolean algebra (3) and, not, or, and

    xor are two things you use ALL the time in programming. These are the important operators in boolean arithmetic. • and ◦ True and True ⇒ True ◦ True and False ⇒ False ◦ False and True ⇒ False ◦ False and False ⇒ False • or ◦ True or True ⇒ True ◦ False or True ⇒ True ◦ True or False ⇒ True ◦ False or False ⇒ False • not ◦ not True ⇒ False ◦ not False ⇒ True • xor ◦ True xor True ⇒ False ◦ False xor True ⇒ True ◦ True xor False ⇒ True ◦ False xor False ⇒ False
  14. Logical operators / boolean algebra (4) Things get a little

    trickier now but you can do even more complex things. >>> x, y = 10, 12 >>> x*2 == 20 and y/2 == 6 and x + y < 50 >>> x + y > 2 or x**2 > 10 >>> z = x != 40 >>> z ⇒ what do you guys think z is?
  15. Data structures: Lists Lists are a way to store a

    group of variables together into a single structure. >>> squares = [1, 4, 9, 16, 25] • A list has properties! For example, you can get the length of a list: len (squares) • You can also access individual elements in the list. Let’s say you want the first number in squares. (Python is zero-indexed, so everything starts at 0) ◦ >>> squares[0] ◦ >>> squares[1] ◦ >>> squares[-1] ⇒ Gets the LAST index
  16. Data structures: Lists (2) Python makes it really easy for

    you to insert/delete/replace in lists. >>> squares = [1, 4, 9, 16, 25] • squares.append(36) • squares.extend([49, 64]) • squares.index(16) ⇒ 3 • squares.reverse() • squares.sort() • squares.remove(16) • squares.pop(3)
  17. Data structures: Lists (3) One last thing about lists, because

    they are probably the most important type of data structure native to python. Lists can hold multiple types of objects in them: this allows you to really create some powerful groups of variables! >>> [True, 0, ‘asd’, 2.412] ⇒ This is totally okay!
  18. Working with strings in Python To define a string, use

    either single or double quotation marks. >>> s = ‘asd’ The cool thing is that a string in python is just a list of characters. A character is just a single letter, like ‘a’, or ‘b’. You can do all the things you could with lists in strings! In fact, you can convert between the two: >>> list(‘asd’) ⇒ [‘a’, ‘s’, ‘d’] >>> ‘’.join([‘a’, ‘s’, ‘d’]) ⇒ ‘asd’
  19. Working with strings in Python (2) Some fun facts about

    strings: You can convert any number into a string. Those little quotation marks means that the variable is no longer a number → it’s a string with all the string properties! >>> str(12250192) ⇒ “12250192”. Here are some string properties: • x = “hi there” • x.replace(“i”, “j”) ⇒ “hj there” • x.split() ⇒ [“hi”, “there”]
  20. Conditional statements : if and else That’s about it --

    those are all the puzzle pieces! The rest of learning python is about using those puzzle pieces to do things fast. Remember boolean variables? True and False? Well they give us a really good way of deciding when and when not to do something. For example, let’s say we have a variable called candy = 5. And I want to set a new variable called doyoulovepython to True only if candy > 1. How do you do that?
  21. Conditional statements : if and else (2) We can use

    something called conditional statements! In python, they look like this: (where … is replaced by a boolean operator, and <do something> is replaced by code). Any ideas how to do the problem now? if (...): <do something> else: <do something>
  22. Conditional statements : if and else (3) if (candy >

    1): doyoulovepython = True else: doyoulovepython = False
  23. Conditional statements : if and else (4) What if I

    wanted to do a slightly more complicated example. What if in the case that the number of candies equals 3, I want to set doyoulovepython to the string “definitely”. How do you do that? We use something called branching.
  24. Conditional statements : if and else (5) if (candy >

    1): doyoulovepython = True elif (candy == 3): doyoulovepython = ‘definitely’ else: doyoulovepython = False In fact, you can have as many of these elif branches as you want! This is power of programming. No matter what the value of candy is, you can anticipate it and do whatever code you need to!
  25. For loops and repetition If statements are pretty important but

    probably the most important tool in computer science is a for loop. • Imagine you want to add the numbers 1 to 100 all to a list. It would be crazy to do that one at a time. • Most of the programming we do can be accomplished with for and if!
  26. For loops and repetition (2) range : a python function

    to create a list up to a certain value N. >>> range(4) ⇒ [0, 1, 2, 3] since python is 0 indexed! >>> lst = [] >>> for i in range(100): >>> lst.append(i) >>> print(lst) ⇒ [0, 1, 2, 3, …, 99]
  27. For loops and repetition (3) You don’t always need to

    use range. If you have a string, you can loop through the characters. You have list already, you can loop through that! >>> for i in “testtest”: >>> <do something> >>> x = [1,2,3] >>> for i in x: >>> <do something>
  28. For loops and repetition (4) Make sure to indent when

    doing if statements and for loops! Python is really careful about indentation. >>> lst = [] >>> for i in range(5): >>> lst.append(i) ⇒ [4] because this line should be indented!
  29. For loops and repetition (5) If you’ve noticed there are

    two kinds of ways to loop through something in Python: >>> lst = [1,2,3] >>> for i in range(len(lst)): OR >>> for i in lst: What’s the difference? Well, the first one loops through the indexes of lst ⇒ [0, 1, 2]. The second one loops through the actual elements in lst ⇒ [1, 2, 3].
  30. While loops and repetition For loops all kind of depend

    on a sequence of number/strings/etc. We always use it in terms of a for loop or a list or a string. B But… what if there isn’t a sequence. For example, what if I am getting a stream of data where numbers come in one a time? That’s what a WHILE look is for. It always us to loop while some condition is True, independent of the data structure we are using.
  31. While loops and repetition (2) It works pretty similar though!

    Let’s say I’m getting a stream of data into the variable x. None is a python object for nothing, null, etc. >>> while (x != None): >>> <do something> As soon as we are out of data, x becomes None and we stop!
  32. Data structures: Dictionaries A dictionary is a (key, value) hash

    table. In order words, it is like a real dictionary. You have some word to look up, and it gives you the dictionary. In python, you look up a variable and it returns another variable. >>> dict = {} >>> dict[‘a’] = ‘alpha’ >>> dict[‘g’] = ‘gamma’] >>> print dict, dict[‘a’] ⇒ {‘a’ : ‘alpha’, ‘g’ : ‘gamma’}, ‘alpha’
  33. Data structures: Dictionaries (2) Dictionaries are super useful when you

    want relate variables one-to-one! >>> dict = {} • That means that all the keys in the dictionary have to be unique! ◦ >>> dict[‘a’] = 2 ◦ >>> dict[‘a’] = 3 ◦ >>> dict[‘a’] ⇒ 2 • You can access all the keys using dict.keys() • Get all values using dict.values()
  34. Data structures: Dictionaries (3) You can also loop through all

    the items in the dictionary by doing: >>> for k, v in dict.items(): >>> print k, ‘>’, v Notice this is a little different : it loops using two variables! Like any variable in Python, dictionary values can be strings, numbers, objects, wtv. Dictionary keys have to be strings.
  35. Using and defining functions This is a big one. Functions

    are really nice because they allow you to reuse code! For example, if you wanted to apply a custom math function like x! , you may now want to write the code every time. def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) Now you can just use this code all other the place. No need to do it over and over. >>> factorial(5) ⇒ 120 >>> factorial(20) ⇒ 2432902008176640000
  36. Using and defining functions (2) So how do you define

    a function? Notice the indentations... def function_name(*function_parameters): <function code> return something Functions optionally can return something. Like if you wanted to make a function to divide a number in half, you would return the result.
  37. Using and defining functions (3) You can have as many

    function_parameters as you need. For example if you want to add two numbers: >>> def add(x, y): >>> return x + y Maybe you just want a function to do something, but return something. >>> def show_me_value(x): >>> print(x)
  38. Using and defining functions (4) Functions really incorporate everything we’ve

    learned. You can loops, strings, dictionaries, lists, everything in a function as parameters, return values, logic, etc. Functions can be as complicated as you make them! >>> def factorial(x): >>> result = 1 >>> for i in range(2, x + 1): >>> result = result * i >>> return result
  39. Importing libraries Importing libraries in python is really easy. >>>

    import sys Boom! Done. You can actually import other files this way too. If you installed third-party libraries, you could import them as well. Although we won’t be using any. If you want to try some out during our open-project time -- we’d be happy to help! Cloud9 already has most of the popular ones: numpy,matplotlib
  40. Writing and reading to a file All you need open().

    If you have the filename of the a file you want to open: >>> f = open(‘foo.txt’, ‘r’) • ‘r’ tells us we are in READ mode. • ‘w’ tells us we are in WRITE mode. • f is an python file object. You can actually loop through it to read all the lines. >>> for line in f: >>> print line >>> f.close()
  41. Variable Scope When you start trying to solve our puzzles,

    I don’t want you to get stuck. One of the more common ways people mess up is confusing variable scope. Here’s an example: >>> x = 5 >>> for i in range(10): >>> x = i What’s x?
  42. Variable Scope (2) Not too bad right? What about this

    one. >>> x = 5 >>> def set(x): >>> x = 10 >>> return x >>> y = set(5) What’s x? What’s y?
  43. Variable Scope (3) There’s a difference between global and local

    variables! • A variable declared outside a function is global • A variable declared inside a function is local ◦ This variable “disappears” after we leave the function! >>> def my_function(c): >>> print(c) >>> print(c) ⇒ does not exist!
  44. Error Catching Sometimes programs produce errors. And sometimes you want

    to be able to predict what errors can happen and handle them nicely. >>> while True: ... try: ... x = int(raw_input("Please enter a number: ")) ... break ... except ValueError: ... print "Oops! That was no valid number. Try again..." This stuff is useful when you want to fail safely.
  45. Regular Expression Regular expressions are way to parse strings really

    really fast and really cleanly. • Python has a really nice library re to do all regex stuff you want. • Not going to bother explaining the details -- that’s a whole class worth. • In short, you pass it “codes” that you want to look for (i.e. a number in the first position, or a letter between a and z in the second, etc). • Returns groups of substrings that satisfy the condition provided. • https://docs.python.org/3/library/re.html
  46. Regular Expression (2) #!/usr/bin/python import re line = "Cats are

    smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) ⇒ Cats print "searchObj.group(2) : ", searchObj.group(2) ⇒ smarter else: print "Nothing found!!"
  47. List comprehension This is special to python. It’s fast way

    of doing for loops that’s kind of like the way you write sets in math. >>> S = [x**2 for x in range(10)] ⇒ [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >> M = [x for x in S if x % 2 == 0] ⇒ [0, 4, 16, 36, 64] In fact, this way is a little faster than plain old for loops. You can do crazy things. >> X = [x for x in range(i) for i in range(10) if i < 100]
  48. Numpy and Itertools Two of the most popular python libraries

    are numpy and itertools. numpy: a super efficient matrix operations library written in C. >>> np.array([1, 2, 3]) array([1, 2, 3]) You can do all kinds of things with it like transpose, matrix additions, multiplications. It allows you to do math really fast. I use this all the time.
  49. Numpy and Itertools (2) Itertools : a library for an

    efficient (fast) way to iterate over objects. Itertools works like a generator. If you wrap an object using itertools, every time you read from that object, it is like popping from a stack. You generate another output. >>> letters = ['a', 'b', 'c', 'd', 'e', 'f'] >>> booleans = [1, 0, 1, 0, 0, 1] >>> decimals = [0.1, 0.7, 0.4, 0.4, 0.5] >>> itertools.chain(letters, booleans, decimals)
  50. Lambda expressions These are like anonymous functions. It’s design is

    inspired from functional programming, where lambda calculus and lambda functions are really important. • Some people like it better b/c it can be shorter code and more expressive. Example: >>> def f(x): return x**2 >>> g = lambda x: x**2 This g object contains a function! You can run it as g()
  51. Python classes & OOB Python has classes as well. self

    is an object reference to the class object itself. So when you define the class, you can use self to refer the classes attributes. class Example(object): def __init__(self, p): Self.example_param = p def example_function(params): <do something>