User:Imirak

From WikiEducator
Jump to: navigation, search

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

Contents

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.

Chapter 1: Introduction to programming

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.

Introduction to Programming

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:
 .model tiny
 .code
 org 100h
 main  proc
      mov    ah,9       ; Display String Service
      mov    dx,offset hello_message    ; Offset of message (Segment DS is the right segment in .COM files)
      int    21h        ; call DOS int 21h service to display message at ptr ds:dx
      retn              ; returns to address 0000 off the stack 
                        ; which points to bytes which make int 20h (exit program)
 hello_message db 'Hello, world!$'
 main  endp
 end   main
  • 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:
#include <iostream.h>
main()
{
   cout << "Hello World!";
   return 0;
}
  • 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:
print "Hello World!"
  • 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.

Further Reading

  • The history of computing - Go through this if you are really interested in knowing about some in-depth concepts we glossed over in chapter 1


Chapter 2: Introduction to python/How python runs programs

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:
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}
  • Python
print "Hello, world!"


  • 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.

Chapter 3: How You Run Programs

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
Operation Interpretation
spam = ‘Spam’ Basic form
spam, ham = ‘yum’, ‘YUM’ Tuple assignment (positional)
[spam, ham] = [‘yum’, ‘YUM’] List assignment (positional)
a, b, c, d = ‘spam’ Sequence assignment, generalized
spam = ham = ‘lunch’ Multiple-target assignment
spams += 42 Argument assignment (equivalent to spams= spams + 42)
  • 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:
    • <var1> = <expr>
    • myVar = oldValue * foo + skip
  • Simultaneous Assignment:
    • <var1>, <var2>, … = <expr1>, <expr2>, …
    • a,b = b,a
  • Assigning Input:
    • input(<prompt>)
    • 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
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches 
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
#
print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
#
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (
    my_age, my_height, my_weight, my_age + my_height + my_weight)

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
'''
testing simple module writing
'''
version = 1.0
target = "education"
  • 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.
Escape Sequence Meaning
\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh


Chapter 4: Introducing Python Object Types

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.
  • 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.
Object Type Example literals/Creation Interpreter Mutable
Numbers 1234, 3.1415, 999L, 3+4j, Decimal width = 20; height = 5*9 No
Strings 'spam', "guido's" 'spam eggs' No
Lists [1, [2, 'three'], 4] a = ['spam', 'eggs', 100, 1234]; a[0] Yes
Dictionaries {'food': 'spam', 'taste': 'yum'} tel = {'jack': 4098, 'sape': 4139}; tel['guido'] = 4127 Yes
Tuples (1, 'spam', 4, 'U') t = (12345, 54321, 'hello!'); t[0] No
Files myFile = open('eggs', 'r') f.read(); f.readline() Yes
Other Types sets, types, None, Boolean Sets (Yes)
  • 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
user_input = raw_input("What’s your input: ")
try:
number = int(user_input)
break # stop while-loop
except ValueError:
print "that was no number: " + user_input
# implicite remain in while loop
------------------------------------------------------
>>> j = raw_input ("what is your name: ")
what is your name: 1
>>> type(j)
<type 'str'>
  • input assigns the input as the object
>>> j = input ("what is your name: ")
what is your name: "moe"
>>> j
'moe'
>>> j = input ("what is your name: ")
what is your name: moe
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'moe' is not defined
>>> type(j)
<type 'str'>
>>> j = input ("what is your name: ")
what is your name: 1
>>> type(j)
<type 'int'>

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 <username>_quadratic.py and email it to me
Exercise 1 Answer: quadratic.py
#!/usr/bin/python
 
from cmath import sqrt
from math import pow
 
a,b,c = input("what is (a,b,c): ")
 
 
x1 = (-b + sqrt(b*b - 4*a*c)) / (2*a)
x2 = (-b - sqrt(b*b - 4*a*c)) / (2*a)
 
print x1.real, x2.real

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.
Conversion Meaning Notes
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal. (1)
u Unsigned decimal.
x Unsigned hexadecimal (lowercase). (2)
X Unsigned hexadecimal (uppercase). (2)
e Floating point exponential format (lowercase). (3)
E Floating point exponential format (uppercase). (3)
f Floating point decimal format. (3)
F Floating point decimal format. (3)
g Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise. (4)
G Floating point format. Uses exponential format if exponent is greater than -4 or less than precision, decimal format otherwise. (4)
c Single character (accepts integer or single character string).
r String (converts any python object using repr()). (5)
s String (converts any python object using str()). (6)
 % No argument is converted, results in a "%" character in the result.

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:

>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
We are the knights who say "Ni!"

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.

>>> print '{0} and {1}'.format('spam', 'eggs')
spam and eggs
>>> print '{1} and {0}'.format('spam', 'eggs')
eggs and spam

Positional and keyword arguments can be arbitrarily combined:

>>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')
The story of Bill, Manfred, and Georg.

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 <username>_month.py and email it to me
Exercise 2 Answer: month.py:
# months is used as a lookup table
months = "JanFebMarAprMayJunJulAugSepOctNovDec"
 
n = input("Enter a month number (1-12): ")
 
