User:Imirak

This self study course has been designed for those who want to learn programming using the Python language.


 * Instructor

Mo Karimi (mkarimi714@gmail.com)

Keep these links under your pillow

Python Tutorial

Python Book

Secondary Book

Pair Programming

Code Academy

Course Group Page

Syllabus
Python 101 Introduction to Programming: Course Info

Instructor: Mo Karimi

Text: Learn Python The Hard Way, 3rd Edition by Zed A. Shaw
 * Learning Python O’Reilly by Mark Lutz and David Ascher

Time and Place: Mondays 7pm-10pm

Course Homepage: This Wiki page Course Group page: Google Group

Prerequisites: None, but basic knowledge of the Linux/Unix terminal and file structure is highly recommended.

Lectures: By the end of the class, you will have knowledge of:
 * - different object data types
 * - understanding of crucial data structures and algorithms common in most languages

Python is a relatively easy language to learn, and the perfect medium to teach broader programming techniques. Lecture subjects are likely to change based on the pace of the class. Please refer to the course homepage for notes and lecture subjects.

Assignments: Four exercises, to be completed as a group of no more than 2 people. Due dates TBD during class sessions. Class discussion will follow each assignment. Please submit your answers by email to me

Exams: Three ungraded open-note quizzes and one review quiz. Although not graded, each quiz will be checked individually, and must be completed alone (no partners). Please submit your answers by email to me.

Other Remarks: Your time is valuable; I want you to get as much as possible out of your time in the classroom with me. Please don’t hesitate to let me know how you feel about the pace, or just about how things are going in general.

What is a Computer?

 * A computer is an electronic machine that tries to emulate a human brain for storing data, processing/analyzing data and outputting data.
 * A computer consists of
 * Hard disk: Permanent storage
 * RAM: temporary storage
 * CPU: The brain of the computer.
 * Monitor is just a display device and not actually the computer. It just is the output device.
 * Keyboard/Mouse are the input devices.

What is a Program?

 * A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text/manipulating text.

Programming Techniques

 * Inheritance: A way to reuse code of existing objects (AKA code reuse)
 * Encapsulation:
 * A language mechanism for restricting access to some of the object's components.
 * A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.
 * Polymorphism: The ability to create a variable, a function, or an object that has more than one form.

3 Main Categories of Programming Languages

 * Assembly Language
 * Different types of CPU's: AMD, Intel, etc.,
 * Assembly language is a language that is directly understood by the CPU.
 * Its very tedious and cumbersome to program to write an assembly program.
 * Example:
 * Assembly languages are specific to a CPU and an assembly language program created for one CPU will not work on another CPU.


 * Compiled languages
 * C, C++, etc.
 * Example:


 * The executable file generated from the above program works only on the CPU for which it is generated.


 * Interpreted languages (scripting languages)
 * Perl, Parsley, Python, etc.
 * Example:


 * The above python program runs on any machine/platform. We just need to install an interpreter for that platform.

Common details of any programming language
The details look different in different languages, but a few basic instructions appear in just about every language:
 * input: Get data from the keyboard, a file, or some other device.
 * 'output': Display data on the screen or send data to a file or other device.
 * 'math': Perform basic mathematical operations like addition and multiplication.
 * 'conditional execution': Check for certain conditions and execute the appropriate sequence of statements.
 * 'repetition': Perform some action repeatedly, usually with some variation.

Introducing Python

 * http://www.python.org
 * Downloading and Installing Python on Windows/Linux
 * Some applications come with Python integrated into them (Maya and LightHouse)
 * Why choose python?
 * If you wish to perform a search-and-replace over a large number of text files.
 * Rename and rearrange a bunch of photo files in a complicated way.
 * Write a small custom database.
 * A specialized GUI.
 * If you are tired of C/C++/Java’s way of write/compile/test/re-compile cycle which could be slow. Python is an interpreted language which will help save development time because no compilation and linking is necessary.
 * You could write a C/C++/Java program, but it can take a lot of development time to get even a first-draft program.
 * Reasons:
 * The high-level data types allow you to express complex operations in a single statement.
 * Statement grouping is done by indentation instead of beginning and ending brackets;
 * No variable or argument declarations are necessary.
 * Java:
 * Python


 * By the way, the creator Guido van Rossum named it after the BBC show “Monty Python’s Flying Circus” and has nothing to do with reptiles.

Introducing the Python Interpreter

 * The Python interpreter is a software program that runs the Python programs (source code) you write.
 * The Python interpreter itself is written in C language.
 * The Python interpreter can be accessed...
 * ...on Linux, by typing the command 'python' in Konsole
 * ...on Windows, by going to Start -> Programs -> Python 2.X -> Python (command line)

The Programmer's View

 * A Python program is just a text file containing Python statements.
 * print 'Hello Python'
 * print 'Bye Bye Perl'


 * You can create such a python source code file by saving the text using a text editor.
 * Python files are usually saved with an extension ".py"
 * After you have saved the .py file (say hello.py), you must now tell python to execute the file.
 * Execution means: for the Python interpreter to run all the statements in the file from top to bottom, one after the other.
 * linux:~> > python hello.py


 * So that is the programmer's view of program execution.

Python's View (Advanced Topic)

 * Under the hood, a lot more happens when you tell Python to execute your source code text file.
 * Although knowledge of Python internals is not strictly required for Python programming, a basic understanding of the runtime structure of Python can help you grasp the bigger picture of program execution
 * When You first instruct Python to run your script (another name for source code text file), there are a few steps that Python carries out before your code actually starts crunching away.

Byte code compilation
 * The script is first compiled to byte code. The byte code is then executed on a virtual machine
 * Byte code is a lower-level, platform-independent, Python-specific representation of your source code.
 * Executing byte code is much quicker than original source code statements.
 * For all the modules imported by a Python script, corresponding .pyc files are created.
 * To manually create .pyc files for all .py files in current directory, run the following command
 * python -mcompileall ./

The Python Virtual Machine (PVM)
 * As mentioned earlier, the compiled byte-code is sent to be executed on a Python Virtual Machine (PVM), the runtime engine of python.
 * PVM is just a big loop that iterates through your byte code instructions, one by one, to carry out their intended operations.
 * All of this complexity is hidden for general use
 * Byte-code compilation is automatic, and the PVM is just part of the Python installation on your machine.

Performance Implications
 * Python byte-code is not binary machine code, where as output generated by a C/C++ compiler is binary machine code.
 * Some Python code may not run as fast as C/C++ code because the Python byte code is executed by the PVM loop and not the CPU chip.

