|
Python
Python is an interpreted language, just like Perl or Tcl. Python's scripts can replace Perl's sricpts. But I personally prefer Python
to Perl:
- Python's syntax encourages clean codes:
- Indentation is obligatory.
- In Python, there is not several ways to say the same thing ... Perl codes may become horribly difficult to read.
- The syntax is clear. Did you already try "object programming" with Perl? Perl was not designed for object programming.
- The interpreter is small.
- Python used precompiled byte code. This byte code is platform-independent (like Java).
- You have a wild variety of modules (CGI, HTTP, SMTP, ...).
a = 1
b = 2
c = a+b
print 'a=%d b=%d c=%d' % (a,b,c)
print 'a+b+c = %d' % (a+b+c)
print 'a+b+c = ' + `a+b+c`
vlist = [1, 2, 3]
print "vlist = " + str(vlist)
print "vlist = " + repr(vlist)
|
a=1 b=2 c=3
a+b+c = 6
a+b+c = 6
vlist = [1, 2, 3]
vlist = [1, 2, 3]
|
import string
a = ' chaine '
b = string.strip(a)
print "string.strip(\'%s\') = [%s]" % (a,b)
a = string.atoi("15")
print "string.atoi(\"15\") = %d" % (a)
a = "abcdabcdabcdabcdabcdx"
print "number of \"abcd\" in \'%s\' is: %d" % (a, string.count(a,"abcd"))
print "number of \"x\" in \'%s\' is: %d" % (a, string.count(a,"x"))
a = "equivalent to strstr()"
b = string.index (a, "strstr")
print "\"strstr\" starts at index %d in \"%s\"" % (b,a)
a = "equivalent to strstr()"
b = string.replace(a,"strstr", "find in string")
print "replacing \"%s\" by \"find in string\" into \"%s\": \"%s\"" % ("strstr",a,b)
a = "equivalent to strstr()"
print 'lengh of "%s" is %d characters' % (a, len(a))
my_list = [1,2,3,4]
print "converting a list into a string of characters."
print "the list my_list is equal to: " + str(my_list)
print "the list my_list is equal to: " + repr(my_list)
print "the list my_list is equal to: " + `my_list`
|
string.strip(' chaine ') = [chaine]
string.atoi("15") = 15
number of "abcd" in 'abcdabcdabcdabcdabcdx' is: 5
number of "x" in 'abcdabcdabcdabcdabcdx' is: 1
"strstr" starts at index 14 in "equivalent to strstr()"
replacing "strstr" by "find in string" into "equivalent to strstr()": "equivalent to find in string()"
lengh of "equivalent to strstr()" is 22 characters
converting a list into a string of characters.
the list my_list is equal to: [1, 2, 3, 4]
the list my_list is equal to: [1, 2, 3, 4]
the list my_list is equal to: [1, 2, 3, 4]
|
a = "len is equivalent to strlen() in C"
for i in range(len(a)):
print i, '=>', a[i]
print "First loop:"
i = 1
while i < 10:
print "loop " + str(i)
i += 1
print "\nSecond loop:"
i = 1
while 1:
if (i >= 10):
break
print "loop " + str(i)
i += 1
|
0 => l
1 => e
2 => n
3 =>
4 => i
5 => s
6 =>
7 => e
8 => q
9 => u
10 => i
11 => v
12 => a
13 => l
14 => e
15 => n
16 => t
17 =>
18 => t
19 => o
20 =>
21 => s
22 => t
23 => r
24 => l
25 => e
26 => n
27 => (
28 => )
29 =>
30 => i
31 => n
32 =>
33 => C
First loop:
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
Second loop:
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
|
a = 1
if a > 0:
print "%d is greater than 0" % (a)
else:
print "%d is smaller than 0" % (a)
if a > 0 and a < 5:
print "%d is between 0 and 5" % (a)
else:
print "%d is not between 0 and 5" % (a)
list1 = [1,2,3,4]
list2 = [1,2,3,4]
list3 = [1,2,3,5]
print "list1:"
print list1
print "list2:"
print list2
print "list3:"
print list3
if list1 == list2:
print "list1 is equal to list2"
else:
print "list1 is not equal to list2"
if list1 == list3:
print "list1 is equal to list3"
else:
print "list1 is not equal to list3"
a = "my string 1"
b = "my string 2"
if a == b:
print "%s is equal to %s" % (a,b)
else:
print "%s is not equal to %s" % (a,b)
|
1 is greater than 0
1 is between 0 and 5
list1:
[1, 2, 3, 4]
list2:
[1, 2, 3, 4]
list3:
[1, 2, 3, 5]
list1 is equal to list2
list1 is not equal to list3
my string 1 is not equal to my string 2
|
###################################################
# Defining a simple function #
###################################################
def my_function(n):
a = n*2
return a
x = my_function(200)
print "x = my_function(200) = %d - should be 400" % (x)
copy_of_the_function = my_function
print "x = copy_of_the_function(300) = %s - should be 600" % (x)
###################################################
# Default arguments for functions #
###################################################
def default_args (a, b=2):
print "default_args (%d,%d)" % (a,b)
x = a + b
print " a = " + `a`
print " b = " + `b`
return x
print "x = default_args(3) = %d" % (default_args(3))
print "x = default_args(3, 4) = %d" % (default_args(3, 4))
###################################################
# Keywords when calling a function #
###################################################
print "x = my_function(n=10) = %d" % (my_function(n=10))
print "x = my_function(b=5, a=2) = %d" % (default_args(b=5, a=2))
###################################################
# Variable number of arguments #
###################################################
def variable (toto, *vargs):
print 'toto is equal to %s' % (toto)
print 'Extra arguments are:'
for i in vargs:
print i
print "calling variable() with \'first arg\', \'a1\', \'a2\', \'a3\' as argument"
variable('first arg', 'a1', 'a2', 'a3')
###################################################
# variable number of keywords #
###################################################
def variable (toto, **vargs):
print 'toto is equal to %s' % (toto)
print 'Extra arguments are:'
for i in vargs.keys():
print i,vargs[i]
print "\n\n"
variable('first arg')
print "\n\n"
variable('first arg', a='first keyword')
print "\n\n"
variable('first arg', a='first keyword', b='second keyword')
|
x = my_function(200) = 400 - should be 400
x = copy_of_the_function(300) = 400 - should be 600
default_args (3,2)
a = 3
b = 2
x = default_args(3) = 5
default_args (3,4)
a = 3
b = 4
x = default_args(3, 4) = 7
x = my_function(n=10) = 20
default_args (2,5)
a = 2
b = 5
x = my_function(b=5, a=2) = 7
calling variable() with 'first arg', 'a1', 'a2', 'a3' as argument
toto is equal to first arg
Extra arguments are:
a1
a2
a3
toto is equal to first arg
Extra arguments are:
toto is equal to first arg
Extra arguments are:
a first keyword
toto is equal to first arg
Extra arguments are:
a first keyword
b second keyword
|
a = ["string1", "string2", "string3"]
print 'a=["string1", "string2", "string3"]'
print " a[0] " + a[0]
print " a[1] " + a[1]
print " a[2] " + a[2]
print ' add "string4" to the end of the list'
a.append("string4")
print " a[3] " + a[3]
print 'Insering "insert0" at index 0'
a.insert (0, "insert0")
print a
print 'Insering "insert4" at index 4'
a.insert (4, "insert4")
print a
print 'remove the first occurence of "insert0" in the list'
a.remove ("insert0")
print a
print "remove (and return) the last item of the list"
b = a.pop()
print "last item is " + b
print "now list is: "
print a
print "remove (and return) the second item of the list"
b = a.pop(1)
print "last item is " + b
print "now list is: "
print a
print "index of \"string3\" is %d" % (a.index("string3"))
print "number of items \"string3\" in the list: %d" % (a.count("string3"))
print "number of items in the list: %d" % (len(a))
print "sorting the list"
print "before:"
print a
print "after"
a.sort()
print a
print "remove items at index 0 and 1 from the list"
del a[0:2]
print a
|
a=["string1", "string2", "string3"]
a[0] string1
a[1] string2
a[2] string3
add "string4" to the end of the list
a[3] string4
Insering "insert0" at index 0
['insert0', 'string1', 'string2', 'string3', 'string4']
Insering "insert4" at index 4
['insert0', 'string1', 'string2', 'string3', 'insert4', 'string4']
remove the first occurence of "insert0" in the list
['string1', 'string2', 'string3', 'insert4', 'string4']
remove (and return) the last item of the list
last item is string4
now list is:
['string1', 'string2', 'string3', 'insert4']
remove (and return) the second item of the list
last item is string2
now list is:
['string1', 'string3', 'insert4']
index of "string3" is 1
number of items "string3" in the list: 1
number of items in the list: 3
sorting the list
before:
['string1', 'string3', 'insert4']
after
['insert4', 'string1', 'string3']
remove items at index 0 and 1 from the list
['string3']
|
hash_table = {'key1':[1,2,3], 'key2':[4,5,6], 'key3':[7,8,9]}
print "The hash table contains:"
print hash_table
print 'value of key "key1" is:'
print hash_table['key1']
print 'add element 4 to value of "key1":'
hash_table['key1'].append(4)
print hash_table['key1']
print 'delete entry for "key1":'
del hash_table['key1']
print hash_table
|
The hash table contains:
{'key3': [7, 8, 9], 'key2': [4, 5, 6], 'key1': [1, 2, 3]}
value of key "key1" is:
[1, 2, 3]
add element 4 to value of "key1":
[1, 2, 3, 4]
delete entry for "key1":
{'key3': [7, 8, 9], 'key2': [4, 5, 6]}
|
import sys
try:
fdin = open("test_file", "r")
except IOError, desc:
print "Can not open input file for reading: ", desc;
sys.exit(1)
try:
fdout = open("out", "w")
except IOError, desc:
print "Can not open output file for writing: ", desc;
sys.exit(1)
i = 1
try:
line = fdin.readline()
except IOError, desc:
print "Error while reading line ", i, " of input file: ", desc;
sys.exit(1)
while line != "":
print "line %d is %s" % (i,line)
i = i + 1
try:
fdout.write("out" + line)
except IOError, desc:
print "Error while writing line ", i, " to output file: ", desc;
sys.exit(1)
try:
line = fdin.readline()
except IOError, desc:
print "Error while reading line ", i, " of input file: ", desc;
sys.exit(1)
fdin.close()
fdout.close()
|
Assuming that the content of the input file test_file is:
line number 1
line number 2
line number 3
line number 4
We get the follwing result:
line 1 is line number 1
line 2 is line number 2
line 3 is line number 3
line 4 is line number 4
|
import re
################################################################
# Testing for pattern #
################################################################
regular = 'ab.'
buff = 'abc'
expr = re.compile(regular)
p = re.match(expr, buff)
print "Does " + buff + " contain " + regular + " ?"
if p == None:
print "No"
else:
print "Yes"
################################################################
# Finding all pattern that matches a given expression #
################################################################
regular = 'ab.'
buff = 'abbxxxxabcyyyyabdb'
expr = re.compile(regular)
p = re.findall(expr, buff)
print "Find all occurrence of " + regular + " into " + buff
print p
################################################################
# Searching for a match in a given string of characters #
################################################################
regular = '.ABBA.'
buff = 'wwwwwwwABBAzzzzzzz'
expr = re.compile(regular)
p = re.search(expr, regular)
print "Searching for " + regular + " into string " + buff
if p != None:
print "Found"
else:
print "Not found"
################################################################
# Replace pattern #
################################################################
regular = '.ABBA.'
buff = '1ABBA2xxx3ABBA4yyy4ABBA5'
tag = "REPLACED"
replaced = re.sub(expr, tag, buff)
print "Replacing " + regular + " by " + tag + " in " + buff
print replaced
################################################################
# Another example with the use of () #
################################################################
test = "<data name=\"email\">adresse email</data>"
test = test + "<data name=\"multisms\">nombres de sms</data>"
test = test + "<data name=\"expire\">date d'expiration de SMS</data>"
test = test + "<data name=\"free\">SMS gratuits</data>"
print "Searching in: [", test, "]"
######################################
# Look for attributs #
######################################
pattern = "\"([^\"<>]*)\""
expr = re.compile(pattern)
attributs = re.findall(expr, test)
print "\nAttributs are:"
print attributs
######################################
# Look for values #
######################################
pattern = ">([^<>]+)<"
expr = re.compile(pattern)
values = re.findall(expr, test)
print "\nValues are:"
print values
|
Does abc contain ab. ?
Yes
Find all occurrence of ab. into abbxxxxabcyyyyabdb
['abb', 'abc', 'abd']
Searching for .ABBA. into string wwwwwwwABBAzzzzzzz
Found
Replacing .ABBA. by REPLACED in 1ABBA2xxx3ABBA4yyy4ABBA5
REPLACEDxxxREPLACEDyyyREPLACED
Searching in: [ <data name="email">adresse email</data><data name="multisms">nombres de sms</data><data name="expire">date d'expiration de SMS</data><data name="free">SMS gratuits</data> ]
Attributs are:
['email', 'multisms', 'expire', 'free']
Values are:
['adresse email', 'nombres de sms', "date d'expiration de SMS", 'SMS gratuits']
|
from socket import *
import sys
SERVER_PORT = 80
SERVER_HOST = 'dev3'
DATA_TO_SEND = "GET / HTTP/1.0\n\n"
###################################################
# Create socket #
###################################################
try:
sock = socket(AF_INET, SOCK_STREAM)
except error, desc:
print "Can not create socket : ", desc
sys.exit(1)
###################################################
# Connect to remote server #
###################################################
try:
sock.connect((SERVER_HOST, SERVER_PORT))
except error, desc:
print "Can not nonnect to server ", SERVER_HOST, " on port ", SERVER_PORT, " : ", desc
sys.exit(1)
###################################################
# Send data #
###################################################
try:
sock.send (DATA_TO_SEND)
except error, desc:
print "Error while sendinf data to server : ", desc
sys.exit(1)
###################################################
# Now get the answer #
###################################################
try:
answer = sock.recv(1000)
except error, desc:
print "Error while reading answer from server : ", desc
sys.exit(1)
print "\nThe server replied:\n\n", answer, "\n"
###################################################
# Close the connexion #
###################################################
sock.close()
|
The server replied:
HTTP/1.1 403 Forbidden
Date: Wed, 20 Feb 2002 13:10:55 GMT
Server: Apache/1.3.19 (Unix) mod_perl/1.25 PHP/4.0.2
X-Powered-By: PHP/4.0.2
Connection: close
Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>404 Not Found</TITLE>
</HEAD><BODY>
<H1>Not Found</H1>
The requested URL was not found on this server.<P>
<HR>
</BODY></HTML>
|
Just like other languages (such as C, C++, Perl, ...), it is possible to define modules. Modules may be compared to the libraries for
C.
import module_name
|
Python will search for the file module_name.py. If this file is not in the current directory, or in the standard Python's
module path, then the Python interpreter will look in the list of directories specified by the environment variable PYTHONPATH.
PYTHONPATH is a list of colon (:) separated directory paths.
Note that all the functions or variables in the module module_name can be called by using the notation:
module_name.function_name. If you want to get rid of the module name (module_name), then you can use the
following notation:
from module_name import function1 function2
This will allow you to call function1 and function2 without the leading "module_name.". But all other
functions or variables from the module module_name will not be exported (this means that you can't call them, even if you
use the leading "module_name.".
If you want to export everything from a module, you can use:
from module_name import *
This will allow you to call any functions or variables from the module module_name without the leading "module_name.".
|
|