# compute starting position of month n in months
pos = (n-1) * 3
 
# Grab the appropriate slice from months
monthAbbrev = months[pos:pos+3]
 
# print the result    
print "The month abbreviation is", monthAbbrev + "."

Quiz 1: Numbers and Strings

 S = “this is a string”
 Using S, how would you get the following to print on the Python 
 Interpreter without actually changing the assignment of S and/or introducing new variables.
 1) 16 ← Length of S
 2) t h i s ← note the space in between the characters.
 3) 'is a string'
 4) ' string string string' ← hint: note the space as the first character of this string
 5) 'zhis is a szring'
 6) 'THIS IS A STRING'
 7) What is polymorphism?
 8) Are strings Mutable? Why or Why not?
 ''Now for bonus question worth 2 points!!!''
 S = “This,is,a,string9) ['This', 'is', 'a', 'string']
  • Please submit your answers in a <username>_quiz1 file and email them to me.

Quiz 1 Answer: Numbers and Strings

1) len(s)
2) print S[0],S[1],S[2],S[3]
3) S[5:16]
4) S[9:16] * 3
5) 'z' + S[1:11] + 'z' + S[13:16] or S.replace('t','z')
6) S.upper() or S.swapcase()
7) using + to both add numbers to each other and concatenate strings and lists
8) No.  Because you can’t do something like S[1] = ‘Z’
9) S.split(',')

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]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
  • >>> L[20] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

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:
>>>stuff = {'name': 'Zed', 'age': 36, 'height': 6*12+2}
>>>print stuff['height']
>>>stuff['city'] = "San Francisco"
>>>print stuff['city']
>>>stuff[1] = "Wow"
>>>stuff[2] = "Neato"
>>>print stuff[1]
>>>Wow
>>>print stuff[2]
>>>Neato
>>>print stuff
 {'city': 'San Francisco', 2: 'Neato',
  'name': 'Zed', 1: 'Wow', 'age': 36,
  'height': 74}
>>>del stuff['city']
>>>del stuff[1]
>>>del stuff[2]
  • Example 2:
>>>record = {'name': {'first': 'Bugs', 'last': 'Bunny'},
             'age': 69,
             'race': 'Looney Toons',
             'friends': ['Daffy Duck', 'Elmer Fudd', 'Porky Pig']}
>>>record['name']['first']
>>>record['friends'].append('Michael Jordan')
>>>Ks = record.keys()
>>>record.has_key(‘age’)
>>>Ks.sort()

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.
birds = { "yellow-nosed albatross" :  "Tristan da Cunha",
          "indigo bunting"  :  "Mexico",
          "Scott's oriole"  :  "California",
          "common yellowthroat"  :  "Central America" }
Homework: Solution
import random
 
birds = { "yellow-nosed albatross" :  "Tristan da Cunha", "indigo bunting"  :  "Mexico", 
    "Scott's oriole"  :  "California", "common yellowthroat"  :  "Central America" }
 
random_key = random.choice(birds.keys())
 
print "%s, %s" %(random_key, birds[random_key])

Tuples

  • Roughly like a list (can hold sequence of arbitrary objects)
  • ...But cannot be changed once created (Immutable like string)
T = (1,2,3,4)

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

fo = open('data.txt', 'w')
  • 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.
fo.write('Hello\n')
fo.write('world\n')
fo.close()
  • This creates a file in the current directory and writes text to it.
  • Alternatively you can open a file using the keyword with
with open("README","r") as fo:
    fo.write("hello world")

Reading an existing file

try:
    fo = open('/var/log/messages','r')
    try:
        line = fo.readline()
    finally:
        fo.close()
except IOError:
    print "cannot open 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
try:
    with open("/var/log/messages","r") as fo:
        data = fo.read()
except IOError:
    print "cannot open file"

Other operations

  • dir(file)
  • help(file.write)

Example

  • filesReadWrite.py

Other Types

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
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket)           	# create a set without duplicates
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit             	# fast membership testing
True
>>> 'crabgrass' in fruit
False
>>> # Demonstrate set operations on unique letters from two words
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                              	# unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b                          	# letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                          	# letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                          	# letters in both a and b
set(['a', 'c'])
>>> a ^ b                          	# letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
  • Example 2
>>> engineers = set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
>>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
>>> employees = engineers | programmers | managers       	# union
>>> engineering_management = engineers & managers        	# intersection
>>> fulltime_management = managers - engineers - programmers # difference
>>> engineers.add('Marvin')                              	# add element
>>> print engineers
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
>>> employees.issuperset(engineers) 	# superset test
False
>>> employees.update(engineers)     	# update from another set
>>> employees.issuperset(engineers)
True
  • Booleans
    • 1 < 2 => 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 <username>_quiz2 file and email it to me.

Quiz 2 Answer: Object Types

1. Positionally ordered collection of other objects from left-to-right.  lists, tuples, and strings
2. Mappings are also collections of other objects, but they store objects by key (instead of by relative position).  dictionaries
3. L = [5.2,’Alex’,11,’soccer’,7.5,’Alex’,461]
    a. L.count()
    b. L.insert(11,4)
    c. L.__str__() or str(L)
    d. L.remove(11)