Interactive Coding

 * Start an interactive python interpreter session by just typing python in the console.
 * The interactive session automatically prints the results of expressions you type. When the Enter key is pressed, the code you enter on a line will be executed.
 * How to exit the interpreter? CTRL+D
 * Using the Interactive Prompt
 * Type Python commands only
 * print statements are required only in files
 * Don't indent at the interactive prompt
 * Watch out for prompt changes and compound statements

System Command Lines and Files

 * Saving code in .py text files
 * Use print statements in files
 * Unix Executable Scripts
 * #!/usr/bin/X11/python - "hash bang" or "shebang" line
 * Making Executable scripts: chmod +x filename.py

Modules

 * Simple example: using the math module
 * Every .py file is a module
 * Import operations essentially load another file and grant access to that file's contents.
 * import math      	← dynamic link library
 * show help with help(math)
 * dir(math) ← shows the overview of the help and displays all of the attributes
 * __doc__ ← Documentation
 * math.sin.__doc__
 * math.sin(math.pi/2)
 * globals ← what is built into the python interpreter
 * globals.keys

Assignment, Expressions, and print

 * Assignment Statements
 * Assignments create object references
 * They always create references to objects instead of copying the objects.
 * Because of that, Python variables are more like pointers than data storage areas.
 * Names are created when first assigned
 * Creates variables the first time you assign them a value,
 * Names must be assigned before being referenced
 * Python throws an error if variables are used before they are declared.
 * Implicit assignments
 * Except for the = assignment, there are other ways such as: module import, function and class definition, for loop variables, and function arguments are all implicit assignments.
 * Assignment Statement Forms


 * Tuple- and list-unpacking assignments
 * Sequence assignments
 * Multiple-target assignments
 * Augmented assignments and shared references


 * Variable Name Rules
 * Python reserved words
 * Naming conventions
 * Names have no type, but objects do
 * Expression Statements
 * Common Python expression statements
 * Expression Statements and In-Place Changes
 * print Statements
 * print statement forms
 * The Python "Hello World" Program
 * Redirecting the Output Stream
 * The print >> file Extension

Assignment Statements

 * Simple Assignment:
 * myVar = oldValue * foo + skip
 * Simultaneous Assignment:
 * a,b = b,a
 * Assigning Input:
 * input
 * myVar = input(“Enter a number: “)
 * x,y = input(“Enter the coordinates (x,y): “)
 * Pluses:
 * less code
 * less upfront explanation
 * eliminates “redeclaration” errors
 * Minuses:
 * typo on LHS of = creates new variable
 * allows variables to change type
 * typo on LHS of = creates new variable
 * allows variables to change type

Indentation as Syntax

 * Python uses indentation to declare a block of code
 * normally 4 spaces
 * Pluses:
 * less code clutter (and {})
 * eliminates most common syntax errors
 * promotes and teaches proper code layout
 * Minuses:
 * occasional subtle error from inconsistent spacing
 * will want an indentation-aware editor

The Grander Module Story: Attributes

 * The contents of a module are made available to the outside world through its attributes.
 * create a test module


 * In the interpreter:
 * import simpleModule (note no need for .py)
 * globals will show that simpleModule.py has been imported
 * dir(simpleModule) ← the attributes version and target are shown
 * help(simpleModule) ← some info on the module
 * simpleModule.version OR simpleModule.target
 * Create another module with the same layout just a little differences to demonstrate that they are independent even if their attributes are the same


 * Modules and namespaces
 * Modules enable us to avoid attributes names in one file not to collide with attribute names in another file.
 * Namespace: collection of attributes that helps keep the two modules separate from each other
 * simpleModule.target ← simpleModule is a namespace
 * In case you don’t want to use simpleModule.target
 * from simpleModule import *
 * globals
 * now you can see that target is available and you can just use it by typing target
 * >>> target
 * NOTE: This can cause issues if you import simpleModule and simpleModule1 that way
 * the old attributes will be overwritten by the latest module
 * similarly you can use “as” i.e. from simpleModule import target as tar
 * The reload built-in function
 * if you add more attributes to your module and want to reload it:
 * attribute: help = “use this module as an example for the class”
 * if you re-import
 * What happens on import? - After the first import, later imports do nothing
 * the only way is:
 * reload(simpleModule)

String literals

 * String literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings).
 * The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

Introducing Python Object Types
Lets begin our tour of the Python language.


 * In Python, we do things with stuff.
 * Things > Addition, concatenation (Operations)
 * Stuff > Objects on which we perform those operations (Things)


 * Remember that from Chapter 1, any program that we write processes data. In Python, data takes the form of objects, either..
 * Built-in Python objects
 * Objects we create using Python or external language tools.


 * This chapter is very important in the context of learning Python and write good programs.
 * Python programs can be decomposed into modules, statements, expressions, and objects, as follows:
 * Programs are composed of modules. (Chapter 3)
 * Modules contain statements.
 * Statements contain expressions.
 * Expressions create and process objects. (Chapter 4, this chapter..)

Why Use Built-in Types?

 * thingsAndStuff.c
 * In languages like C, most of the programming time goes in implementing data structures (objects/stuff)
 * Also we need to implement functions (operations/things) to manipulate the data structures
 * All this becomes tedious and distracts us from the actual goals of writing a program.


 * thingsAndStuff.py
 * As you can see, in Python most of the tedious work goes away and you can concentrate on solving the problem.
 * Python provides powerful built-in object types as part of the language (We will get an overview of them in this chapter).
 * You can write your own object types (...if really really needed)
 * You are always better off using a built-in object instead of implementing your own. Some reasons are
 * Built-in objects make programs easy to write
 * Built-in objects are a standard part of the language
 * Built-in objects are often more efficient than custom data structures
 * Built-in objects make components of extensions.
 * Python Classes
 * C language interfaces (numPy: Numeric library for scientific computations)


 * In Summary
 * Built-in object types make programming easier
 * More powerful and efficient than most of what can be created from scratch,
 * Bottomline: Built-in objects form the core of every Python program

