Python: Difference between revisions

From Halfface
Jump to navigation Jump to search
Line 437: Line 437:
=output formatting=
=output formatting=


str() function is meant to return representations of values which are fairly human-readable.
str() function is meant to return representations of values which are fairly human-readable.
repr() is meant to generate representations which can be read by the interpreter
repr() is meant to generate representations which can be read by the interpreter
str.rjust() method which right-justifies a string in a field of a given width by padding it with spaces on the left.
str.rjust() method which right-justifies a string in a field of a given width by padding it with spaces on the left.
str.ljust() left justify
str.ljust() left justify
str.center() center
str.center() center

Revision as of 20:18, 8 November 2011

links

 http://docs.python.org/tutorial

Reference

http://docs.python.org/ref/ref.html
http://docs.python.org/library/

basics

print "Hello, World!"

command called print followed by one argument,which is "Hello, World!". (referred to as a string of characters, or string) Command and its arguments are collectively referred to as a statement,

print "2 + 2 is", 2 + 2

The first argument is the string "2 + 2 is" and the second argument is the mathematical expression 2 + 2, which is commonly referred to as an expression. each of the arguments separated by a comma

Print without spaces. flush buffers.

import sys
sys.stdout.write(character)
sys.stdout.flush()
sys.argv   arguments are passed to the script in the variable sys.argv
#          is used to start a comment

Enable swedish keys åäö

#!/usr/bin/python
# -*- coding: utf-8 -*-

operations for numbers

Operation Symbol Example
Power (exponentiation) ** 5 ** 2 == 25
Multiplication * 2 * 3 == 6
Division / 14 / 3 == 4
Remainder (modulo) % 14 % 3 == 2
Addition + 1 + 2 == 3
Subtraction - 4 - 3 == 1

userinput

raw_input (returns a string)

user_reply = raw_input("Who goes there? ")

input (returns digits)

number = input("Type in a number: ")

type(number) (tells what a variable is.)

print "number is a", type(number)

while loop

print number interval. finish while loop with a ':' The while statement only affects the lines that are indented with whitespace.

start = input("Start number? ")
stop = input("Stop number? ")
a = start
while a < stop:
    print a
    a = a + 1
operator function
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal
<> another way to say not equal (old style, not recommended)

if statment

 if a > 5:  
   print a, ">", 5
 elif a <= 7:
   print a, "<=", 7
 else:
   print "Neither test was true"
  1. This Program Demonstrates the use of the == operator # using numbers
print 5 == 6 

false

strings

strings are impossible to change