4. Here you want to use a dictionary
    a. employee = {'firstname':None, 'lastname':None, 'deptID':None, 'email':None, 'room':None, 'dateStarted':None, 
            'dateEnded':None}
    b. emplyee['active'] = True
    c. employee = {'firstname': 'Mo', 'lastname': 'Karimi'}

Chapter 5: Dynamic Typing

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

>>> a = 3
  • 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

>>>>> a = 3
>>>>> a = 'spam'
>>>>> a = 1.23

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?
>>>>> a = 3
>>>>> a = 'spam'
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

>>> a = 3
>>> b = a
>>> a = 'spam'
>>> a = 3
>>> b = a
>>> a, b
   (3, 3)
>>> a = a + 2
>>> a, b
   (5, 3)

Shared References and In-Place Changes

>>> L1 = [2, 3, 4]
>>> L2 = L1
>>> L2 = 24
>>> L1 = [2, 3, 4]
>>> L2 = L1
>>> L1[0] = 24
>>> L1
>>> L2
>>> L1 = [2, 3, 4]
>>> L2 = L1[:] 	# Make a copy of L1
>>> L1[0] = 24
>>> L1
>>> L2
>>> import copy
>>> X = [1,2,3]
    Y = copy.copy(X)    	# Make a top-level "shallow" copy of any object Y
    Y = copy.deepcopy(X)	# Make a deep copy of any object Y: copy all nested parts
    Y == X
        True
    Y is X
        False

Shared References and Equality

  • Garbage-collection behavior
>>> x = 42
>>> x = 'Foosball'	# Reclaim 42 now?

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

>>> L = [1, 2, 3]
>>> M = L	     # M and L reference the same object
>>> L == M   # Same value
True
>>> L is M   # Same object
True

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

>>> L = [1, 2 ,3]
>>> M = [1, 2 ,3]	# M and L reference different objects
>>> L == M	# Same values
True
>>> L is M	        # Different objects
False

Above operations on small numbers (Behavior is different)

>>> X = 42
>>> Y = 42  # Should be two different objects (but NOT!)
>>> X == Y
True
>>> X is Y	# Same object because 42 is reused, since its a http://en.wikipedia.org/wiki/Flyweight_pattern
True

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
>>> import sys
>>> sys.getrefcount(1)	# ??? pointers to this shared piece of memory
287
>>> sys.getrefcount(2)
77
>>> sys.getrefcount(0)
260
>>> i = 1            	# Python checks if there exists a cached object
>>> sys.getrefcount(1)
288                  	# And, yes it does reuse the object 1

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 <username>_quiz3 and email it to me.

Quiz 3 Answer: Exercise reading from file
#!/usr/bin/python
user_info_dict = {}
fo = open('/home/mkarimi/testfile','r')
 
for line in fo.readlines():
     line = line.strip()
     user_info_dict[line.split(':')[0]] = line.split(':')[1].strip()
 
print user_info_dict

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)
Statement Role Example
Assignment Creating References a,b,c = ‘good’, ‘bad’, ‘ugly’
calls Running functions log.write(“Spam, ham\n”)
print Printing objects print ‘The Killer’, joke
if/elif/else Selecting actions if “python” in text: print text
for/else Sequence iteration for x in mylist: print x
while/else General loops while X > Y: print 'hello'
pass Empty placeholder while True: pass
break, continue Loop jumps while True: if not line: break
try/except/finally Catching exceptions try: action()
raise Triggering exceptions raise endSearch, location
import, from Module access import sys OR from sys import stdin
def, return, yield Building functions def f(a, b, c=1, *d):
class Building objects class subclass(superclass):
global Namespaces global x, y
del Deleting references del data[k]
exec Running code strings exec “import “ + modName
assert Debugging checks assert X > Y
with/as Context managers (2.6) with open(‘data’) as myfile:


  • A Tale of Two ifs
    • Other C-like languages:
if (x>y) {
    x = 1;
    y = 2;
}


  • Python
if x > y:
    x = 1
    y = 2
  • 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 ({ })
mlist = [111, 222, 333]
X = (A + B + 
     C + D)

OR

if (A == 1 and
    B == 2 and
    C == 3)
  • 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
while True:
    reply = raw_input(‘Enter text: ‘)
    if reply == ‘stop’:
        break
    elif not replay.isdigit():
        print ‘Bad!’ * 8
    else:
        num = int(reply)
        if num < 20:
            print ‘low’
        else:
            print num ** 2
print ‘Bye’

Chapter 7: If test

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.

General Format

#The general form of an ''if'' statement
if <test1>:       	# if test
    <statements1> 	# Associated block
elif <test2>:     	# Optional elifs
    <statements2>
else :            	# Optional else
    <statements3>

When the if statement runs

  • Python executes the block of code associated with the first test that evaluates to true
  • The else block is executed if all tests prove false.




Basic Examples

  • Simplest possible if statement
>>> if 1:          	# 1 is Boolean true.
        print 'true'
    true
  • We can also use the built-in True Boolean object
>>> if True:
        print 'true'
    true
Note
The if statements above always succeed.
  • To handle a false result, code else