Python's Core Data Types

 * Core data types are built into the Python language.
 * Everything we process in Python a kind of object.


 * Literal
 * The expression that generates an object.
 * Types originate from the expressions/literals.
 * example: >>> type(1+2+3) ← an object “6” will be created and its type will be int


 * Type declarations
 * In C/C++, are mandatory: int i = 10;
 * In Python, are not present: i = 10
 * The syntax of the expressions you run determines the types of objects you create and use.
 * Built-in function type


 * Python is Dynamically Typed and Strongly Typed
 * Python is strongly typed as the interpreter keeps track of all variables types. It's also very dynamic as it rarely uses what it knows to limit variable usage. In Python, it's the program's responsibility to use built-in functions like isinstance and issubclass to test variable types and correct usage. Python tries to stay out of your way while giving you all you need to implement strong type checking.
 * In a dynamically typed language, objects still have a type, but it is determined at runtime. You are free to bind names (variables) to different objects with a different type. So long as you only perform operations valid for the type the interpreter doesn't care what type they actually are.
 * Object-generation expressions are generally where types originate
 * ...hence Python language is Dynamically Typed
 * stuff = 1
 * stuff = "blender"
 * stuff = [1, 2, 3]
 * In a strongly typed language (like Python) you can't perform operations inappropriate to the type of the object - attempting to add numbers to strings will fail. Problems like these are easier to diagnose because the exception is raised at the point where the error occurs rather than at some other, potentially far removed, place.
 * Once you create an object, you bind its operation set for all time.
 * ...hence Python language is Strongly Typed
 * hello' + 'world
 * 1 + 2
 * ''1 + " hello"
 * dir - list of all attributes of an object (things, data)
 * So then what are Weakly typed and Statically Typed:
 * In a weakly typed language a compiler / interpreter will sometimes change the type of a variable. For example, in some languages (like JavaScript) you can add strings to numbers 'x' + 3 becomes 'x3'. This can be a problem because if you have made a mistake in your program, instead of raising an exception execution will continue but your variables now have wrong and unexpected values.
 * In a statically typed language, the type of variables must be known (and usually declared) at the point at which it is used. Attempting to use it will be an error.

raw_input vs input

 * raw_input assigns the input to a variable as a string


 * input assigns the input as the object

Numbers

 * Types:
 * int: Standard 32 bit integer
 * 32 OR -3432 OR 0
 * long int: Indefinitely long integers
 * 999999999999 OR 1267650600228229401496703205376L
 * floating-point: Standard double-precision float
 * 3.1415 OR 2.57e-10 OR 5E210 OR -3.64e+210
 * Built-in Numeric Operations
 * +, -, *, %, /, abs, round
 * Math Library
 * pi, e, sin, cos, tan, log, log10, ceil
 * dir(2) Vs. dir(3.1415)
 * Interpreter:
 * import random
 * random.random
 * random.choice([1,2,3,4])
 * 3.1415 * 3 vs. print 3.1415 * 3

Exercise 1: quadratic.py
* Quadratic Formula * Individuals will write a python module that will take in as input ... ...a, b, and c and will output the two possible results for x.
 * Please submit this module as a _quadratic.py and email it to me

Strings

 * Literal delimited by ‘ or " pr '''
 * s1 = ‘This is a string”
 * s2 = “This is another”
 * s3 = “that’s one alright”
 * s4 = This is a very long string... # multi-line quote
 * Recording textual information
 * Strings are an example of Python sequence objects
 * Positionally ordered collection of other objects.
 * Left-to-right order
 * Other examples of sequence objects are lists and tuples.
 * String Operations
 * “Hello, “ + “ world!”
 * “Hello ” * 3
 * greet = “Hello Mike”
 * print greet[0], greet[2], greet[4]
 * greet[4:9]
 * greet[:5]
 * greet[6:]
 * len(greet)

Sequence operations

 * S = 'Spam'
 * S[0]
 * S[-1] == S[len(S)-1]
 * len(S) - built-in Python function
 * Slicing - extract entire section in a single step
 * X[I:J]: Give me everything in sequence X from Offset I up to, but not including offset J
 * Concatenation and Repetition
 * S + ' good'
 * S * 3

Brief introduction to Polymorphism

 * '+' means different things for different objects
 * S + ' good'
 * 2 + 3
 * [1,2,3] + [4]
 * ... in sum, the meaning of an operation depends on the objects being operated on.

Immutability

 * integers, strings, tuples are immutable (cannot be changed)
 * S[0] = 'Z'
 * Error text ...omitted... ‘str’ object does not support item assignment
 * S = 'Z' + S[1:] #but we can run expressions to make new objects
 * Python cleans up old objects as you go
 * lists and dictionaries are mutable (can be changed)
 * [1,2,3] + [4]

Type Specific Methods

 * +, * operations are common to all sequence types (strings, lists, tuples)
 * Apart from the generic sequence operations listed above, strings have operations unique to them.
 * These type specific operations are available as methods (functions attached to object, and are triggered with a call expression)
 * Example
 * S = 'spam'
 * S.find('pa') --> new string 	#Find the offset of a substring
 * S.replace('pa', 'lu') --> new string #Replace occurrences of a substring with another
 * S.upper #upper and lowercase conversion
 * S.isalpha #True if all character in the string are alphabetical
 * dir(S)
 * To see what each actually does => help(S.index)
 * line = 'aaa,bbb,ccccc,dd'
 * line.split(‘,’) #Split on a delimiter into a list of substrings.
 * [‘aaa’,’bbb’,’ccccc’,’dd’]

Other ways to code strings

 * S = 'Term\n>\tDefinition'
 * Multi-line strings
 * S = 'A\nB\tC'
 * len(S) #returns 5, \n is new line \t is tab
 * ord(‘\n’) #returns 10 because \n is a byte with the binary value 10 in ASCII
 * S = ‘A\0B\0C’ #\0 the binary zero byte, does not terminate the string

Pattern Matching

 * import re #This module has analogous calls for searching, splitting, and replacement
 * matchVar = re.match(‘Hello[ \t]*(.*)world’, ‘Hello   	Python world’)
 * matchVar.group(1)

String Formatting Operations

 * The effect is similar to the using sprintf in the C language
 * A conversion specifier contains two or more characters and has the following components, which must occur in this order:


 * 1) The "%" character, which marks the start of the specifier.
 * 2) Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
 * 3) Conversion flags (optional), which affect the result of some conversion types.
 * 4) Minimum field width (optional). If specified as an "*" (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
 * 5) Precision (optional), given as a "." (dot) followed by the precision. If specified as "*" (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
 * 6) Length modifier (optional).
 * 7) Conversion type.

Notes:

(1) The alternate form causes a leading zero ("0") to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

(2) The alternate form causes a leading '0x' or '0X' (depending on whether the "x" or "X" format was used) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero.

(3) The alternate form causes the result to always contain a decimal point, even if no digits follow it. The precision determines the number of digits after the decimal point and defaults to 6.

(4) The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be. The precision determines the number of significant digits before and after the decimal point and defaults to 6.

(5) The %r conversion was added in Python 2.0. The precision determines the maximal number of characters used.

