Updated document.txt

grymoire authored
revision c40a80827bfef38d37bfc0f93993aa07a11d8d5b
## **Print Stuff** (Python Essential References)
1. print year, principal
2. print "%3d %0.2f" % (year, principal)
3. print format(year,"3d"),format(principal,"0.2f")
4. print "{0:3d} {1:0.2f}".format(year,principal)

## **File** (Python Essential References)
- Read File:
f = open("foo.txt") # Returns a file object
line = f.readline() # Invokes readline() method on file
while line:
print line, # trailing ',' omits newline character
print(line,end='') # Use in Python 3
line = f.readline()

- Write File:
1. f = open("out","w") # Open file for writing
while year <= numyears:
principal = principal * (1 + rate)
print >>f,"%3d %0.2f" % (year,principal)
//f.write("%3d %0.2f¶
" % (year,principal))
year += 1
2. import sys
sys.stdout.write("Enter your name :")
name = sys.stdin.readline()
3. name = raw_input("Enter your name :")

- Triple-quoted strings are useful when the contents of a string literal span multiple lines of text.

- Strings are stored as sequences of characters indexed by integers, starting at zero.

- Although str() and repr() both create strings, their output is usually slightly different.
str() produces the output that you get when you use the print statement,
whereas repr() creates a string that you type into a program to exactly represent the
value of an object. For example:
>>> x = 3.4
>>> str(x)
>>> repr(x)

## **List** (Python Essential References)
import sys # Load the sys module
if len(sys.argv) != 2 # Check number of command line arguments :
print "Please supply a filename"
raise SystemExit(1)
f = open(sys.argv[1]) # Filename on the command line
lines = f.readlines() # Read all lines into a list
# Convert all of the input values from strings to floats
fvalues = [float(line) for line in lines]
# Print min and max values
print "The minimum value is ", min(fvalues)
print "The maximum value is ", max(fvalues)

- List-comprehension
fvalues = [float(line) for line in open(sys.argv[1])]
- min max

## **Tuples** (Python Essential References)
- Python often recognizes that a tuple is intended even if the parentheses are missing:
stock = ('GOOG', 100, 490.10)
stock = 'GOOG', 100, 490.10

- Some programmers are inclined to ignore tuples altogether and simply use lists because they seem to be more flexible. Although this works, it wastes memory if your program is going to create a large number of small lists (that is, each containing fewer than a dozen items).This is because lists slightly overallocate memory to optimize the performance of operations that add new items. Because tuples are immutable, they use a more compact representation where there is no extra space.

- Use List and Tuple together:
filename = "portfolio.csv"
portfolio = []
for line in open(filename):
fields = line.split(",") # Split each line into a list
name = fields[0] # Extract and convert individual fields
shares = int(fields[1])
price = float(fields[2])
stock = (name,shares,price) # Create a tuple (name, shares, price)
portfolio.append(stock) # Append to list of records

## **Sets** (Python Essential References)
- Unlike lists and tuples, sets are unordered and cannot be indexed by numbers.Moreover, the elements of a set are never duplicated.
>>> t = set("Hello")
>>> t
set(['H', 'e', 'l', 'o'])
- Sets support a standard collection of operations
a = t | s # Union of t and s
b = t & s # Intersection of t and s
c = t – s # Set difference (items in t, but not in s)
d = t ^ s # Symmetric difference (items in t or s, but not both)
- Add Update Remove
t.add('x') # Add a single item
s.update([10,37,42]) # Adds multiple items to s
t.remove('H') # Removes single items from t

## **Dictionaries** (Python Essential References)

## **Scopes**

In python, a variable name can be thought of as a label attatched to a variable stored in memory.

If I go
a = 1
b = a
Then both a and b point to the same reference object (which represents 1).
If I wrote:
a = []
b = a
print a[0]
Then the output will be "hi".

This is important when you are dealing with mutable types, as in the list example above.

This next part I am having trouble expressing so you will excuse me if I lead with a code sample:

a = 5
def doStuff(b) :
b = b + 5
print b
print a

The output of the above is 10 and then 5


a = []
def doStuff(b) :
print b[0]
print a[0]

The output of the above is 'hi' and then 'hi'.

That is, when you call a function, the parameters, which are references, are coppied, but the values in memory they refer to are not.
So if you re-assign the variable within the function, using the equals operator, the original label is not affected, because you didn't modify that label, you modified the new one that was created when you called the function.
But if you modify the mutable value in memory pointed at by that label, then sure you get side effects when you return out of the function.

A couple more interesting things about scope -

In python, all the variables from the parent calling function are still in scope in the child function that got called. So you can go:

def doStuff(a) :
print b

a = 0
b = 5

and it will print 5.

But variables declared in the function prototype 'shadow' (hide) variables that already existed, so if you go:

a = 5
b = 10
def stuff(a):
a = 15
b = 20
print a

print a
print b

It will print 15, then 10 and then 20.
That is, b was modified but a was not. The new variable, that shadows (hides) a got modified

If you pass a mutable type into a function as a paramter and modify it, those modifications will still be present when you get back to the calling function.

In general, you should not take advantage of variables from the calling function being in scope. List everything you need in the function prototype, so that if you reuse the code, the names are reliable (and so you don't have to think of the above wierdness).

But knowing that where you modify a mutable object that you passed to a function, there is only one copy and you are modifying that is really useful.

## **Search Path** (Dive Into Python)
I want to briefly mention the library search path. Python looks in several places when you try to import a module. Specifically, it looks in all the directories defined in sys.path. This is just a list, and you can easily view it or modify it with standard list methods.

import sys
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-i386-linux-
gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-
packages', '/usr/local/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-
packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-
packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-
packages/ubuntuone-client', '/usr/lib/python2.7/dist-
packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-
packages/ubuntuone-storage-protocol', '/usr/lib/python2.7/dist-

1. sys.path is a list of directory names that constitute the current search path. (Yours will look different, depending on your operating system, what version of Python you're running, and where it was originally
installed.) Python will look through these directories (in this order) for a .py file matching the module name you're trying to import.

2. Actually, I lied; the truth is more complicated than that, because not all modules are stored as .py files. Some, like the sys module, are "built−in modules"; they are actually baked right into Python itself. Built−in modules behave just like regular modules, but their Python source code is not available, because they are not written in Python! (The sys module is written in C.)

3. You can add a new directory to Python's search path at runtime by appending the directory name to sys.path, and then Python will look in that directory as well, whenever you try to import a module. The effect lasts as long as Python is running.

## **Objects** (Dive Into Python)

Everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.

What is an object? Different programming languages define "object" in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects, and not all objects are subclassable. But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function.

## **Random Stuffs**
- ###if __name__ == "__main__" (Dive Into Python, docs.python.org)

So what is that all about?
Modules are objects, and all modules have a built−in attribute __name__. A module's __name__ depends on how you're using the module. If you import the module, then __name__ is the module's filename, without a directory path or file extension. But you can also run the module directly as a standalone program, in which case __name__ will be a special default value, __main__.

When you run a Python module with

>>>python xyz.py

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:

if __name__ == "__main__":
... do stuff

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file.If the module is imported, the code is not run.

>>>import xyz