>>> if not True:     	# if test fails since, '''not True''' is False
        print 'true'
    else:
        print 'false'
    false


  • An example using an arithmetic expression
>>> x = 10
>>> if x > 0:                  	# '''10 > 0 is True'''
        print "Positive number"
    else:
        print "Number is zero or negative"
    Positive number
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.
'''Multiway branching using if-elif-else'''
>>> toon = 'killer rabbit'
>>>
>>> if toon == 'roger':
         print "How's jessica?"
    elif toon == 'bugs':
         print "What's up doc?"
    else:
         print 'Run away! Run away! Ahhhhhhhhhhhhhhhhhh'
 Run away! Run away! Ahhhhhhhhhhhhhhhhhh
Note
The words if, elif, and else are associated by the fact that they line up vertically, with same indentation.
'''Multiway branching by indexing dictionaries'''
>>> choice = 'fries' 
>>>
>>> menu = { 'burger': 4.00,
            'fries':  2.50,
            'softy': 1.75,
            'soda':  1.25 }
>>> print menu[choice]
2.50
  • The above example is only doing the if-elif-elif tests and not the else test.
  • The following example does the else test, which handles the case when all tests fail.
>>> notAvailable = 'Sorry!! We are not serving this item.'
>>>
>>> choice = 'fries'
>>>
>>> menu = { 'burger': 4.00,
           'fries':  2.50,
           'softy': 1.75,
           'soda':  1.25 }
>>> print menu.get(choice, notAvailable)
2.50
>>>
>>> choice = 'soda'
>>> print menu.get(choice, notAvailable)
1.25
>>>
>>> choice = 'happy meal'
>>> print menu.get(choice, notAvailable)
Sorry!! We are not serving this item.

Equivalent, but more verbose example using if statement

>>> notAvailable = 'Sorry!! We are not serving this item.'
>>>
>>> choice = 'happy meal'
>>>
>>> if choice == 'burger':
         print 4.00
     elif choice == 'fries':
         print 2.50
     elif choice == 'softy':
         print 1.75
     elif choice == 'soda':
         print 1.25
     else:
         print notAvailable
Sorry!! We are not serving this item.
  • As you will see in later chapters, dictionaries can also contain functions to implement advanced multiway branching techniques.
Tip
As a rule of thumb in coding, when in doubt, err on the side of simplicity and readability.

Python Syntax Rules

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 <username>_temperature.py and email it to me
Exercise 3 Answer: temperature.py
#!/usr/bin/python
 
while True:
    choice = raw_input('Press C to convert Celsius to Fahrenheit\nPress F to convert Fahrenheit to Celsius: ')
 
    if choice.lower() == 'c':
    	while True:
    	    try:
                c = input('what is the temperature in Celsius? ')
                temp = (c * (9.0 / 5.0)) + 32
                print "%.2f in Celsius == %.2f in Fahrenheit" %(c, temp)
            except NameError:
                print "user didn't enter a number"
                continue
            break
        break
    elif choice.lower() == 'f':
    	while True:
            try:
                f = input('what is the temperature in Fahrenheit? ')
                temp = (f - 32) * (5.0 / 9.0)
                print "%.2f in Fahrenheit == %.2f in Celsius" %(f, temp)
            except NameError:
                print "user didn't enter a number"
                continue    
            break
        break
    else:
        print "Please enter either F or C."

Chapter 8: while and for Loops

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.

while <test>:            	# Loop test
    <statement1>         	# Loop body
    <statement2>        	 
else:                    	        # Optional else
    <statement3>         	# Runs if the loop was not exited using a break statement
    <statement4>

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

while <test>: <statement1>
else: <statement2>

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

Examples

Infinite loop
while True:
     print "Type CTRL+C to stop
Loop until user enters 'stop'
# get input from user and remove whitespace
input = raw_input('--> ').strip()
while input != 'stop':
    print input
    input = raw_input('--> ').strip()
else:
    print 'User entered %s' % (input)
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.
input = raw_input('--> ')
while input:
    print input
    input = input[1:]

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:

while <test1>:
    <statements1>
    if <test2>: break      	# Exit enclosing loop now, skip else
    if <test3>: continue   	# Go to top of enclosing loop now, to test1
         <statements2>          	# will Run if test2 and test3 were false
    else:
         <statements3>          	# Run if we didn't hit a 'break'

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:

sph = None
if sph is None: print "Select an obje"

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

while True: pass

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)
number = 10
while number:
    number = number - 1
    if (number % 2) != 0: continue	# if 'number' is odd, skip the print statement below
    print number
  • 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)
number = 10
while number:
    number = number - 1
    if (number % 2) == 0:
    print number
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.
while True:
    name = raw_input('Enter name: ').strip()
    if name in ('Time', 'time'):
        print('Time is ageless.. breaking out of loop..')
        break
    age = raw_input('Enter age:')
    print('Hello', name, '=>', int(age))
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)
number = int(raw_input("Enter number: "))
 
quotient = number / 2
 
while quotient > 1:
	if number % quotient == 0:
   	    print number, ' has factor ', quotient
   	    break
	quotient = quotient - 1
else:
	print number, 'is prime'
isPrime.py (by using if-else)
number = int(raw_input("Enter number: "))
 