(6) If the object or format provided is a unicode string, the resulting string will also be unicode. The precision determines the maximal number of characters used.

Fancier Output Formatting
Basic usage of the str.format method looks like this:

The brackets and characters within them (called format fields) are replaced with the objects passed into the str.format method. A number in the brackets refers to the position of the object passed into the str.format method.

Positional and keyword arguments can be arbitrarily combined:


 * More Documentation

Exercise 2: month.py:
Given the string month write a Python module called month.py which will convert an int, that stands for the month into the three letter abbreviation for that month. (i.e. 1 for Jan) month = “JanFebMarAprMayJunJulAugSepOctNovDec”
 * Please submit this module as a _month.py and email it to me

Quiz 1: Numbers and Strings

 * Please submit your answers in a _quiz1 file and email them to me.

Lists
The Python list object is the most general sequence provided by the language. List are positionally ordered collections of arbitrarily typed objects, and they have no fixed size.
 * Mutable---unlike strings

Sequence Operations
Because they are sequences, lists support all the sequence operation we discussed for strings, the only difference is that results are usually lists instead of strings.
 * len, [I], [I:J], +, *
 * L = [213, ‘spam’, 1.23]
 * len(L)
 * L[:-1]
 * L + [4, 5, ‘hello’]
 * L * 4

Mutability
The reason why lists are considered mutable objects, is because we can items in a list with simple assignment operations.


 * L = [213, 'spam', 1.23, 4, 5, 'hello']
 * L[3] = 'new string'
 * NOW L is [213, 'spam', 1.23, 'new string', 5, 'hello']

Type specific operations
Just like arrays in other languages except a little more powerful: 1) They have no fixed type constraints (L has integers, strings and floats). 2) No fixed size
 * L.append(stuff)
 * L.pop(index)
 * del L[index]
 * L.sort, L.reverse

Bounds Checking

 * List index out of range
 * To grow a list, use append method
 * >>> L
 * [123, 'spam', 'NI']
 * >>> L[20]
 * >>> L[20] = 5

Nesting

 * Matrix = 1,2,3], [4,5,6], [7,8,9
 * Matrix[0]
 * Matrix[2][2]

List Comprehensions

 * A powerful way to process structures like Matrix
 * Example: want to get the second column of Matrix M
 * col2 = [row[2] for row in Matrix]
 * Example-2: Add 1 to each item in column 2
 * [row[1] + 1 for row in M]
 * Example-3: Filter out odd items
 * [row[1] for row in M if row[1] % 2 == 0]
 * Bottom-line
 * Nesting allows us to build up complex information structures directly and easily.
 * You don't wanna build a similar example as above in a language like C/C++
 * Memory management - Allocating memory on the RAM for this
 * Memory cleanup - delete the object
 * Garbage Collection (Automatic Memory management tool)
 * In Python, when we lose the last reference to an object, the memory space occupied by that object's structure is automatically cleaned up for us.

Dictionaries

 * Dictionaries are not sequences, but are instead known as mappings
 * Mappings are also collections of other objects, but they store objects by key (instead of by relative position)
 * Dictionaries are mutable data type in Python.
 * Example
 * D = {‘food’: ‘Spam’, ‘quantity’: 4, ‘color’: ‘pink’}

Mapping Operations

 * D = {}
 * D['food'] = 'idli'
 * D['quantity'] = 100
 * D['taste'] = 'awesome'
 * D['quantity'] -= 10 # subtract “Subtracting 10 from ‘quantity’ value

Nesting Revisited

 * Previously we saw an example of nesting lists to create matrices
 * We can nest lists inside dictionaries and vice versa to create complex objects.
 * You can use numbers to "index" into a list, meaning you can use numbers to find out what's in lists. You should know this about lists by now, but make sure you understand that you can only use numbers to get items out of a list.
 * What a dict does is let you use anything, not just numbers. Yes, a dict associates one thing to another, no matter what it is. Take a look:


 * Example 1:


 * Example 2:

Homework
Write a Python module that uses the following dictionary, chooses a random key from that dictionary, and prints the key and its value as a tuple.

Tuples

 * Roughly like a list (can hold sequence of arbitrary objects)
 * ...But cannot be changed once created (Immutable like string)

Sequence Operations

 * T[0], T[1:] ....
 * len(T)
 * T + (5, 6)
 * Note that there is no .append so you are not changing the object and therefore it is immutable.
 * T[0] = 1000
 * (1000,) + T[1:]

Why tuples?

 * Tuples are not generally used as often as lists in practice, but their immutability is the whole point.
 * If you pass a collection of objects around your program as a list, it can be changed anywhere.. but with a tuple you cannot.
 * Bottom-line: tuples provide a sort of integrity constraint that is convenient when we write very large software systems. They are also hash-able and can be used as things like, dictionary keys or set values.

Files

 * File objects are your Python programs main interface to external files on your computer.
 * There is no specific literal/expression for creating them
 * Use the built-in Python function open

Writing to/Creating a new file

 * first argument is a string containing the filename.
 * second argument is another string containing a few characters describing the way file will be used.
 * ‘r’ for read, ‘w’ for only writing (an existing file with the same name will be erased), ‘a’ opens the file for appending; any data written to the file is automatically added to the end
 * ‘r+’ opens the file for both reading and writing
 * ‘r’ will be assumed if the mode argument is omitted.
 * This creates a file in the current directory and writes text to it.


 * Alternatively you can open a file using the keyword with

Reading an existing file

 * A files contents are always a string of bytes to your script/program
 * read read([size]) -> read at most size bytes, returned as a string.
 * readline return a line of the file. Returns an empty string if the end of the file has been reached.
 * returns ‘\n’ for a blank line
 * readlines returns a list containing all the lines of data in the file.
 * Again here, alternatively you can open a file using the keyword with

Other operations

 * dir(file)
 * help(file.write)

Example

 * filesReadWrite.py

Sets & Special Types

 * Sets
 * Built-in set function
 * Sets are an unordered collection of objects that are unique.
 * S1 = set([1,2,3,4,4,4,4])
 * will result in a set S1 = set([1,2,3,4])
 * Basic uses include membership testing and eliminating duplicate entries.
 * The set function can be used to create sets.
 * S1 = set([1,2,3,4])
 * S2 = set([2, 3, 5,6])
 * dir(S1) to see what’s available
 * Mathematical set operations
 * S1 | S2 (Union) - new set of all the elements
 * S1 & S2 (Intersection) - What is common in both sets
 * S1 - S2 (Difference) - Which elements are unique in S1 than S2
 * Interpreter
 * Example 2


 * Booleans
 * 1 True object
 * 0 > 5 => False object
 * bool(object)
 * None
 * Placeholder object
 * L = [None] * 100
 * L[50] = ['Bugs Bunny', 69, 'Looney Toon'] OR L[30] = ‘Thirty first index’
 * type
 * type(object)

User Defined Classes

 * If the types we discussed so far are boring and primitive for your own needs...
 * You can define new classes which create new Python types.. Joy!!!!!
 * Classes define new types of objects that extend the core Python built-in object types
 * Apart from creating new types, you can also dictate what operations can be performed on those types.. Joy Unlimited!!!
 * Example
 * RHEmployee.py
 * This example brings up the topic of Object Oriented Programming. But we will discuss that later on.

Quiz 2: Object Types
1. what does “sequence” mean, and which three types fall into that category? 2. what does “mapping” mean, and which core type is a mapping? 3. Given the list L answer the following questions using python’s built-in functions: L = [5.2,’Alex’,11,’soccer’,7.5,’Alex’,461] a. Number of occurrences of Alex and 11 b. Append the number 11 to index 4 c. Return L as a string d. Return and Remove the first occurrence of 11 in the list 4. Create an object that will hold basic information about an employee. a. These information include: firstName, lastName, deptID, email, room, dateStarted, and dateEnded b. Now add the following information: active (True/False), permanent_location, and title c. Update the values to reflect your own information.
 * Please submit your answers in a _quiz2 file and email it to me.

Intro
Typing is one of the most important concepts to understand for a programmer. And Dynamic Typing in Python is very important to understand to be able to program using OOPS.

The Case of the Missing Declaration Statements

 * In C/C++/Java (compiled or statically typed languages) we must declare them (type and name).
 * But how come we have not specified a type, when creating a variable?

Enter the domain of Python's dynamic typing model.
 * Types are determined automatically at runtime (not in response to declarations in your code)
 * Its all about the variables, objects and links between them.

Variables, Objects and References
The implications of the dynamic typing in Python are
 * Variable creation:
 * A variable (also called a name) is created when your code first assigns it a value.
 * Future assignments change the value of the already created name


 * Variable types:
 * A variable never has any type information or constraints associated with it.
 * The notion of type lives with objects!
 * Variables are generic in nature: they always simple refer to a particular object at a particular time.


 * Variable use:
 * When a variable appears in an expression, it is immediately replaced with the object that it currently refers to, whatever that may be.
 * All variables must be declared (via assignment) before they can be used.

Practical Example


 * Create an object to represent the value 3.
 * Objects are pieces of allocated memory, with enough space to represent that value for which they stand.
 * Create a variable a, if it does not not yet exist.
 * Variables are entries in the system table, with spaces for links to objects.
 * Link the variable a to the new object 3.
 * References are automatically followed pointers from variables to objects.

Types live with Objects, Not Variables
In Python
 * 1) Names have no types
 * 2) Types live with objects
 * 3) Each object contains a header field that tags the object with its type.

