Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Complex is better than complicated.


-The Zen of Python, Tim Peters


What is Python?

  • A general purpose programming language that focuses on simplicity and clarity.
  • The glue that allows for the different elements of the Python data analysis stack to communicate with one another.
  • Stupid simple to use and understand.
  • A language that enables people to be productive by generating results quickly.

Side note: Python is a dynamically-typed interpreted language. Open up the Start Menu and the Anaconda3 folder. Click on 'IPython'. This is an interpreter. It interprets your commands through what is called a a Read-Eval-Print loop. It reads your commands after you press enter, it evaluates them, it prints the results, and then waits for your next input to read. Type a = 1 and then press enter. Then type a + 10 and press enter. It allows you to enter your instructions one-by-one in a convenient, interactive manner.


What is IPython?

  • IPython is an enhanced version of the Python interpreter that is designed specifically for interactive use.
  • It has features like autocompletion, object inspection and special functions that allow for easy interaction with data.
  • More importantly for us, it is also tightly integrated with the Jupyter Notebook (in fact, the Jupyter Notebook used to be the IPython Notebook before it expanded beyond Python to other languages.

What can we use Python for?

  • Web programming (many of the websites you use have Python on the backend for generating web templates (via Django)
  • GUI Programming (via PyQT (pronounced 'pie-cute') ... warning GPL3)
  • System administration and system scripting (via the Python Standard Library).
  • Data analysis, via the Scipy stack (pronounced 'sigh-pie').
  • Lots and lots of other stuff (see Python Package Index PyPI (pronounced 'pie-P-I').

Python eccentricities


In [ ]:
# Remember, lines starting with # comments and are not run. 
a = 5

'''Multiline
   comments
   done
   like
   this.'''

if a > 1:
    print('Greater than 1.')
else:
    print('Not greater than 1.')

In Python, we have syntatically important whitespace. In other words, you have to indent certain things. This is different than most other languages where curly braces {} are used to set code blocks apart. This, for example, would not work:

a = 5

if a > 1:
print('Greater than 1.')
else:
print('Not greater than 1.)

This takes some getting used to, but is a blessing in disguise because it forces you to write cleaner and more understandable code.

If you come from another programming language, you'll also notice that we don't have to specify the types of our variables. The 'a' in the example above is automatically presumed to be a number because we put a number in it. It will happily treat it as a number until we do something un-number-like with it, at which point Python will complain.

To compare with a similar Java program (notice type designations and curly braces):

public class ProgramInJava {
public static void main(String[] args) {
int a = 5;
if (a > 1) {
System.out.println("Greater than 1.");
} else {
System.out.println("Not greater than 1.");
}
}
}

Normally, this would have indentation to make it clearer, but it has been removed for the purposes of demonstration.

Common Constructs

No need to fully understand these. Just FYI.


In [ ]:
# You assign variables with the equals sign
a = 5

# Not to be confused with equality
5 == 5

In [ ]:
# Functions
def functiony(my_input):
    s = 'Functions process input and give outputs like ' + my_input
    return s


# We invoke functions with parenthesis
functiony('rutabega')

In [ ]:
# Loops
for item in [1, 2, 3, 4, 5]:
    print(item * 5)

In [ ]:
# Indexing is 0-based like other C languages
my_list = [0, 1, 2, 3]

print('First item of list is ' + str(my_list[0]))
print('Last item of list is ' + str(my_list[-1]))

# WE can also slice ranges like this
print(my_list[0:2])

# Or this
print(my_list[1:])

# Or this
print(my_list[:2])

In [ ]:
# Exceptions are straightforward.
try:
    print(x)
except NameError as e:
    print('Name not found!')

In [ ]:
# We can also create objects for object-oriented programming
class Classy(object):
    
    def __init__(self):
        self.attribute = 'Attribute!'
        
    def method(self):
        return 'Method invoked!'
    
    
c = Classy()

# When you see a period, you're accessing a part of it
c.attribute

IPython Enhancements

Cell Magic

If you ever see a % (percent) sign in IPython code where you wouldn't expect it otherwise, it's pretty safe to assume that you're triggering some of IPython's "magic" commands. These commands will let you do everything from running external commands to timing how quickly certain calculations run. Some of the more common ones you will see are:

%time

Which times how long it takes for your cell to run, and:

%matplotlib inline

Which makes plotting functions draw in your browser instead of in a separate window.


In [ ]:
# Here is an example of %timeit. Use magic.
%timeit import time; time.sleep(.1);

Auto Complete


In [ ]:
# Run this cell to enter the variable
text = 'I am a text string'

In [ ]:
# After that, we can autocomplete by pressing TAB
# Add a period to the end of the text variable.
# This will allow you to access attributes.
# Move until after the period, and press TAB.
# A window should come up giving you your options.
# Choose the "split" function with your arrow keys.
# Add parenthesis to invoke the function.
text

Help


In [ ]:
# Putting a question mark will bring up a help window.
text?

# Don't forget the built in dir() method either, which allows inspection.
dir(text)[-5:]

Next Up: Matplotlib