quotient = number / 2
 
if quotient == 1:
	print number, 'is prime'
else:
	while quotient > 1:
   	    if number % quotient == 0:
       	        print number, 'has factor', quotient
       	        break
   	quotient = quotient - 1

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.

'''This is how you would code it in other languages <br /> which do not support ''loop else'''''
found = False
 
names = ['Adam', 'God', 'Eve']
 
while names and not found:
	if names[0] == 'God':
   	print "What's up God!!"
   	found = True
	else:
   	names = names[1:]
if not found:
	print "Where art thou God?"

Python way of the same program using loop else

names = ['Adam', 'God', 'Eve']
 
while names:
	if names[0] == 'God':
   	print "What's up God!!"
   	break
	names = names[1:]
else:
	print "Where art thou God?"

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

for <target> in <iterable-object>: 	# assign iterable-object items to target
	<statements>                   	# Repeated loop body: use target

Use conditional checks, break, continue, else

for <target> in <iterable-object>: 	# assign iterable-object items to target
	<statements>                   	# Repeated loop body: use target
	if <test1>: break              	# Exit loop now, skip else
	if <test2>: continue           	# Goto top of loop now
else:
	<statements>                   	# If we did not hit a 'break'
  • When Python runs a for loop,
  1. It assigns the items in the sequence object (<iterable-object>) to the <target> object one by one, and...
  2. 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)

Examples

Basic usage

>>> for eatable in ['Burger', 'Fries', 'Potato Wedges']
...	print "Devouring %s" % (eatable)
...
>>> sum = 0
>>> for number in [1, 2, 3, 4]:
...	sum = sum + number
...
>>> sum
10
>>> product = 1
>>> for number in range(1, 5):
...	product *= number
...
>>> product
24
Other data types

for loop and string object

>>> name = 'Python: Batteries included!!'
>>>
>>> for character in name:
...	print character
...
P y t h o n :   B a t t e r i e s   i n c l u d e d ! !

for loop and tuple object

>>> doNotRearrange = ('Day', 'Afternoon', 'Evening')
>>>
>>> for item in doNotRearrange:
... 	print item,
...
Day Afternoon Evening
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

>>> listOfNames = [('Bugs', 'Bunny'), ('Daffy', 'Duck'), ('Mickey', 'Mouse')]
>>>
>>> for (firstName, lastName) in listOfNames:
...	print firstName, lastName
...
Bugs Bunny
Daffy Duck
Mickey Mouse
Nested for loops

Needle in a haystack

#!/usr/local/bin/python
#needleInHaystack.py
 
haystack = ['Food', 'Magazines', ('Purse', 32), 'Katana', ('Key', 'Lock')]
 
needles = ['Katana', ('Key', 'Lock'), ('Purse', 54)]
 
for needle in needles:
	for thing in haystack:
   	if thing == needle:
       	print needle, "was found in haystack"
       	break
	else:
   	print needle, "was NOT found in haystack"

Output

linux:~> python needleInHaystack.py
 
Katana was found in haystack
('Key', 'Lock') was found in haystack
('Purse', 54) was NOT found in haystack


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

Collecting common items in two sequences'

#!/usr/local/bin/python
# nestedForLoops.py
 
sequence1 = "Tomato"
sequence2 = "Potato"
 
commonCharacters = []
 
for character in sequence1:
	if character in sequence2:
   	commonCharacters.append(character)
 
print commonCharacters


Output

linux:~> python nestedForLoops.py
['o', 'a', 't', 'o']

Loop Coding Techniques

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


0 to upperBound-1

>>> range(5)
[0, 1, 2, 3, 4]


lowerBound to upperBound-1

>>> range(2,5)
[2, 3, 4]
>>> range(-5, 5)
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

with step of ...

>>> range(0, 10, 2)
[0, 2, 4, 6, 8]
>>> range(5, -5, -1)
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]



Using range in for loops

>>> for index in range(3):
... 	print index, 'Atoms'
...
0 Atoms
1 Atoms
2 Atoms

Using range to iterate over a sequence indirectly

>>> place = 'Bali'
>>> for index in range(len(place)):
... 	print place[index]
...
B a l i

Using while to iterate over sequence directly

>>> index = 0
>>> while index < len(place):
... 	print place[index]
... 	index += 1
...
B a l i

BUT, Python for loop does the indexing for us

>>> for character in place:
... 	print character,
... 
B a l i

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.


Use

>>> S = 'abcdefghijk'
>>> for item in S:
... 	print item


Avoid

>>> for index in range(len(S)):
... 	print S[index]

Extended form of range

>>> for index in range(0, len(S), 2):
... 	print S[index]
...
a c e g i k

Python best practice is to use extended three-limit form of the slice expression

>>> for item in S[::2]:
... 	print item

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.

>>> L = [1, 2, 3, 4, 5]
>>>
>>> for index in range(len(L)):
... 	L[index] += 1
... 
>>> L
[2, 3, 4, 5, 6]

If you try it the normal way, you will not get expected result

>>> L = [1, 2, 3, 4, 5]
>>> for x in L:
... 	x += 1
...
>>> L
[2, 3, 4, 5, 6]