Objects are Garbage-Collected

 * When we reassign an already existing variable, what happens to the value (object) it was previously referencing?


 * Garbage Collection:
 * Whenever a name is assigned to a new object, the space held by the previously referenced object is reclaimed.
 * This automatic reclamation of object's space is called garbage collection.

Shared References and Equality

 * Garbage-collection behavior

The int object 42 is cached by Python (its treated as a Flyweight object )

Detecting shared references in your code (for not so simple data types)

Above operations on small numbers (Behavior is different)

Ask Python about reference count of an object (How many variables are referencing the same object)
 * Note: The results may vary when you run the commands below

The above behavior reflects one of many ways Python optimizes its model for execution speed.

Dynamic Typing Is Everywhere

 * In most cases, you need not worry about the reference, reference count semantics that we discussed in the previous section.
 * If a mutable object out from under you when passed around your program, for example, chances are you are witnessing the semantics discussed in the previous section.


 * Why care about the semantics discussed in this section?:
 * Because, everything seems to work by assignment and references in Python
 * Assignment statements
 * Function arguments
 * for loop variables
 * module imports
 * and more...
 * The good news is that there is just one assignment model in Python.


 * Pro's of Dynamic Typing in Python:
 * Once you get a handle of it, you'll find that it works the same everywhere in the language.
 * There is less code for you to write
 * Its the root of polymorphism
 * Because we do not constrain types in Python, its very flexible.

When used right, dynamic typing and the polymorphism it provides produce ... ... code that automatically adapts to new requirements as your systems evolve.

Quiz 3: Exercise reading from file
1) Create a file in your home directory and call it testfile. 2) Contents of the file should be: uname: minnie fname: Minnie lname: Mouse title: HR Administrator loc: Van 3) Using what we have learned so far:        3.1) Parse the file ~/testfile 3.2) Read it line by line. Then use the first column as a key to your dictionary and the rest as your value 4) Using string manipulation techniques previously covered, print a line which describes a little about ...     ... Minnie and her roll in the company 5) Note: The point of the exercise is to design the perfect dictionary that can serve you as a temporary database.      Meaning, if you were to add more items (appending) and retrieving the data should be easy and straight forward.

Please submit your answers in a _quiz3 and email it to me.

Chapter 6: Introducing Python Statements

 * Python Program Structure Revisited
 * Programs are composed of modules.
 * Modules contain statements.
 * Statements contain expressions.
 * Expressions create and process objects.


 * Python's Statements (Table 10-1)


 * A Tale of Two ifs
 * Other C-like languages:


 * Python


 * What Python Adds
 * Colon instead of braces
 * What Python Removes
 * Parentheses are optional
 * End of line is end of statement
 * End of indentation is end of block


 * Why Indentation Syntax?
 * Forces a clean and readable code
 * Different people might light to indent differently.
 * Python is a WYSIWYG language - what you see is what you get Python’s Syntax Model
 * Python’s syntax model
 * The end of a line terminates the statement on that line (without semicolons).
 * Nested statements are blocked and associated by their physical indentations (without braces)
 * A Few Special Cases
 * Statement rule special cases (semicolons as statement separators)
 * Can have more than one per line with semicolons; a = 1;b = 2; print a+b
 * Only for simple statements, like assignments, prints, and function calls.
 * ALSO you can use parentheses (), square brackets ([ ]), or ({ })

OR


 * Block rule special case
 * Body of a compound statement can instead appear on the same line as the header
 * if x > y: print x
 * This allows us to code single-line if statements, single-line loops, and so on.


 * A Simple Interactive loop

