Lesson 02 Python Tutorial 01 - adparker/GADSLA_1403 GitHub Wiki

Python Shell

Typing python into the command line will put you into the "Interactive Interpreter" or "Python Shell". Let's make a directory, cd into it, then run python:

andrews-mbp:~ andrew$ mkdir data_science
andrews-mbp:~ andrew$ cd data_science/
andrews-mbp:data_science andrew$ python
Python 2.7.6 |Anaconda 1.9.0 (x86_64)| (default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

Additional Notes

The >>> is the prompt that tells you the interpreter is ready for your next statement. If you see ..., that means it's waiting for more input from you.

If you get stuck with ..., then you can hit control-c. Sometimes also depicted as ctrl-c, ctrl+c, ^c.

IPython

IPython provides a more interactive shell and a few nice utility functions that make life easier and is worth installing later if you don't have it already.

andrews-mbp:data_science andrew$ ipython
Python 2.7.6 |Anaconda 1.9.0 (x86_64)| (default, Jan 10 2014, 11:23:15)
Type "copyright", "credits" or "license" for more information.

IPython 1.1.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]:

For example, starting with a ?,

?sys

will give documentation for function. Also, IPython provides autocomplete as well. Additionally it provides a few "magic" functions like %time and %paste, the former of which times function and the latter allows easy copy and paste of code.

Don't worry if you don't have it installed. For this tutorial, you can use the regular Python Shell. It's a little more bare-bones, but you should become comfortable with it, since you may find yourself limited to using it (on a server that you don't own, for example).

Variables

Variables are labels that refer to data. Thinking of these as labels will become clearer later.

>>> a = 'Hello, world!'
>>> print a
Hello, world!

White-space at the beginning of a line is important!

Python really cares about white-space because it's used to denote indentation and grouping of code.

>>>  a = 1
  File "<stdin>", line 1
    a = 1
    ^
IndentationError: unexpected indent

Data Types

There are different types of data that Python knows about. By the way, '#' indicates the beginning of a comment, which the interpreter will ignore.

###Basic numeric types

>>> a = 1 # Integer (or just 'int')
>>> a = 2.443 # floating point (or just 'float')
>>> a = 2.3 + 3.1j

Boolean types. They are capitalized.

>>> a = True # Boolean (or just 'bool')
>>> a = False # Boolean (or just 'bool')
>>> a = false # This is not capitalized, so Python doesn't know that you mean Boolean "False".
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'false' is not defined  # This is a Traceback. For now, just pay attention to the last line.
>>>

Strings (i.e. Text)

Strings are created using either single quote, double quote, triple single quote, or triple double quote.

>>> a = 'single'
>>> a = "double"

You have to be consistent though. If you start with one type of quote, you have to end with the same type.

>>> a = 'confused"
  File "<stdin>", line 1
    a = 'confused"
                 ^
SyntaxError: EOL while scanning string literal

What if your text already contains a quote?

>>> a = 'Don't quote me on that.'  # Python thinks you have a string 'Don' followed by other stuff.
# The other stuff doesn't make sense.
  File "<stdin>", line 1
    a = 'Don't quote me on that.'
             ^
SyntaxError: invalid syntax

You can escape quotes and other special characters:

The triple quotes allow you to easily make strings that are multiple linesThe different ways of quoting also let you easily include quotes inside your string. Otherwise, you'll have to escape certain characters to tell Python to treat the character literally. They all result in the same string value. Python doesn't remember which type of quotes you used to define the string.

By the way, print, which we really haven't talked about yet, renders the value for display. Where as, in the Python shell, if you just type in the name of the variable, it will print it out in a more raw format. See below:

>>> a = 'single'
>>> a = "double"
>>> a = "Don't quote me on that."
>>> a
"Don't quote me on that."
>>> print a
Don't quote me on that.
>>> a = '''triple
... single'''
>>> a
'triple\nsingle'    # Note the \n, which represents the New Line control character.
>>> print a   # Using print will *render* the value of a.
triple
single

>>> a = '''Shelly said, "Don't quote me on that."'''  # Mixing quotes.
>>> a
'Shelly said, "Don\'t quote me on that."' # This is the same string as far as Python is concerned. 
# Note the escaped single quote in Don\'t.
# The raw representation is what you can "cut and paste" if you want.
>>> a = 'Shelly said, "Don\'t quote me on that."'   # Don't forget the outer single quotes from above
>>> a
'Shelly said, "Don\'t quote me on that."'
>>> print a      # And here it is rendered. Note the lack of escaping. You can't cut and paste this.
Shelly said, "Don't quote me on that."
>>> a = Shelly said, "Don't quote me on that."   # This is what happens if you mess it up.
  File "<stdin>", line 1
    a = Shelly said, "Don't quote me on that."
                  ^
SyntaxError: invalid syntax
>>>

##Defining functions In Python we define functions by using the def keyword. The value of the function is giving in the return statement.

def addition(x, y):
	return x + y

x and y are the inputs to the function and the return keyword tells us what the function responds. The most important thing to note here is that Python respects whitespace, the second like must be indented for this to run.

##Data Structures

Python has a variety of data structures available. The most basic of them are the basic integer, float and strings. Python is dynamically typed, so typed do not need to be specified and variables can be respecified to different types

x = 5.0
x = [5.0]
x = "Five Point 0"

###Lists

Lists are one of the most common data structures in Python.

l = [1,2,3,4] #Setting up a list
l.append(5) #Adding to it using the append function
l += [6] #Adding to it using the addition operation

###Dictionaries

Dictionaries in Python are equivalent to Hash Tables in any other language.

x = {} # Empty Dictionary
y = {'key' : value}
y[key] = "new-value"

##Loop Constructs

Like any other programming language, Python has loop constructs, the ability to iterate over different elements.

l = [1,2,3,4]
for i in l:
	print i

However, when possible, Python will perform better using list comprehensions.

x = [1,2,3,4]

#The following are equivalent
y = []
for i in x:
	y.append(i**2)

#OR

y = [i**2 for i in x]

Also, Python can iterate over generators, these are functions act as iterators, meaning they give access to elements of a sequence.

For example, xrange

for i in xrange(10):
    print x

or enumerate

for i, el in enumerate(my_list):
   print i, el

This will print out the index of the element (starting from 0) and the element.

⚠️ **GitHub.com Fallback** ⚠️