Using while loop also we can get a similar result

>>> L = [1, 2, 3, 4, 5]
>>>
>>> index = 0
>>> while index < len(L):
... 	L[index] += 1
... 	index += 1
...
>>> L
[2, 3, 4, 5, 6]


While loops in cases like these run slower than corresponding for loops.








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


>>> L1 = [1,2,3,4] 
>>> L2 = [5,6,7,8]
>>>
>>> zip(L1, L2)
[(1, 5), (2, 6), (3, 7), (4, 8)]
>>> for (l1, l2) in zip(L1, L2):
...	print l1, '+', l2, '=', l1+l2
...
1 + 5 = 6
2 + 6 = 8
3 + 7 = 10
4 + 8 = 12


>>> T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)
>>>
>>> T3
(7, 8, 9)
>>>
>>> zip(T1, T2, T3)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]


>>> S1 = 'abc'
>>> S2 = 'xyz123'
>>>
>>> zip(S1, S2)
[('a', 'x'), ('b', 'y'), ('c', 'z')]
>>> map(None, S1, S2)
[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None, '3')]




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...


Using dict() constructor call and zip

 >>> keys = ['scenes', 'objects', 'images']
 >>> values = [['Scene.001', 'Scene.002'],
 ... ['Cube.001', 'Sphere.001', 'Cylinder.001'],
 ... ['sideView,jpg', 'topView.jpg', 'frontView.jpg']]
 >>>
 >>> library1 = dict(zip(keys, values))
 >>>
 >>> library1
 




Using zip and for loop

 >>> keys = ['scenes', 'objects', 'images']
 >>> values = [['Scene.001', 'Scene.002'],
 ... ['Cube.001', 'Sphere.001', 'Cylinder.001'],
 ... ['sideView,jpg', 'topView.jpg', 'frontView.jpg']]
 >>>
 >>> library1 = {}
 >>>
 >>> for (key, value) in zip(keys, values):
 ... 	library1[key] = value
 ...
 >>> library1

Using the dict() call is the easiest way.


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.


Enumerate example

 name = 'Samsung'

 for (index, character) in enumerate(name):
     print character, "is at index", index


The same program without using enumerate

 name = 'Samsung'
 index = 0

 for character in name:
     print character, "is at index", index
     index += 1


Output

 S is at index 0
 a is at index 1
 m is at index 2
 s is at index 3
 u is at index 4
 n is at index 5
 g is at index 6












More on enumerate

 >>> e = enumerate(range(5))
 >>> e
 <enumerate object at 0x2b94a453c5f0>
 >>> e.next()
 (0, 0)
 >>> e.next()
 (1, 1)
 >>> e.next()
 (2, 2)
 >>> e.next()
 (3, 3)
 >>> e.next()
 (4, 4)
 >>> e.next()
 Traceback (most recent call last):
 File "<stdin>", line 1, in ?
 StopIteration

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:
# hello.py
def hello():
    print "Hello World!"
  • 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:
# We can use append here
def map( fun, list ):
    nlist = []
    for item in list:
        nlist.append( fun( item ) )
        return nlist
# But here we have to use concatenation, or the + operator for lists.
def rmap ( fun, list ):
    if list == []:
        return []
    else:
        return [fun( list[0] )] + rmap( fun, list[1:] )
# Make a sample test fu
  • Testing:
# Test them out!
map( increment, [1,2,3,4,5] )
# should return [2,3,4,5,6]
map( increment, [1,2,3,4,5] ) == rmap( increment, [1,2,3,4,5] )
# Their outputs should
  • 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:

#!/usr/bin/python
 
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist.append([1,2,3,4]);
   print "Values inside the function: ", mylist
   return
 
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

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.

#!/usr/bin/python
 
# Function definition is here
def changeme( mylist ):
   "This changes a passed list into this function"
   mylist = [1,2,3,4]; # This would assig new reference in mylist
   print "Values inside the function: ", mylist
   return
 
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

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:

#!/usr/bin/python
 
# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str;
   return;
 
# Now you can call printme function
printme();

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

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    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:

#!/usr/bin/python
 
# Function definition is here
def printme( str ):
   "This prints a passed string into this function"
   print str;
   return;
 
# Now you can call printme function
printme( str = "My string");

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.

#!/usr/bin/python
 
# Function definition is here
def printinfo( name, age ):
   "This prints a passed info into this function"
   print "Name: ", name;
   print "Age ", age;
   return;
 
# Now you can call printinfo function
printinfo( age=50, name="miki" );

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:

#!/usr/bin/python
 
# Function definition is here
def printinfo( name, age = 35 ):
   "This prints a passed info into this function"
   print "Name: ", name;
   print "Age ", age;
   return;
 
# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );

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:

def functionname([formal_args,] *var_args_tuple ):
   "function_docstring"
   function_suite
   return [expression]

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:

#!/usr/bin/python
 
# Function definition is here
def printinfo( arg1, *vartuple ):
   "This prints a variable passed arguments"
   print "Output is: "
   print arg1
   for var in vartuple:
      print var
   return;
 
# Now you can call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );

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

Output is:
10
Output is:
70
60
50