Introduction
In our day-to-day life we perform actions after careful thought for each of the options we come across. Python provides the if compound statement to achieve this conditional execution.


 * What is a compound statement?:
 * A compound statement embeds other statements.

if Statements

 * Simply put, if statement selects actions to perform (selecting from alternative actions based on test results)
 * Most of the logic in a Python program can be represented using if.
 * Since if is a compound statement, it can contain other if statements, or any other Python statements to create complex programs.

Multiway Branching

 * 1) Multiway branching means using if-elif-elif...else chain of conditional statements to code your program logic.
 * 2) Another way of achieving multiway branching is using Dictionaries.

Few properties of statement-based syntax

 * Statements execute one after another, until you say otherwise.
 * Block and statement boundaries are detected automatically
 * Compound statements = header, ":," indented statements
 * Blank lines, spaces, and comments are usually ignored
 * Docstrings are ignored, but saved and displayed by tools

Block Delimiters

 * Python detects block boundaries automatically, by line indentation (Empty space to the left of your code)
 * All statements indented the same distance to the right belong to the same block of code
 * The statements within a block line-up vertically, as in a column.
 * When does the block end?: The block ends when..
 * A lesser-indented line is encountered
 * The end of file is reached.

Statement Delimiters
Special rules for long statements to span multiple lines
 * Statements may span multiple lines if you're continuing an open syntactic pair
 * Statements may span multiple lines if they end in a backslash
 * Triple-quotes string literals can span multiple lines
 * Other rules
 * Terminate statements with semicolon
 * Comments and blank lines can appear anywhere in a file

Exercise 3: temperature.py:
The homework for this week will be a module that asks the user the following question: Press C to convert Celcius to Fahrenheit Press F to convert Fahrenheit to Celcius: Note: You have to make sure to accept either lowercase or uppercase C's and F's. Then it will use the mathematical formula for the conversion and print out something like this: X degree Celcius == y degree Fahrenheit and vise versa.
 * Please submit this module as _temperature.py and email it to me

Introduction
Ever found yourself repeating forever, or for sometime, or repeating somethings.. In either case, Python provides you with looping constructs - statements that repeat an action over and over. Python also provides facilities to break out of a looping operation..

Lets go on with the tutorial shall we..

while Loops

 * Python's while statement is the most general iteration construct in the language.
 * It repeatedly executes a block of statements as long as a test at the top is true
 * When test becomes false, control passes to the statement that follows the while block.
 * If a test is false to begin with, the body of while never runs.

General Format
Following is another way of putting the above described characteristics of the while loop statement.

If the while and else body does not have compound statements,

There is a general while loop format, which we will take a look in the next section "break, continue, pass, and the Loop else"

Slice and Dice

 * In this example, we keep slicing off the first character of a string object until it is empty.
 * In Python, if an object is empty, it translates to False value, so we can use an object for the while test.

break, continue, pass, and the Loop else
Now that we have seen the while loop, lets take a look at some simple python statements that make programming easier and convenient


 * break: Jumps out of the closest enclosing loop (past the entire loop statement).
 * continue: Jumps to the top of the closest enclosing loop (to the loop's header line).
 * pass: Does nothing at all: it's an empty statement placeholder.
 * Loop else block: Runs if and only if the loop is exited normally (i.e., without hitting a break)


 * Note:
 * break and continue statements can appear anywhere inside the while (or for) loop's body.
 * Although, they are generally coded further nested in an if test to take action in response to some condition. (as you will see in next sub-section)

We will take a close look at these statements while going through the examples

General Loop Format
Taking the above new statements, the general form of while loop is:

Examples
Lets now take a look at some examples.

pass
Pass is roughly to statements as None is to objects - an explicit nothing.

Just to reacall:

So, if your loop should do nothing forever, you can code it like this.

For the time being lets just be content with this useless use of pass. We will revisit this statement in further chapters (Functions and Classes)

continue

 * The continue statement causes an immediate jump to the top of a loop.
 * It also sometimes lets you avoid statement nesting


 * Program to print all even numbers less than 10 (without statement nesting):


 * While continue lets you avoid statement nesting, use it sparingly.
 * Too many continue statements in your program might make it difficult to decipher, as continue it jumping control from one part of program to another.

Following is the another version above program that does not use 'continue' (and more straightforward)


 * Program to print all even numbers less than 10 (with statement nesting):

break

 * The break statement causes an immediate exit from a loop
 * breakOnTime.py:
 * This program repeatedly (in a forever loop) accepts a name and age and prints them out.
 * If name entered is Time/time, it breaks out of the loop.

else

 * The loop else clause is run if the body of the loop is never executed, as you don't run a break in that event either
 * In a while loop, this happens if the test in the header is false to begin with.
 * When combined with the loop else clause, the break statement can often eliminate the need for the search status flags.


 * isPrime.py (by using loop else):


 * isPrime.py (by using if-else):

More on the loop else clause

 * The loop else clause is unique to Python and its inclusion can cause some confusion for some.
 * In a nutshell, the loop else clause provides explicit syntax for a common coding scenario:
 * Its a coding structure that lets you catch the "other" way out of a loop, without setting and checking flags or conditions

Lets compare and contrast using a simple program whose purpose is to loop though a list of names and find if the name 'God' exists or not.

Python way of the same program using loop else

for Loops

 * The for loop is a generic sequence iterator in Python.
 * Can step through the items in any ordered sequence object.
 * Works on
 * strings,
 * lists,
 * tuples,
 * other built-in iterables, and
 * user-defined objects (More on this in later chapters)

General Format
As in the case with the while loop, there are two ways we can use the for loop:

Just looping, no conditional checks, break, continue, else

Use conditional checks, break, continue, else


 * When Python runs a for loop,
 * It assigns the items in the sequence object () to the object one by one, and...
 * Executes the loop body for each
 * The loop body typically uses the assignment target to refer to the current item in the sequence (as though it were a cursor stepping through the sequence)

Other data types
for loop and string object

for loop and tuple object

Tuple assignment in for

 * In previous examples, we were using only one target object in the for loop.
 * BUT,the loop target can actually be a tuple of targets.
 * This is just another case of tuple-unpacking assignment at work.

Tuple-unpacking in a for loop

Nested for loops
 Needle in a haystack

Output


 * Note: The second for loop can be made redundant by using the in membership test operator.

Collecting common items in two sequences'

Output

Counter Loops: while and range

 * The range function is really a general tool that can be used in a variety of contexts.
 * Most often used to generate indexes in a for loop
 * But you can use it anywhere you need a list of integers

Nonexhaustive Traversals: range

 * If you just want to deal with each item in a sequence, then use the simple iteration scheme.
 * If only you need access to the index, use range in the for loop.
 * But if you want to skip items in a sequence as you loop, then you can use an extended form of range, that takes a steps argument.

Changing Lists: range
Another common place where you may use the range and for combination is in loops that change a list as it is being traversed.

Parallel Traversals: zip and map

 * zip
 * Built-in function allows us to use for loops to visit multiple sequences in parallel
 * Takes one or more sequences as arguments, and returns a list of tuples that pair up parallel items taken from those sequences.
 * Truncates result tuples at the length of the shortest sequence when the argument lengths differ.
 * map
 * Built-in function pairs items from sequences, like zip, but it pads shorter sequences with a None object if the argument lengths differ

Dictionary construction with zip
Suppose you have two list objects with keys and values respectively and you want to construct a dictionary object out of this, you can do so...

Generating Both Offsets and Items: enumerate

 * range function can be used to generate offsets of item in a sequence.
 * We can then use that offset to index an item of the sequence.
 * If we want both the index and item at the same time, we can use the enumarate type in Python.

Iterators: A First Look

 * File Iterators
 * Other Built-in Type Iterators
 * Other Iteration Contexts

Chapter 9: The Documentation Interlude
Documenting your operators plays a very important role for their maintainability. Python provides built-in documentation features (syntax and tools) that one should be aware of.


 * Python Documentation Sources
 * # Comments
 * The dir Function
 * Docstrings: __doc__
 * User-defined docstrings
 * Docstring standards
 * Built-in docstrings
 * PyDoc: The help Function
 * PyDoc: HTML Reports
 * Common Coding Gotchas

Chapter 10: Functions and Methods: (Not in a specific chapter, but very important)

 * Unlike other languages like C/C++ and Java, functions in Python are not magic constructs, but values.
 * Functions in Python are like integers in C.
 * They are values that can be passed to other functions/object constructors, and so forth.
 * Example:
 * def is the keyword used when defining functions.
 * Arguments are passed in parentheses just like C, and the return statement cannot return multiple values.
 * However, since lists, tuples, and dictionaries are basic types they can be returned instead.
 * They always return a value
 * If no return value is specified, or you don't use the return keyword, Python automatically returns the value None
 * Let's write a simple function called "map", which maps a function across a list, applying that function to each list element. I'm also going to illustrate recursion by writing a recursive and nonrecursive version of "map".
 * map.py:


 * Testing:


 * Now notice how a function, in this case increment is passed to map and rmap, just as if it were a number or some other data. Why is that?
 * Because functions are data in Python.
 * There is also a nice example of the difference between recursive and nonrecursive code in Python.
 * First form more intuitive, but the second form is more interesting.

Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:

Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result:

Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.

The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result:

Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]

