RSS

Search Engine

Wednesday, December 8, 2010

Programming in Python

5.1. Comments

The following create a single line comment.

    
# This is a comment

5.2. Variables

Python provides dynamic typing of its variables, e.g. you do not have to define a type of the variable Python will take care of this for you.

    
# This is a text
s= "Lars"
# This is an integer
x = 1
y=4
z=x+y

5.3. Assertions

Python provides assertions. These assertions are always called.

    
assert(1==2)

5.4. Methods / Functions in Python

Python allows to define methods via the keyword def. As the language is interpreted the methods need to be defined before using it.

    
def add(a,b):
return a+b

print add(1,2)

5.5. Loops and if clauses

The following demonstrates a loop the usage of an if-clause.

    
i = 1
for i in range(1, 10):
if i <= 5 :
print 'Smaller or equal then 5.\n',
else:
print 'Larger then 5.\n',

5.6. String manipulation

Python allows the following String operations.

Table 2.

OperationsDescription
len(s)Returns the length of string s
s[i]Gets the element on position i in String s, position start with zero
s[-i]Get the i-tes Sign of the string from behind the string, e.g. -1 returns the last element in the string
"abcdefg"[0:4]Gets the first 4 elements (abcd)
"abcdefg"[4:]Gets the elements after the first 4 elements (abcd)
`a`+`b` + `c`Concatenates the int varibles a, b,c, e.g. if a=1, b=2, c=3 then the result is 123.
s.lower()Result will be s in lower cases
s.upper()Result will be s in upper cases
s.startswith(t)True, if s startsWith t
s.rstrip()Removes the end of line sign from the string

For example:

    
s = "abcdefg"
assert (s[0:4]=="abcd")
assert ( s[4:]=="efg")
assert ("abcdefg"[4:0]=="")
assert ("abcdefg"[0:2]=="ab")

5.7. Concatenate strings and numbers

Python does not allow to concatenate a string directly with a number. It requires you to turn the number first into a string with the str() function.

If you don't use str() you will get "TypeError: cannot concatenate 'str' and 'int' objects".

For example:

    
print 'this is a text plus a number ' + str(10)

5.8. Lists

Python has good support for lists. See the following example how to create a list and how to access individual elements or sublists.

    
'''
Created on 14.09.2010

@author: Lars Vogel
'''
list = ["Linux", "Mac OS" , "Windows"]
# Print the first list element
print(list[0])
# Print the last element
# Negativ values starts the list from the end
print(list[-1])
# Sublist - first and second element
print(list[0:2])

5.9. Processing files in Python

The following example is contained in the project "de.vogella.python.files".

The following reads a file, strips out the end of line sign and prints each line to the console.

    
'''
Created on 07.10.2009

@author: Lars Vogel
'''

f = open('c:\\temp\\wave1_new.csv', 'r')
print f
for line in f:
print line.rstrip()
f.close()

The following reads the same file but write the output to another file.

    
'''
@author: Lars Vogel
'''

f = open('c:\\temp\\wave1_new.csv', 'r')
output = open('c:\\temp\\sql_script.text', 'w')
for line in f:
output.write(line.rstrip() + '\n')
f.close()

5.10. Splitting strings and comparing lists.

The following example is contained in the project "de.vogella.python.files". It reads to files which contain one long comma separated string. This string is splitted into lists and the lists are compared.

    
f1 = open('c:\\temp\\launchconfig1.txt', 'r')
s= ""
for line in f1:
s+=line
f1.close()

f2 = open('c:\\temp\\launchconfig2.txt', 'r')
s2= ""
for line in f2:
s2+=line
f2.close()
list1 = s.split(",")
list2 = s2.split(",");
print(len(list1))
print(len(list2))


difference = list(set(list1).difference(set(list2)))

print (difference)

5.11. Classes in Python

The following is a defined class in Python. Python uses the naming convension __name__ for internal functions.

Python allows operator overloading, e.g. you can define what the operator + will to for a specific class.

Table 3.

__init__Constructor of the class
__str__The method which is called if print is applied to this object
__add__+ Operator
__mul__* Operator

The empty object (null) is called "None" in Python.

    
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "x-value" + str(self.x) + " y-value" + str(self.y)
def __add__(self,other):
p = Point()
p.x = self.x+other.x
p.y = self.y+other.y
return p

p1 = Point(3,4)
p2 = Point(2,3)
print p1
print p1.y
print (p1+p2)

0 comments:

Post a Comment