Functions vs. Methods

  • 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)
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:
>>>def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216,
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.25), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.s

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 <username>_quiz1 file and email them to me.

Exercise 4 Answer: PrintBox

#include<stdio.h>
#include<stdbool.h>
 
void PrintBox (int width, int height)
{
/*
 * user PrintRow if necessary to draw the boxes 
 * */
     int i,j;
 
     for (i=0; i<height; i++) //rows
     {
 
         for (j=0; j<width; j++) //height
         {
              if (j== 0 || j == width-1 || i == 0 || i == height-1)
              {
                  printf("*");
              }
              else{printf(" ");}
         }   
         printf("\n");
     }
}
 
bool BoxNumValid(int width, int height)
{
/*
 * 1) check that the values are true
 *     if 1 <= width < 79
 *     and if height > 0
 * */
        if (width >= 1 && width <79)
        {
            if (height > 0)
            {
                return true;
            }
            else {return false;}
        }
        else {return false;}
}
 
 
int main(void)
{
/*
 *   1) this function will get the width and height from user
 *   2) BoxNumsValid(width, height)
 *   3) if true:
 *        PrintBox(width, height)
 *      else:
 *        "didn't get the right stuff"
 * */
        int w,h;
        printf("Please input an integer value width and height: ");
        scanf("%d %d", &w,&h);
        printf("You entered: %d %d\n", w,h);
        if (BoxNumValid(w,h))
        {
            //"You entered the correct width and height!!!
            PrintBox(w,h);
        }
        else {printf("You entered the incorrect width and height!!!\n");}
        return 0;
}

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
Interpreter
>>> import testfib
>>> testfib.fib(2)
1
>>> testfib.fib(7)
13
>>> testfib.fib(8)
21
Exercise 5 Answer: Fibonacci.py
def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return f(n-1)+f(n-2)

OR

N = input("Which iteration? ")
a = 0
b = 1
count = 0
max_count = N
 
while count <= N:
    count = count + 1
    old_a = a
    old_b = b
    a = old_b
    b = old_a + old+b

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:

#!/usr/bin/python
 
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
   # Add both the parameters and return them."
   total = arg1 + arg2; # Here total is local variable.
   print "Inside the function local total : ", total
   return total;
 
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total

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

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

Revised Temperature.py

#!/usr/bin/python
 
def temperature(choice, temp):
 
  while True: 
    if choice.lower() == 'c':
        while True:
            try:
 
                result = (temp * (9.0 / 5.0)) + 32
                print "%.2f in Celsius == %.2f in Fahrenheit" %(temp, result)
            except NameError:
                print "user didn't enter a number"
                continue
            break
        break
    elif choice.lower() == 'f':
        while True:
            try:
 
                result = (temp - 32) * (5.0 / 9.0)
                print "%.2f in Fahrenheit == %.2f in Celsius" %(temp, result)
            except NameError:
                print "user didn't enter a number"
                continue    
            break
        break
    else:
        print "Please enter either F or C."

Keywords in Python

Keywords Examples Keywords Examples

and


or


assert


break


class


continue


def


del


yield


except

if age < 55 and sex == "M":


if (answer != 'yes' or answer != 'no'):


assert salary > 0


if (val == 22): break


class Square:


while (num < 1000): continue


def root(x):


del a[:2]


def gen(): yield x


except IOError:

in


is


as


lambda


pass


raise


from


return


finally


exec

for i in range(10):


print None is None


import random as rnd


a = lambda x: x * x


def function(): pass #does nothing


raise YesNoException


from sys import version


return x * x


finally: f.close()


exec("for i in [1, 2, 3, 4, 5]: print i,")


  • 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.


Python Expression Operators and Precedence

Operators Description

x or y


x and y


not x


x < y, x <= y, x > y, x >= y,


x == y, x <> y, x != y, x is y, x is not y,


x in y, x not in y


x | y


x ^ y


x & y


x + y


x - y


x * y


x % y


x / y


-x


+x


x ** y


x[i]


x[i:j]


x.attr


x(...)


(...)


[...]


{...}


`...`

Logical OR (y is evaluated only if x is false)


Logical AND (y is evaluated only if x is true)


Logical negation


Comparison operators


Value equality operators


Object identity tests, sequence membership


Bitwise OR


Bitwise eXclusive OR


Bitwise AND


Addition/Concatenation


Subtraction


Multiplication/repetition


Remainder/format


Division


Unary negation


Identity


Power


Indexing


Slicing


Qualification


Function calls


Tuple


List


Dictionary


Conversion to string


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

 

Chapter 11: Command-line arguments

sys.argv

import sys
print sys.a
  • 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:
import sys
print "This is the name of the script: ", sys.argv[0]
print "Number of arguments: ", len(sys.argv)
print "The arguments are: " , str(sys.argv)

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

  • Output:
This is the name of the script:  sysargv.py
Number of arguments in:  1
The arguments are:  ['sysargv.py']
  • If I run it again with additional arguments, I will get this output:
This is the name of the script:  sysargv.py arg1 arg2
Number of arguments in:  3
The arguments are:  ['sysargv.py', 'arg1', 'arg2']

argparse

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:

