Python Tutorial - Some of the basics

Notes on the content of this tutorial

This tutorial is a composite of a number of sources:

[1]Python for Data analysis: Appendix Python Essentials

[2] https://developers.google.com/edu/python/introduction

I reccommend making a copy of this notebook and change the code to test your understanding of the concepts.

What is python?

Python is an interpreted language. The interpreter executes one line at a time. Python can be invoked at the command line with the python command:

C:\Users\PS>python Python 2.7.9 |Anaconda 2.2.0 (64-bit)| (default, Dec 18 2014, 16:57:52) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://binstar.org >>> a=5 >>> print a 5 >>>

>>> is a prompt for the interpreter asking for input. To exit python type exit() or press the combination of keys: ctrl-D

The other way to use ipython is in a ipython notebook like this one. Then instead of >>> the lines of input are delineated by code cells labeled In \[N\]:


In [5]:
a=5
print ("a")
a


a
Out[5]:
5

The print statement printed out right after the input cell and the value of the last variable was displayed in an Out[N]: label in the code cell. Learn about the features of IPython Notebook from http://ipython.org/notebook.html. The use of the cell labels In and Out are from using ipython as the ehanced interpreter shell.

C:\Users\PS>ipython Python 2.7.9 |Anaconda 2.2.0 (64-bit)| (default, Dec 18 2014, 16:57:52) [MSC v.1500 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. IPython 3.0.0 -- An enhanced Interactive Python. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://binstar.org ? -> 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]: a=5 In [2]: print("a") a In [3]: a Out[3]: 5

The Basics Of Python

Language Semantics

Python is a dynamic, interpreted (bytecode-compiled) language. There are no type declarations of variables, parameters, functions, or methods in source code. This makes the code short and flexible, and you lose the compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs.

The emphasis in this language is readablity, simplicity, and explicitness. Some refer to python as executable psuedo code. The best way to learn this code is to run it.

Python uses whitespace (tabs or spaces) to structure code instead of using braces. Some suggest this makes it more readable but you do need to take care that the number and type of white spaces is consistent to maintain working code. The reccommended indent style is to use 4 spaces for each level of the code. You can set an IDE to replace tabs with 4 space characters to speed up development. The notebook interfaces does this for you.

Fix the indent in the following code block ( move the else: back inline with the if block ) and then rerun the cell.


In [6]:
for x in [1,2]:
    if x == 1:
        print 'x=1'
        else:
        print 'x!=1'


  File "<ipython-input-6-0e1ef86a1715>", line 4
    else:
       ^
SyntaxError: invalid syntax

Semicolons (\;) are not needed to terminate a line but they can be used to concatenate a number of statements in a line


In [7]:
a=50;print("a equals "+str(a));b="b contains this string";b


a equals 50
Out[7]:
'b contains this string'

Everything is an object

A fundemental characteristic of python is the consistency of its object model. Numbers, strings, data structures, classes, modules, ... are python objects ( Objects have a name and internal data). Even functions are first class objects and treated just like everything else in the language.

Comments

Good code is self commenting. Better code uses comments to convey intention and dispel confusion. A # stops the interpreter from treating the rest of the line as code, so effectively anything after a # is a comment.


In [8]:
length=7;width=10;#width=55;  oops better not process 
                  #the second width assignment
print (width)
    # best to use comments indented to the block that 
    # the comment refers to ( not like this comment) but a # 
    # could be used to describe the line of code. 
    # See the first line in this cell


10

Function and Object Method Calls

Variables and pass-by-reference

Dynamic references, strong types

Attributes and Methods

Duck Typing

Imports

Binary Operators and comparisons

Strictness vs Laziness


In [9]:
### Mutable and immutable objects

Scalar Types

###Numerics

Strings

Booleans

Type casting

None

Dates and times

Control Flow

if, elif, and else

for loops

while loops

pass

exception handling

Ternary Expressions

Data Structures and Sequences

Tuple

Unpacking tuples

tuple methods

Lists

Adding and removing elements

Concatenating and combining

Generating Lists (range, xrange)

sorting

binary search and maintaining sorted list

slicing

Built-in Sequence Functions

enumerate

sorted

zip

reversed

DICT

Creating Dicts from sequences

Default values

valid dict key types

Set

List, Set, and Dict Compreshensions

Nested list comprehensions

Functions

Function and Object Method Calls