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!
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.
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)
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!
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)
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. >>>
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.
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
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
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
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?
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
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!
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’
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”]
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?
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>
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.
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!
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!
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]
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>
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!
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].
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.
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!
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’
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()
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.
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
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.
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)
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
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
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()
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?
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!
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.
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
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]
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.
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)
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()
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>