$ ls
cpython  devguide  prog.py  pypy  rm-unused-function.patch
$ ls pypy
ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
$ ls -l
total 20
drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
drwxr-xr-x  4 wena wena 4096 Feb  8 12:04 devguide
-rwxr-xr-x  1 wena wena  535 Feb 19 00:05 prog.py
drwxr-xr-x 14 wena wena 4096 Feb  7 00:59 pypy
-rw-r--r--  1 wena wena  741 Feb 18 01:01 rm-unused-function.patch
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default.
Sort entries alphabetically if none of -cftuvSUX nor --sort is

The basics

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

import argparse
parser = argparse.ArgumentParser()
parser.parse_

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:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo

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:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print args.echo

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:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number")
args = parser.parse_args()
print args.square**2

Following is a result of running the code:

$ python prog.py 4
Traceback (most recent call last):
    File "prog.py", line 5, in <module>
         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:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number", type=int)
args = parser.parse_args()
print args.square**2

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 <username>_quiz4 files to my home directory (the folder is /home/mkarimi/python)

Point added for a correct answer:  
Points for a wrong answer:
Ignore the questions' coefficients:

1. what does the following code do?

>>> def a(b, c, d): pass
defines a list and initializes it
defines a function, which does nothing
defines a function, which passes its parameters through
defines an empty class

2. What is the output of the following code?

>>>print type(1/2)
<type 'int'>
<type 'number'>
<type 'float'>
<type 'double'>
<type 'tuple'>

3. What is the output of the following code?

>>>print type([1,2])
<type 'int'>
<type 'set'>
<type 'complex'>
<type 'list'>
<type 'tuple'>

4. What should the following code print?

>>>print type(1J)
<type 'complex'>
<type 'unicode'>
<type 'float'>
<type 'int'>
<type 'decimal'>

5. What is the output of the below program?

>>>a = [1,2,3,None,(),[],]
>>>print len(a)
syntax error
4
5
6
7

6. What gets printed?

>>>nums = set([1,1,2,3,3,3,4])
>>>print len(nums)
1
2
4
5
6

7. What gets printed? #Note: NOT has first precedence, then AND, then OR

>>>x = True 
   y = False
   z = False
   if not x or y:
       print 1
   elif not x or not y and z:
       print 2
   elif not x or y or not y and x:
       print 3
   else:
       print 4
1
2
3
4

8. What gets printed?

>>>counter = 1
   def doLotsOfStuff():
       global counter
       for i in (1, 2, 3):     
           counter += 1
   doLotsOfStuff()
   print counter
1
3
4
7
none

9. What gets printed?
>>>print r"\nwoow"
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

10. What gets printed?
>>>print "\x48\x49!"
\x48\x49!
4849
4849!
48 49
HI!

11. What gets printed?

>>>kvps  = {"user","bill", "password","hillary"}
>>>print kvps['password']
user
bill
password
hillary
Nothing. Python Syntax Error

12. What gets printed?

>>>name = "snow storm"
>>>print "%s" % name[6:8]
st
sto
to
tor
Syntax Error

13. What gets printed?

>>>name = "snow storm"
>>>name[5] = 'X'
>>>print name
snow storm
snowXstorm
snow Xtorm
ERROR, this code will not run

14. Which numbers are printed?

>>>for i in  range(2):
       print i
>>>for i in  range(4,6):
       print i
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

15. Which of the following print statements will print all the names in the list on a separate line

>>>names = ['Ramesh', 'Rajesh', 'Roger', 'Ivan', 'Nico']
print "\n".join(names)
print names.join("\n")
print names.concatenate("\n")
print names.append("\n")
print names.join("%s\n", names)

16. True or false? Code indentation must be 4 spaces when creating a code block?

>>>if error:
       # four spaces of indent are used to create the block
       print "%s" % msg
True
False

17. What gets printed?

>>>country_counter = {} #empty dictionary
   def addone(country):
       if country in country_counter:
           country_counter[country] += 1
       else:
           country_counter[country] = 1
   addone('China')
   addone('Japan')
   addone('china')
   print len(country_counter)
1
2
3
4

18. What gets printed?

>>>kvps = { '1' : 1, '2' : 2 } #kvps dictionary
   theCopy = kvps
   kvps['1'] = 5
   sum = kvps['1'] + theCopy['1']
   print sum'''
1
2
7
10
An exception thrown

19. What gets printed?

>>>a = 1
   b = 2
   a,b = b,a
   print "%d %d" % (a,b)
1 2
2 1
An exception is thrown
This program has undefined behavior

20. What gets printed assuming the user enters the following at the prompt? #:foo

>>>a = raw_input("#: ")
   print a
f
foo
#:foo
A number
An exception is thrown

21. What gets printed?

>>>def addItem(listParam):
       listParam += [1]
   mylist = [1, 2, 3, 4]
   addItem(mylist)
   print len(mylist)
1
4
5
8
An exception is thrown

22. What gets printed?

>>>kvps = { '1': 1, '2': 2 , '3': 3, '4': 4, '5': 5 }"
   newData = { '1': 10, '3': 30 }"
   kvps.update(newData)
   x = sum(kvps.values())
   print x
15
51
150
An exception is thrown

Your score is 0 / 0


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