Python - howto for VB6 developers
By: John McFarlane
<john.mcfarlane@rockfloat.com>
I'm finished with this step
This document was originally created on 05/10/2006
Abstract:
This document is a quick introduction into Python programming
intended for those with a background in Microsoft Visual Basic
or Active Server Pages. (This howto is not even close
to complete, partly because I lost my will to go on, when trying
to write the VB examples.)
Table of Contents:
1. Introduction to Python
Python is an interpreted language started by Guido Van Rosen?.
It's often compared to languages such as Perl and Ruby. It's a
very popular langauge often because it's easy to learn and fast to
develop with. All the cool kids use Python. Python is known to
run on nearly everything:
I'm finished with this step
- Windows
- BSD
- Macintosh
- Linux
-
Running sample code:
Windows c:\> python foobar.py Linux/Unix/BSD user# python foobar.pyc:\> foobar.exe -
Comments in code:
# This is a comment' This is a comment
2. Variables
Python is a strongly typed lanuage at it's core, but it's easy to forget
because casting is implicit.
I'm finished with this step
a = 1 # Integer (>= 32 bit)
b = 1L # Long (Unlimited precision)
c = 1.1 # Float (Precision determined by arch)
d = 2J # Complex (Real and imaginary part)
e = "2" # String
f = foobar(a, b) # Class instance
Dim a As Integer
a = 1 # Integer (16 bits)
Dim b As Long
b = 1.1 # Long (32 bits)
Dim e As String
e = "2" # String
Dim f As foobar
Set f = CreateObject("Foo.bar") # Class instance
3. Operators
Python is a bit more like other languages such as Java/PHP:
I'm finished with this step
- = Assignment
- == Evaluation, equals
- != Evaluation, does not equal
- + Addition of numbers, concatination of strings
- - Subtraction
- % Modulous
- += Add number to self, concatinate string
- -= Subtract number to self
- is Evaluation, exact Here is a list every Python operator.
- = Assignment
- = Evaluation, equals
- <> Evaluation, does not equal
- + Addition of numbers, concatination of strings
- - Subtraction
- Mod Modulous
- i = i + 1 Add number to self, concatinate string
- i = i - 1 Subtract number to self
- NA Evaluation, exact
4. Conditional statements
Python and VB6 both lack real switch statements:
I'm finished with this step
# Simple
if a == 1:
print ""
# Multiple conditions
if a == 1 and b == 2 or c == 3:
print ""
elif b == 2:
print ""
else:
print ""
' Simple
if a = 1 then
msgbox("")
end if
' Multiple conditions
If a = 1 And b = 2 Or c = 3 Rhen
Msgbox("")
Else if b = 2 Then
Msgbox("")
Else
Msgbox("")
End If
5. Looping statements
# For loop
for i in xrange(5):
print i
# While loop
i = 0
while (i <= 5):
print i
i += 1
' For loop
Dim i As Integer
For i = 0 to 5
Msgbox(i)
Next
' While loop
Dim i As Integer
i = 0
Do While i <= 5 Do
Msgbox(i)
i = i + i
Loop
6. Strings
Python has four types of strings:
I'm finished with this step
- Single and Double: There's no difference between single or double quoted strings you can use the appropriate one based on the content of the string to avoid having to escape characters. For example you could use "I'm happy" or 'The author "Big Daddy"' as appropriate.
- Triple: Python also supports triple quoted strings in either single or double quotes. The difference is that they are considered code documentation when placed at the top of a function or class, and can span multiple lines.
- Raw: Raw strings are prefixed by r or R and differ in that escape sequences are not used.
a = 'This is a simple string'
b = "this is a simple string"
c = "This is a string with two \t\t tabs"
d = """This string
spans multiple lines"""
e = r"This string does not contain any \t\t tabs"
You can find the official Python documentation on strings
here.
Note:
To my knowledge VB doesn't have anything other than double
quoted strings, which cannot span multiple lines or support escape
sequences like tabs/carriage returns ect.
7. String manipulation
Python is extremely strong at string manipulation. There's nothing VB
can do that Python can't do better.
I'm finished with this step
a = "abcdefg"
# First character
print a[0]
# First three characters
print a[0:3]
# Last three characters
print a[-3:]
# Middle three characters
print a[2:5]
# Find the position of a string in another string
print a.find('d')
# Everything to the left of the "d"
print a[0:a.find('d')]
# Convert a string to upper, and lower case
print a.upper(), a.lower()
# A string with the first letter of each word in caps
print "i love to eat apples".title()
# String right justified by dashes
print "Angry baby".rjust(15, '-')
# Last word in a sentence
print "I love apples".rsplit(' ', 1)[1]
# Sentence printed in reverse
a = "I love avacados and apples".split()
a.reverse()
print ' '.join(a)
# Return string without any trainling spaces
print "abcdefg ".rstrip()
# Replace a specific part of a string
print "I think apple's are the best fruit ever!".replace('apple', 'avacado')
# Replace whole words in a sentence
import re
print re.sub(r'\bby\b', ' BY ', "By the way, I walked by the bicycle shop today.")
# Multiple string replacements (usually you make a function out of this)
r = {'avacados':'oranges', 'apples':'kiwi'}
rc = re.compile('|'.join(map(re.escape, r)))
def translate(match):
return r[match.group(0)]
print rc.sub(translate, "I love avacados and apples")
Here
you can find the available Python string methods.
8. Arrays
Python has extensive support for arrays. Python implements this via:
I'm finished with this step
- Tuple - Immutable lists
- List - Mutable lists
- Dictionary - Key/value pairs
# Create a new list with three elements
a = [1, 2, 6]
# Add one more elements
a.append(3)
# Add three more elements
a.extend([4, 9, 10])
# Loop thru the list
for e in a:
print e
# Sort the list and print again
a.sort()
for e in a: print e
# Reverse the sort and print again
a.reverse()
for e in a: print e
# Print the first and last elements
print a[0], a[-1]
# Print and remove the last element in
print a.pop()
# Print and remove the first element in
print a.pop(0)
# Create a simple dictionary with two key/value pairs
a = {'color':'red', 'size':12}
# Add another key/value pair
a['price'] = 125.99
# Sort based on the keys
s = a.keys()
s.sort()
for key in s:
print a[key]
# Sort based on the keys in reverse
s = a.keys()
s.sort()
s.reverse()
for key in s: print a[key]
# Because the items() method returns a tuple, we can also use an alternate style loop
for key, value in a.items():
print key, value
# Sort based on the values in reverse
s = a.values()
s.sort()
s.reverse()
for value in s: print value
# Conditional statement based on presense/absense of key
a = {'color':'red', 'size':12}
if 'red' == a.get('color'): print True
if 10.00 >= a.get('price', 0.00): print 'greater than'
Here can find the official Python documentation for
dictionaries,
lists, and
tuples. You can also find tutorial style documentation
here.
This document was originally created on 05/10/2006
Conventions and tips for this howto document:
- Most examples in this howto will contain code snippets in both Python and VB6
- The Python examples in this howto have only been tested against Python-2.4.2
Disclaimer:
This page is not endorsed by gentoo.org or any other cool
cats. Any information provided in this document is to be used
at your own risk.