strings can be surrounded in a pair of matching triple-quotes: """ or '''. No newlines will be created.

If we make the string literal a “raw” string, \n sequences are not converted to newlines,

raw = r"Hello\nWhat \
is happening"
print raw

Unicode strings

text = u'Hej på dig'

To convert a Unicode string into an 8-bit string

u"äöü".encode('utf-8')

Multi asignment

a, b = 0, 1
print a, b
0 1

functions

The key feature of this program is the def statement. def (short for define) starts a function definition. def is followed by the name of the function absolute_value. Next comes a '(' followed by the parameter n (n is passed from the program into the function when the function is called). The statements after the ':' are executed when the function is used. The statements continue until either the indented statements end or a return is encountered. The return statement returns a value back to the place where the function was called.

def absolute_value(n):
  if n < 0:
    n = -n
  return n
  • The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring. If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
  • Print documentation. print function.__doc__
  • The return statement returns with a value from a function.
  • *name which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.)
  • **name options to function, it receives a dictionary

Unpack argument list.

args = [3, 6]
range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Unpack argument dictionary.

d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d) # dictionaries can deliver keyword arguments with the **-operator:


list

list with more than one value.

which_one = input("What month (1-12)? ")
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
if 1 <= which_one <= 12:
 print "The month is", months[which_one - 1]

Print a whole list.

demolist = ["life", 42, "the universe", 6, "and", 7]
print "demolist = ",demolist

demolist = ['life', 42, 'the universe', 6, 'and', 7]

b = a

makes b a reference to a.

b = a * 1
b = a[:]

copies b to a.

list as stacks

Last in First out.

stack = [3, 4, 5]
stack.append(6)
stack.pop()

lists as queus

from collections import deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.popleft()                 # The first to arrive now leaves

map

map(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the return values.

def cube(x): return x*x*x
map(cube, range(1, 11))

list methods

list.append(x) Add an item to the end of the list.
list.extend(L) Extend the list by appending all the items in the given list.
list.insert(i, x) Insert an item at a given position.  The first argument is the index of the element before which to insert.
list.remove(x) Remove the first item from the list whose value is x.
list.pop([i]) Remove the item at the given position in the list, and return it.  If no index is specified, a.pop() removes and returns the last item in the list.
list.index(x) Return the index in the list of the first item whose value is x.
list.count(x) Return the number of times x appears in the list.
list.sort() Sort the items of the list, in place.
list.reverse() Reverse the elements of the list.

List comprehensions

List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or lambda. The resulting list definition tends often to be clearer than lists built using those constructs. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it. If the expression would evaluate to a tuple, it must be parenthesized.

vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]

Same things can be done with zip()

mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
zip(*mat)

list

example explanation
demolist[2] accesses the element at index 2
demolist[2] = 3 sets the element at index 2 to be 3
del demolist[2] removes the element at index 2
len(demolist) returns the length of demolist
"value" in demolist is True if "value" is an element in demolist
"value" not in demolist is True if "value" is not an element in demolist
demolist.sort() sorts demolist
itarable.sorted() sorts any itarble
demolist.index("value") returns the index of the first place that "value" occurs
demolist.append("value") adds an element "value" at the end of the list
demolist.remove("value") removes the first occurrence of value from demolist (same as del demolist[demolist.index("value")])
onetoten = range(1, 11)
list[-1] Returns the last index
list[-2] Returns the second last index
things[4:7] Pick slice of list
sum(sequence) Summarize a sequence

functions

ord()        Returns a character as a number. 
chr(15)      Return number to character
repr()       Convert a integer to a string
int()        Convert a string to an integer.
float()      Convert a string to a float
eval()       Takes a string and returns type that python thinks it found
text.split(",")    converts a string into a list of strings. The string is split by whitespace by default or by the optional argument You can also add another argument that tells split() how many times the separator will be used to split the text.
round(_, 2)  Make the floating point into two decimals.
reversed()   Reverse contents.

for loop

in keyword. This tests whether or not a sequence contains a certain value.

demolist = ['life', 42, 'the universe', 6, 'and', 9, 'everything']
for item in demolist:
   print item

break and continue Statements, and else Clauses on Loops

break statement breaks out of the smallest enclosing for or while loop
continue statement continues with the next iteration of the loop.
else Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

looping techniques

Key and corresponding value can be retrieved at the same time

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.iteritems():
     print k, v
gallahad the pure
robin the brave


looping trough sequence

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
    print i, v
0 tic
1 tac
2 toe

dictionary

Add an empty dictonary called words

words = {}

Create a list of keys in dictionary.

for x in words.keys():

Grabs the words in a dictionary. Print meaning of word

print words[x]

If name exist in dictionary, remove it.

if name in words:
 del words[name]

File IO

  1. Write a file
out_file = open("test.txt", "w")
out_file.write("This Text is going to out file\nLook at it and see!")
out_file.close()
  1. Read a file
in_file = open("test.txt", "r")
text = in_file.read()
in_file.close()
  1. Read file if it exists.
import os 
filename = os.environ.get('PYTHONSTARTUP') 
if filename and os.path.isfile(filename):
  execfile(filename)

error handling

try:
number = int(raw_input("Enter a number: "))
 print "You entered:", number
except ValueError:
 print "That was not a number."

Try handles error handling. If you didn't get a number ask for one.

python configuration

How to configure python. Where should I put config file.

import site
site.getusersitepackages()
/home/user/.local/lib/python3.2/site-packages'
/home/user/.local/lib/python3.2/site-packages/usercustomize.py
/home/user/.local/lib/python3.2/site-packages/sitecustomize works in the

pass

The pass statement does nothing.

reduce()

reduce(function, sequence) returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers

def add(x,y):
 print "x, y", x, y
 print "x+y ", x+y
 return x+y
reduce(add, range(1, 3))
x, y 1 2
x+y  3
x, y 3 3
x+y  6
6

tuple,array

# Tuples may be nested: t = (1, 2, 3, 4, 5)

set

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements.

print set('abracadabra')
set(['a', 'r', 'b', 'c', 'd'])

operators

a = set('abracadabra')
b = set('alacazam')
a                                  # unique letters in a
a - b                              # letters in a but not in b
a | b                              # letters in either a or b
a & b                              # letters in both a and b
a ^ b                              # letters in a or b but not both

format()

To loop over two or more sequences at the same time, the entries can be paired with the zip() function. format() exchange q and a with {0} and {1}

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print 'What is your {0}?  It is {1}.'.format(q, a)

modules

A module is a file containing Python definitions and statements.
The file name is the module name with the suffix .py appended. 
Within a module, the module’s name (as a string) is available as the value of the global variable __name__.
import fibo # import fibo.

This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module name fibo there. Using the module name you can access the functions:

fibo.fib(1000)

If you intend to use a function often you can assign it to a local name:

fib = fibo.fib

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions,

modname.itemname.

There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. For example:

from fibo import fib, fib2  fib(500)

The dir() Function

The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:

import fibo, sys
dir(fibo)
['__name__', 'fib', 'fib2']

lists all types of names: variables, modules, functions, etc.

dir()

dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module __builtin__

dir(__builtin__)

module examples

command import loads a module

Sleep

import time
time.sleep(secs)

random

import random
number = random.randrange(1, 100, 1)

deepcopy

To copy lists that contain lists use deepcopy

import copy
c = copy.deepcopy(a)

packages

  • Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.
  • The __init__.py files are required to make Python treat the directories as containing packages.
  • When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
  • __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable
import sound.effects.echo

This loads the submodule sound.effects.echo. It must be referenced with its full name.

from sound.effects import echo

An alternative way of importing the submodule. This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:

echo.echofilter(input, output, delay=0.7, atten=4)

import

Importing * From a Package

output formatting

str() function is meant to return representations of values which are fairly human-readable.
repr() is meant to generate representations which can be read by the interpreter
str.rjust() method which right-justifies a string in a field of a given width by padding it with spaces on the left.
str.ljust() left justify
str.center() center