This notebook was prepared by [Thunder Shiviah](https://github.com/ThunderShiviah). Source and license info is on [GitHub](https://github.com/ThunderShiviah/code_guild).

Relevant links to check out

Python links

Wk0.0

Introduction: Hello Code Guild!

Who I am

What this course is about

Course overview and tentative timeline

wk0: Python

  • Did you know: Python is named after the BBC show “Monty Python’s Flying Circus” and has nothing to do with reptiles.

  • Remember: when you're stuck, google it!

Initialization: Shaving the yak

  • A quick primer on the command line
    • Note: I highly recommend that windows users install a virtual box with ubuntu linux (or some other linux) for this course.
    • Note: Use tab completion!!!
    • pwd - print working directory
    • ls - list directories
    • cd - change directory
    • mkdir - make directory
    • man - get the manual pages for a command
  • Install:

    • Python3
    • IPython
    • git
  • Deliverables:

    • Check that python and ipython are correctly installed by running the REPL (read-eval-print-loop) from your command line (your output should look something like the next line).

Hello!

print('hello world')

In [ ]:
!ipython # you can exit by using Ctrl-c twice.


Python 3.4.3 |Anaconda 2.3.0 (64-bit)| (default, Jun  4 2015, 15:29:08) 
Type "copyright", "credits" or "license" for more information.

IPython 4.0.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: 
KeyboardInterrupt

In [1]: 

In [1]: 
  • Open up ipython notebook by running
    ipython notebook
  • Make sure git is correctly installed by running
    git --version
    You should see git version 2.1.4 or some version greater than 2.1.4.
  • Last, go to my code_guild project repository https://github.com/ThunderShiviah/code_guild and copy the repo url. In your terminal, navigate to the directory that you want to keep your projects and run
    git clone git@github.com:ThunderShiviah/code_guild.git

This should download some class materials to a directory named code_guild. Navigate to wk0/notebooks and run

ipython notebook wk0.0_course_overview

Try running and editing some of the cells.

Introduction to Python

A little history

Python was conceived in the late 1980s[27] and its implementation was started in December 1989[28] by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language (itself inspired by SETL)[29] capable of exception handling and interfacing with the Amoeba operating system.[6] Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, benevolent dictator for life (BDFL).

About the origin of Python, Van Rossum wrote in 1996:[30]

Over six years ago, in December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office ... would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus).


In [6]:
from IPython.display import Image
Image(url='https://upload.wikimedia.org/wikipedia/commons/6/66/Guido_van_Rossum_OSCON_2006.jpg')


Out[6]:

The zen of python


In [7]:
import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

A quick overview of ipython notebook, the python REPL, and running python programs

  • What should you use the REPL for?
  • How can you run a python program (hint: use .py)?
  • How can you use ipython notebook?
  • How can I get help?
    • Python help() command
    • Python documentation
    • Stack overflow
    • google
    • google
    • your classmates
    • me
    • google

