Python

From no name for this wiki
Jump to: navigation, search

Python

Control structures

#while
b = 0
while b < 100:
   print b
   b = b + 1
print "Done"

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

#Named arguments
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "volts through it."
    print "-- Lovely plumage, the", type
    print "-- It's", state, "!"

parrot(220, type='Swiss Chick')

#unpacking arguments
args = [3, 10]
print range(*args)

Strings

#More than one line
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
 significant."

print hello

#Substrings
hello = "Hi there"
print hello[2:7]

Collections

#Dictionary
tel = {'jack': 4098, 'sape': 4139}
a = tel['jack']
print a

Classes

#Simple
class Hello :
  def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Hello(2,3)

#Simple2
class Bag:
    def __init__(self):
        self.data = []
    def add(self, x):
        self.data.append(x)
    def addtwice(self, x):
        self.add(x)
        self.add(x)

bag = Bag()
bag.add("Hello")
bag.add("Testmaster")

Iterator

#Simple
for element in [1, 2, 3]:
    print element
for element in (1, 2, 3):
    print element
for key in {'one':1, 'two':2}:
    print key
for char in "123":
    print char

#Generator
def someyield():
    for index in  range(1,10):
        yield index

x = someyield()
for t in x:
    print t

Exceptions

#Simple
try:
   10 * (1/0)
except Exception:
   print "Error Occured"

#Funktioniert in Jython nicht
try:
  x = 10/0
except ZeroDivisionError as detail:
  print 'Handling run-time error:', detail

Jython

#Interacting with java packages
from java.util import Random
r = Random()
print r.nextInt()

Resourcen

Iron Python

import clr
clr.AddReference("System.Windows.Forms")
import System.Windows.Forms as WinForms
WinForms.MessageBox.Show("Hello", "Hello World")

Resourcen