Function Arguments
You can call a function by using the following types of formal arguments:
 * 1) Required arguments
 * 2) Keyword arguments
 * 3) Default arguments
 * 4) Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.

To call the function printme, you definitely need to pass one argument, otherwise it would give a syntax error as follows:

When the above code is executed, it produces the following result:

Traceback (most recent call last): File "test.py", line 11, in     printme; TypeError: printme takes exactly 1 argument (0 given)

Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme function in the following ways:

When the above code is executed, it produces the following result:

My string

Following example gives more clear picture. Note, here order of the parameter does not matter.

When the above code is executed, it produces the following result:

Name: miki Age 50

Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Following example gives an idea on default arguments, it would print default age if it is not passed:

When the above code is executed, it produces the following result:

Name: miki Age 50 Name: miki Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

The general syntax for a function with non-keyword variable arguments is this:

An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:

When the above code is executed, it produces the following result:

Output is: 10 Output is: 70 60 50

Functions vs. Methods
map(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the return values. For example, to compute some cubes:
 * Functions:
 * A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).
 * All data that is passed to a function is explicitly passed.
 * Methods:
 * A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.
 * It is implicitly passed the object for which it was called
 * It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)

Exercise 4: PrintBox
Since we just discussed functions, it's time to write some, don't you think? For this program you're going to draw a hollow box with a border of asterisks. You'll prompt the user for the width and height to use, and if they're valid, you'll simply draw the box. However, to get the job done you'll write a few functions: main -- this funtion will get the width and height values from the user, then pass them to the BoxNumsValid function. This function will return a value of TRUE if the values are legitimate, FALSE otherwise. If the values are okay, then the PrintBox function is called, passing the width and height values as arguments. BoxNumsValid -- this function will receive the width and height arguments from the caller and return a value of TRUE if they're okay, FALSE otherwise. What constitutes valid input? The width must be greater than or equal to one, but not greater than 79 (the default width of the putty screen), and the height just has to be a positive number (we don't care if the box rolls off the screen display). PrintBox -- this function receives from the caller the width and height of the box to draw. It can lean on the PrintRow function for support.


 * Please submit your answers in a _quiz1 file and email them to me.

Exercise 5: Fibonacci.py:
Mathematician Leonardo Fibonacci posed the following problem in his treatise Liber Abaci: "How many pairs of rabbits will be produced in a year, beginning with a single pair, if in every month each pair bears a new pair which becomes productive from the second month on?" In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: 0,1,1,2,3,5,8,13,21,34,55,89,144, ... or, alternatively, 1,1,2,3,5,8,13,21,34,55,89,144, ... By definition, the first two numbers in the Fibonacci sequence are 0 and 1 (alternatively, 1 and 1), and each subsequent number is the sum of the previous two. F_n = F_{n-1} + F_{n-2} with seed values F_0 = 0, F_1 = 1 in the first form; o

Exercise 5 Answer: Fibonacci.py
OR

Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example:

When the above code is executed, it produces the following result:

Inside the function local total : 30 Outside the function global total : 0

Keywords in Python

 * assert: Assert statements are a convenient way to insert debugging assertions into a program
 * lambda: Python’s lambda is a tool for building functions (or more precisely, function objects). That means that Python has two tools for building functions: def and lambda.
 * class: Is the most important keyword in object oriented programming. It is used to create new user defined objects.
 * continue: It is used to interrupt the current cycle, without jumping out of the whole cycle. New cycle will begin.
 * yield: is used with generators.

Just incase you want to learn binary

 * 0 is written as "0"
 * 1 is written as "1"
 * 2 is written as "10"
 * 3 is "11"
 * 4 is "100"
 * 5 is "101"
 * ...and so forth. Thus
 * 1029 is "10000000101" == 2**10 + 2**2 + 2**0 == 1024 + 4 + 1

The Bitwise Operators

 * x << y
 * Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
 * x >> y
 * Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
 * x & y
 * Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.
 * x | y
 * Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0, otherwise it's 1.
 * ~ x
 * Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
 * x ^ y
 * Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
 * Just remember about that infinite series of 1 bits in a negative number, and these should all make sense.

Exercise 6 (Final Project): ngram.py:
./python_Ngram.py Welcome to Ngram please choose of the following options: (1) have the output printed to the screen. (2) have the output printed to an outputfile. (3) exit. Enter the number: 1 Please enter the name of the file: testfile.txt Enter the N for N-grams you would like: 3

http://www.informationisbeautiful.net/visualizations/google-ngram-experiments/

http://books.google.com/ngrams

http://en.wikipedia.org/wiki/N-gram

Exercise 6 Answer: ngram.py

 * What is sys.argv?
 * sys.argv is a list in Python, which contains the command-line arguments passed to the script.
 * With the len(sys.argv) function you can count the number of arguments.
 * If you are gonna work with command line arguments, you probably want to use sys.argv. To use sys.argv, you will first have to import the sys module.


 * Example:

Note: sys.argv[0] is the name of the script.


 * Output:


 * If I run it again with additional arguments, I will get this output:

Concepts
Let’s show the sort of functionality that we are going to explore in this introductory tutorial by making use of the ls command:

The basics
Let us start with a very simple example which does (almost) nothing:

Following is a result of running the code: $ python prog.py $ python prog.py --help usage: prog.py [-h] optional arguments: -h, --help show this help message and exit $ python prog.py --verbose usage: prog.py [-h] prog.py: error: unrecognized arguments: --verbose $ python prog.py foo usage: prog.py [-h] prog.py: erro


 * Running the script without any options results in nothing displayed to stdout. Not so useful.
 * The second one starts to display the usefulness of the argparse module. We have done almost nothing, but already we get a nice help message.
 * The --help option, which can also be shortened to -h, is the only option we get for free (i.e. no need to specify it). Specifying anything else results in an error. But even then, we do get a useful usage message, also for free.

Introducing Positional arguments
An example:

And running the code: $ python prog.py usage: prog.py [-h] echo prog.py: error: the following arguments are required: echo $ python prog.py --help usage: prog.py [-h] echo positional arguments: echo optional arguments: -h, --help show this help message and exit

Here is what’s happening:
 * We’ve added the add_argument method, which is what we use to specify which command-line options the program is willing to accept. In this case, I’ve named it echo so that it’s in line with its function.
 * Calling our program now requires us to specify an option.
 * The parse_args method actually returns some data from the options specified, in this case, echo.
 * The variable is some form of ‘magic’ that argparse performs for free (i.e. no need to specify which variable that value is stored in). You will also notice that its name matches the string argument given to the method, echo.

Note: Although the help display looks nice and all, it currently is not as helpful as it can be. For example we see that we got echo as a positional argument, but we don’t know what it does, other than by guessing or by reading the source code. So, let’s make it a bit more useful:

And we get: $ python prog.py -h usage: prog.py [-h] echo positional arguments: echo   	echo the string you use here optional arguments: -h, --help show this help m

Now, how about doing something even more useful:

Following is a result of running the code: $ python prog.py 4 Traceback (most recent call last): File "prog.py", line 5, in          print args.square**2 TypeError: unsupported operand type(s) for ** or pow: 'str' and 'int'

That didn't go so well. That’s because argparse treats the options we give it as strings, unless we tell it otherwise. So, let’s tell argparse to treat that input as an integer:

Following is a result of running the code: $ python prog.py 4 16 $ python prog.py four usage: prog.py [-h] square prog.py: error: argument square: invalid int v

That went well. The program now even helpfully quits on bad illegal input before proceeding.

Quiz 4: Review
Please submit your answers _quiz4 files to my home directory (the folder is /home/mkarimi/python)

{what does the following code do? - defines a list and initializes it + defines a function, which does nothing - defines a function, which passes its parameters through - defines an empty class
 * type=""}

{ What is the output of the following code? +  -  -  -  - 
 * type=""}

{ What is the output of the following code? -  -  -  +  - 
 * type=""}

{ What should the following code print? +  -  -  -  - 
 * type=""}

{ What is the output of the below program? - syntax error - 4 - 5 + 6 - 7
 * type=""}

{ What gets printed? - 1 - 2 + 4 - 5 - 6
 * type=""}

{ What gets printed? #Note: NOT has first precedence, then AND, then OR - 1 - 2 + 3 - 4
 * type=""}

{ What gets printed? - 1 - 3 + 4 - 7 - none
 * type=""}

{ What gets printed? - new line then the string: woow - the text exactly like this: r"\nwoow" + the text like exactly like this: \nwoow - the letter r and then newline then the text: woow - the letter r then the text like this: nwoow
 * type=""}

{ What gets printed? - \x48\x49! - 4849 - 4849! -       48    49 + HI!
 * type=""}

{ What gets printed? - user - bill - password - hillary + Nothing. Python Syntax Error
 * type=""}

{ What gets printed? - st - sto + to - tor - Syntax Error
 * type=""}

{ What gets printed? - snow storm - snowXstorm - snow Xtorm + ERROR, this code will not run
 * type=""}

{ Which numbers are printed? - 2,4,6 - 0,1,2,4,5,6 + 0,1,4,5 - 0,1,4,5,6,7,8,9 - 1,2,4,5,6
 * type=""}

{ Which of the following print statements will print all the names in the list on a separate line + print "\n".join(names) - print names.join("\n") - print names.concatenate("\n") - print names.append("\n") - print names.join("%s\n", names)
 * type=""}

{ True or false? Code indentation must be 4 spaces when creating a code block? - True + False
 * type=""}

{ What gets printed? - 0 - 1 - 2 + 3 - 4
 * type=""}

{ What gets printed? - 1 - 2 - 7 + 10 - An exception thrown
 * type=""}

{ What gets printed? - 1 2 + 2 1 - An exception is thrown - This program has undefined behavior
 * type=""}

{ What gets printed assuming the user enters the following at the prompt? #:foo - f + foo - #:foo - A number - An exception is thrown
 * type=""}

{ What gets printed? - 1 - 4 + 5 - 8 - An exception is thrown
 * type=""}

{ What gets printed? - 15 + 51 - 150 - An exception is thrown
 * type=""}

Survey
If you get the chance please take a moment to answer some very short questions about Python 101 and my teachings. The survey is completely confidential and it does not ask for any information from you. It is merely designed to help me improve. https://www.surveymonkey.com/s/python101

© 2012 by Mohammad Karimi m.karimibox@gmail.com