Open writing projects/Scientific Programming with Python and Subversion/Appendices/Introduction to Python: Difference between revisions

From OpenWetWare
Jump to navigationJump to search
Line 101: Line 101:
=== Exceptions ===
=== Exceptions ===
<syntax type="python">
<syntax type="python">
# Don't crash if something goes wrong - except it
dict = {'my_key' : 3}
print dict[your_key] # this will cause a halt
# This will print a warning message and continue
try:
    print dict[your_key]
except KeyError:
    print 'Key not found, moving on.'
# Exceptions are actually objects, so you can define your own
</syntax>
</syntax>



Revision as of 19:29, 26 May 2008

This page is part of the Open Writing Project Scientific_Programming_with_Python_and_Subversion. (More Open Writing Projects.)



Julius B. Lucks 21:58, 26 May 2008 (EDT): Very rough code snippets detailing some of the main features of python.

Variables

<syntax type="python">

  1. All variables are pointers.

an_integer = 1 a_float = 1. a_string = 'Hi'

a = 1 b = a a = 2 print b,a #prints 1 2 </syntax>

Data Structures

<syntax type="python"> a_list = [1,2,3,[4,5,6]] a_tuple = (1,2,3,(4,5,6)) a_dictionary = {'key_1' : 1, 'key_2' : 2} </syntax>

Control Structures

<syntax type="python">

  1. conditional

if a == b then:

   print 'I knew it!'
  1. looping

for element in my_list:

   print 'The element is ',element
  1. list comprehensions

my_new_list = [5*num for num in my_old_list] </syntax>

Functions

<syntax type="python">

  1. defining a function - remember indentation

def a_function(argument_1):

   print argument_1
  1. def returns a pointer!

def a_function():

   print 'Hi'

my_function = a_function

  1. so functions can return functions (and we can do closures too)!

def generator_function(number,arg=0):

   The default value of arg is 0
   def temp_function(arg):
       return number*arg
   return temp_function

multiply_of_five = generator_function(5) print multiply_by_five() #returs 0 print multiply_by_five(1) #returs 5 print multiply_by_five(10) #returs 50 </syntax>

Objects

<syntax type="python">

  1. Define your classes with class

class MyClass(object):

   Classes inherit from object
   def __init__(self,attribute):
       __init is like a constructor
          like other class methods, it takes self
          as the first argument
       #object attributes are easy to define
       self.attribute = attribute
   def method_1(self):
       if self.attribute != 0:
           print 'I am not 0.'
  1. create an object of MyClass

my_class_object = MyClass(1) my_class_object.method_1() # prints 'I am not 0.'

  1. we can introspect objects easily!

print dir(my_class_object)

  1. prints
  2. ['__class__', '__delattr__', '__dict__',
  3. '__doc__', '__getattribute__', '__hash__',
  4. '__init__', '__module__', '__new__', '__reduce__',
  5. '__reduce_ex__', '__repr__', '__setattr__', '__str__',
  6. '__weakref__', 'attribute', 'method_1']
  7. Actually my_class_object.__dict__ is the key to hacking, but it's ugly!
  1. most things are objects, like functions!

my_function = lambda x: 2*x print dir(my_function)

  1. prints a bunch of stuff like above

</syntax>

Exceptions

<syntax type="python">

  1. Don't crash if something goes wrong - except it

dict = {'my_key' : 3} print dict[your_key] # this will cause a halt

  1. This will print a warning message and continue

try:

   print dict[your_key]

except KeyError:

   print 'Key not found, moving on.'
  1. Exceptions are actually objects, so you can define your own

</syntax>

Modules

<syntax type="python"> </syntax>