Python basic data types

  • See Python 3.5 official tutorial for help.

  • numbers

    • using python as a calculator
  • using variables

    • good variables (hint: short but descriptive)
    • bad variables (hint: not descriptive, don't collide with existing names like str or list!)
  • strings

    • concatenation with +
    • concatenation by putting two strings together
    • multiplication with *
    • indexing
    • reverse indexing (starts at -1!)
    • slicing
  • lists

    • indexing
    • concatenating with +
    • multiplying with *
    • slicing
    • appending
  • Reminder: You can get help on any command by using help(command) (ex. help(str) for help on strings.)

  • Tip: If you're on ipython notebook, try shift+tab to get a function overview. Hitting shift+tab multiple times gives you a more thorough function overview.

Basic data structure - Exercises

Open up the REPL and write the following code. Note: read https://docs.python.org/3.5/tutorial/introduction.html as you do the exercises. It's very useful!

  1. What does putting a # in your code do? # Hint: it's a comment!
  1. print out Hello, world!
    • print out Hello,\nworld! # What is the \n doing?
    • print out Hello,\tworld! # What is the \t doing?
  1. print out Hello, world! back to back 10 times (don't do this the dumb way)
  1. make a string 'hello' and a string 'world' and concatenate them two different ways.
  2. Make two variables, str1 and str2, and assign 'hello' and 'world' to them respectively # Why wouldn't we use as a variable?
  3. Use string indexing on the previous variables to get the o's from 'Hello' and 'World'.
  4. Get the last character in each variable by using reverse indexing. # Why can't we use -0 to reverse index?
  5. What happens if you call an index that's greater than the length of the string? # Ex. str1[100]

  6. Type in the following code (hit enter after each line):

    str1 == 'hello'
    str2 == 'mars'

    What do these return? How is = different from ==?

  7. Make a new variable py = 'Python'. How would we slice py to get 'Py'? # Slice this two ways
  8. What does py[::1] do? What about py[::2] and py[::-1]?
  9. Make an empty list called lst. Append str1, str2, and py (in that order). What will lst[0] return?
  10. Make a new list called lst_long which contains the backwards version of str1, str2, and py entered each three times (hence list should contain 'olleh', 'sram', 'nohtyP', three times each. Don't reverse the strings the dumb way).
  11. Set lst to lst concatenated with lst_long. Use len(lst). What do you get? What does len() command do? Type help(len). Also type help(lst).
  12. Use list slicing to return the original lst. Use lst slicing to return an empty list.
  13. When we slice an object, the first index in the slice is inclusive and the second index is exclusive. What do I mean here?
  14. Remember how indexing with a number larger than the length of our object gave an error? What if we slice with a number larger than the length of our object? Will it give an error? Try out lst[100] and lst[:100]. What's going on here? What about lst[100:]?
  15. Try changing the second element in lst to the number 5 by using lst[1] = 5. Can you change letters in strings?
  16. Python can do multiple variable assignment. Try entering the following:
    a, b = 4, 5
    What does a equal? What about b? Now type (but don't press enter)
    b, a = a, a + b
    Before you press enter, take a guess at what a and b will equal. Were you right?
  17. If you finish early, take a second to look over python documentation for strings and lists. Try implementing a few new functions!

Basic control flow and functions

  • indenting (hint: spaces not tabs! See Guido's reason.)
  • if and else
  • for
    • the range() function
    • for thing in thing:
  • while
  • break, pass
  • making a function using def and return
  • assert

Basic control flow - Exercises

What would the output for the following statements be? Guess the output and then type up the following code to verify your results. Note: Make sure you use four spaces for your indents. Yay muscle memory practice!

for i in range(5):
    print(i*i)
for d in [3,1,4,1,5]:
    print(d, end=" ")
for i in range(4):
    print("Hello")
for i in range(5):
    print(i, 2**i)
for i in range(0):
    print("Hello")
for i in range(20):
    if i%2 == 0:
        print("i equals", i)
for i in range(20):
    for j in range(i,20):
        print(i, j)
for i in range(20):
    for j in range(i,20):
        if i != 0 and i == j - 3:
            print(i, j)
i, j = 10, 20
while i < j:
    print("not yet...", i, j)
    i += 1   # What does the += symbol do?
i, j = 10, 20
while i < j:
    print("not yet...", i, j)
    j -= 1   # What does the -= symbol do?
i, j = 1, 20
while i < j:
    print("not yet...", i, j)
    j /= 2   # What does the /= symbol do?
i, j = 2, 200000
while i < j:
    print("not yet...", i, j)
    i **= 2
for i in range(10):
    if i % 3 == 0:
        print(i, "foo")
    if i % 6 == 0:     # What if I indented this line?
        print(i, "bar")
    else:
        print(i, "baz")
for i in range(10):
    if i % 3 == 0:
        print(i, "foo")
    elif i % 6 == 0: # elif is short for else if
        print(i, "bar")
    else:
        print(i, "baz")
for i in range(10):
    if i % 3 == 0:
        print(i, "foo")
    elif i % 2 == 0: # elif is short for else if
        print(i, "bar")
    else:
        print(i, "baz")
lst = ['a', 'b', 'c', 'd', 'e']
for elem in lst:
    print(elem)
words = 'How many of these do I have to make!!?!?!'
for word in words:  
    print(word)
words = 'How many of these do I have to make!!?!?!'
for thingy in words:  
    print(thingy)
some = 'abvdfh'
stuff = 'mnbdjhe'
for foo in some:
   for bar in stuff:
       if foo == bar:
           print(foo) # What would happen if I instead printed bar?
some = 'abvdfh'
stuff = 'mnbdjhe'
for foo in some:
   for bar in stuff:
       if foo != bar: # What does != do?
           print(foo) # What would happen if I instead printed bar?
some = 'abvdfh'
stuff = 'mnbdjhe'
for foo in some:
   if foo == bar: 
       for bar in stuff:
           print(foo)

What's wrong with the code below?

Figure out what' wrong with each of the below examples and then fix the code.

# Don't run this!
i, j = 10, 20 
while i < j:
    print("not yet...", i, j)
# How would you fix this
for i in range(20):
    for j in range(10):
        print(j/i)
for i in range(20):
    for j in range(10):
        print(j%i)
for i in range(20):
    for j in range(10):
    print(i, j)
for i in range(20):
    if j < i:
        print(i, j) # This will probably work on your machine but that makes it even worse! What's going on?

In [30]:


In [ ]: