IntroToPythonForProgrammers

Intro

Some Resources

rickspencer3's chapters

  • rickspencer3.com
  • some errors
  • single space indent instead of four spaces
  • not define difference between "==" and is

What is Python?

  • A language
  • A standard library
  • both parts work hand in hand, hard to separate totally
  • interpreted at run time, at least once (no compile errors! watch out)

Python Interpreter

  • just type "python" in terminal, and start
  • very handy for small jobs and tests
  • ipython - install it, love it, tab it
  • >>> means sample is in interpreter

Language Concepts

Indentation levels

  • controls scoping instead of {}, "end", etc...
  • standard is to use 4 spaces for each indentation level
  • you will get used to it, and probably format you code this way anyway
  • at first, many errors will be caused by this

   1 for i in xrange(5,20):
   2     print i

2. Strong Dynamic Typing

  • Object and sibclasses, int, float, etc...
  • A variable can change type
  • don't declare variables with types
  • can convert a *variable* to another type, not casting and assigning

Dynamic Typing

>>> x = 1 
>>> x 
1 
>>> type(x) 
<type 'int'> 
>>> x = "string" 
>>> x 
'string' 
>>> type(x) 
<type 'str'> 

Strong Typing

>>> x = 1 
>>> print x + " is a string" 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

Types

Numeric types

  • Integer, Long Integer, Float, Complex
  • Normal operands and conversion functions float(), int(), etc...
  • Can mix and match them in math, will convert to use least "restrictive" type

>>> x = 5 
>>> y = 5L 
>>> x * y 
25L 
>>> x = 5 
>>> y = 5.0 
>>> x * y 
25.0 
>>> x = 5L 
>>> y = 5.0 
>>> x * y 
25.0 
>>> x = 25 
>>> y = 5.01 
>>> x / y 
4.9900199600798407

Strings

  • lots of functions
  • not difference between characters and strings
  • concatenation with +, +=, etc...
  • ",' are the same
  • """ can included \n, ",', etc...

None is an object of NoneType

  • like Null, null, etc...
  • None is an object of type NoneType

  • undefined variables are not None, just undefined errors

Lists and Tuples

  • Like an array
  • Not typed, can contain anything
  • Tuples are immutable lists
  • modify with "append", +/-, etc...

create a tuple

>>> wintermonths = ("December","January","February") 
>>> wintermonths 
('December', 'January', 'February') 

create a list

>>> grades = ["A","A-","B","C"] 
>>> grades 
['A', 'A-', 'B', 'C'] 

Accessing

Indexed with [] as you are used to

>>> wintermonths 
('December', 'January', 'February') 
>>> wintermonths[0] 
'December' 

A handy trick for starting from the back

>>> grades 
['A', 'A-', 'B', 'C'] 
>>> grades[-1] 
'C' 
>>> grades[-2] 
'B' 

in

Test if a list or tuple contains a value

>>> grades = ["A","A-","B","C"] 
>>> grades 
['A', 'A-', 'B', 'C'] 
>>> "A" in grades 
True 
>>> "F" in grades 
False 

Dictionaries

  • Like hash tables
  • "foo in bar" syntax like tuples and lists
  • how to append, remove, etc...
  • are NOT ordered!

>>> grades 
['A', 'A-', 'B', 'C'] 
>>> i = grades.index("A") 
>>> i 
0 
>>> i = grades.index("B") 
>>> i 
2 

Test with "in" first, or you are liable to get an error

>>> grades 
['A', 'A-', 'B', 'C'] 
>>> i = grades.index("F") 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
ValueError: list.index(x): x not in list 

Comparisons and branching

  • True and False
  • if, ==, !=, <=, >=, etc....

  • is, is not
  • or, and
  • else, elif

a = "xxx"

if a is "boo":
    print "a is boo"
elif a is not "foo":
    print "a is not foo"
else:
    print "a is foo"

a = 1

if a == 1:
    print "a is 1"

Loops

  • - for foo in bar: - while loops - for i in xrange(10)

>>> for g in grades: 
...  print g 
... 
A 
A- 
B 
C 

>>> x = 0 
>>> while x < 10: 
...  x += 1 
...  print x 
... 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

>>> grades = [] 
>>> for i in xrange(10): 
...  digits.append(i) 
... 
>>> digits 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 

Error Handling

  • try, except
  • Exception type: except Exception
  • Exception instance: except Exception instance:
  • lots of built in exceptions
  • derive your own, just end it in "Error"

>>> grades = ['A', 'A-', 'B', 'C'] 
>>> 
>>> grades = ['A', 'A-', 'B', 'C'] 
>>> try: 
...  grades.index("F") 
... except ValueError: 
...  print "no Fs" 
... 
no Fs 

comments and doc comments

  • #comment is just for folks reading code
  • using """ in strategic places == doc comments, pydoc

Modules, Files, Classes

file overview

  • shbang, tell bash what interpreter to use
  • imports section
    • like #include
    • import os
    • from foo import bar
  • code section
  • if __name__ == "__main__"

    • runs if module is called directly not from another module
    • start your program, also useful for writing test apps

import pygtk
pygtk.require('2.0')
import gtk

class program2:
    def __init__(self, startval):
       self.x = startval

    def run(self):
        for i in range(1,10):
            self.x += 1
            self.output()

    def output(self):
        if self.x > 9:
            print "x is greater than 9"
        else:
            print "x is not greater than 9"

if __name__ == "__main__":
    p = program2(0)
    p.run()
    p = program2(1)

    p.run()

Code section

class overview

  • class decleration, define superclass, call super.__init__(self)

  • __init__, more or less the constuctor, not required

   1 class program3(program2):
   2     def __init__(self):
   3         program2.__init__(self, 5)
  • member functions, what's this "self" thing?
    • the object that the function is acting on
    • required for all member function
    • added automatically when calling on self or instantiated class
    • must add when calling in a super class (see above)
  • member variables
    • instance variables are defined with a function using self.foo
    • class variables declared outside a functions, once instance of the variable for all instances of the class (weird?)

z = 1
class program:
    x = 2 #class variable
    def __init__(self):
        print self.x #not necessarily 2, could have been modified by another instance
        print z
        self.y = 3 #instance variable

if __name__ == "__main__":
    p = program()
    print p.y
  • can define multiple classes in a file
  • can define functions variables outside classes

OO syntax

  • instantiating object
  • no private variables, really?
    • convention: start with _ for members that should be private and inheritable
    • start with __ for members that should be private and not heritable (munging)

UbuntuOpportunisticDeveloperWeek/IntroToPythonForProgrammers (last edited 2010-02-25 17:54:59 by static-68-151-229-77)