Python Training Guide

Learn Python using your VBScript knowledge

Table of Contents

VBScript to Python Training Guide

Welcome to your journey from VBScript to Python! This guide is specifically designed for programmers who are comfortable with VBScript and Classic ASP and want to learn Python for modern web development.

Python is a powerful, versatile programming language that has become one of the most popular choices for web development, data analysis, automation, and many other applications. Unlike VBScript, which is primarily used in Windows environments and Classic ASP, Python is cross-platform and has a vast ecosystem of libraries and frameworks.

Why Learn Python?

Coming from VBScript, you'll find Python offers several advantages:

  • Cross-platform compatibility: Python runs on Windows, Mac, Linux, and many other systems
  • Rich ecosystem: Thousands of libraries and frameworks available
  • Modern web frameworks: Flask, Django, FastAPI for building web applications
  • Strong community: Extensive documentation, tutorials, and community support
  • Career opportunities: Python is in high demand across many industries

Key Differences to Keep in Mind

Before we dive into the comparisons, here are some fundamental differences between VBScript and Python:

  1. Indentation matters: Python uses indentation to define code blocks instead of keywords like "End If" or "End Function"
  2. Case sensitivity: Python is case-sensitive, unlike VBScript
  3. Strong typing: While Python is dynamically typed, it's more strict about type operations than VBScript
  4. Object-oriented: Python is fully object-oriented from the ground up
  5. Zero-based indexing: Arrays (lists) start at index 0, not 1

Basic Syntax Comparison

Let's start with the most fundamental differences in syntax between VBScript and Python.

Hello World

VBScript (Classic ASP):

<%
Response.Write("Hello World!")
%>

Python:

print("Hello World!")

Comments

VBScript:

' This is a single line comment
REM This is also a comment

' Multi-line comments require multiple single quotes
' Line 1 of comment
' Line 2 of comment

Python:

# This is a single line comment

"""
This is a multi-line comment
Line 1 of comment
Line 2 of comment
"""

# You can also use triple single quotes
'''
Another multi-line comment
'''

Line Continuation

VBScript:

' Use underscore for line continuation
Dim longString
longString = "This is a very long string that " & _
             "spans multiple lines using " & _
             "the underscore character"

Python:

# Python automatically continues lines inside parentheses, brackets, or braces
long_string = ("This is a very long string that "
               "spans multiple lines using "
               "implicit line continuation")

# Or use backslash (less preferred)
long_string = "This is a very long string that " \
              "spans multiple lines using " \
              "explicit line continuation"

Case Sensitivity

VBScript (Case Insensitive):

Dim myVariable
MyVariable = 10
MYVARIABLE = 20
' All three refer to the same variable

Python (Case Sensitive):

my_variable = 10
MyVariable = 20
MYVARIABLE = 30
# These are three different variables!

Code Blocks and Indentation

This is one of the biggest differences between VBScript and Python. VBScript uses keywords to define code blocks, while Python uses indentation.

VBScript:

If age >= 18 Then
    Response.Write("You are an adult")
    If age >= 65 Then
        Response.Write("You are a senior")
    End If
Else
    Response.Write("You are a minor")
End If

Python:

if age >= 18:
    print("You are an adult")
    if age >= 65:
        print("You are a senior")
else:
    print("You are a minor")

Notice how Python doesn't need "End If" - the indentation defines where the code block ends. This makes Python code cleaner but requires consistent indentation (typically 4 spaces).

Variables and Data Types

This is a major difference between VBScript and Python. VBScript has only one data type (Variant), while Python has several specific data types.

Variable Declaration and Assignment

VBScript:

' Variables must be declared with Dim (or Public/Private)
Dim myNumber
Dim myString
Dim myDate

' Then assigned values
myNumber = 42
myString = "Hello"
myDate = #01/01/2024#

' Or declare and assign in separate statements
Dim userName : userName = "John"

Python:

# No declaration needed - variables are created when assigned
my_number = 42
my_string = "Hello"
my_date = "2024-01-01"  # Python handles dates differently

# Multiple assignment
user_name = "John"

Data Types Comparison

VBScript Variant Content Python Equivalent Example
Integer int age = 25
Decimal float price = 19.99
String str name = "John"
Boolean bool is_active = True
Date datetime from datetime import datetime
Array list numbers = [1, 2, 3]
Nothing/Null None result = None

Working with Numbers

VBScript:

Dim num1, num2, result
num1 = 10
num2 = 3

result = num1 + num2    ' Addition: 13
result = num1 - num2    ' Subtraction: 7
result = num1 * num2    ' Multiplication: 30
result = num1 / num2    ' Division: 3.333...
result = num1 \ num2    ' Integer division: 3
result = num1 Mod num2  ' Modulus: 1
result = num1 ^ num2    ' Exponentiation: 1000

Python:

num1 = 10
num2 = 3

result = num1 + num2    # Addition: 13
result = num1 - num2    # Subtraction: 7
result = num1 * num2    # Multiplication: 30
result = num1 / num2    # Division: 3.333... (always returns float)
result = num1 // num2   # Integer division: 3
result = num1 % num2    # Modulus: 1
result = num1 ** num2   # Exponentiation: 1000

Working with Strings

VBScript:

Dim firstName, lastName, fullName
firstName = "John"
lastName = "Doe"

' String concatenation with &
fullName = firstName & " " & lastName

' String functions
Dim upperName, lowerName, nameLength
upperName = UCase(fullName)      ' "JOHN DOE"
lowerName = LCase(fullName)      ' "john doe"
nameLength = Len(fullName)       ' 8

' Substring
Dim firstThree
firstThree = Left(fullName, 3)   ' "Joh"

Python:

first_name = "John"
last_name = "Doe"

# String concatenation with +
full_name = first_name + " " + last_name

# Or using f-strings (preferred in modern Python)
full_name = f"{first_name} {last_name}"

# String methods
upper_name = full_name.upper()      # "JOHN DOE"
lower_name = full_name.lower()      # "john doe"
name_length = len(full_name)        # 8

# Substring (slicing)
first_three = full_name[:3]         # "Joh"
last_three = full_name[-3:]         # "Doe"

Control Structures

Control structures in Python work similarly to VBScript but with different syntax. The logic remains the same, but the way you write it changes.

If Statements

VBScript:

Dim score
score = 85

If score >= 90 Then
    Response.Write("Grade: A")
ElseIf score >= 80 Then
    Response.Write("Grade: B")
ElseIf score >= 70 Then
    Response.Write("Grade: C")
ElseIf score >= 60 Then
    Response.Write("Grade: D")
Else
    Response.Write("Grade: F")
End If

Python:

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Comparison Operators

VBScript Python Description
= == Equal to
<> != Not equal to
< < Less than
> > Greater than
<= <= Less than or equal
>= >= Greater than or equal

For Loops

VBScript:

' Simple For loop
Dim i
For i = 1 To 10
    Response.Write(i & "<br>")
Next

' For loop with step
For i = 0 To 20 Step 2
    Response.Write(i & "<br>")
Next

' For Each loop with array
Dim fruits(2)
fruits(0) = "Apple"
fruits(1) = "Banana"
fruits(2) = "Orange"

Dim fruit
For Each fruit In fruits
    Response.Write(fruit & "<br>")
Next

Python:

# Simple for loop using range
for i in range(1, 11):  # range(1, 11) gives 1 to 10
    print(i)

# For loop with step
for i in range(0, 21, 2):  # range(start, stop, step)
    print(i)

# For each loop with list
fruits = ["Apple", "Banana", "Orange"]

for fruit in fruits:
    print(fruit)

# If you need the index too
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

Functions and Procedures

VBScript has both Sub procedures (no return value) and Function procedures (return value). Python only has functions, but they can optionally return values.

Basic Functions

VBScript Sub (No Return Value):

Sub DisplayMessage(message)
    Response.Write("<p>" & message & "</p>")
End Sub

' Calling the sub
Call DisplayMessage("Hello World")
' Or without Call keyword
DisplayMessage("Hello World")

VBScript Function (With Return Value):

Function AddNumbers(num1, num2)
    AddNumbers = num1 + num2
End Function

' Using the function
Dim result
result = AddNumbers(5, 3)
Response.Write("Result: " & result)

Python Functions:

# Function without return value (like VBScript Sub)
def display_message(message):
    print(f"<p>{message}</p>")

# Calling the function
display_message("Hello World")

# Function with return value (like VBScript Function)
def add_numbers(num1, num2):
    return num1 + num2

# Using the function
result = add_numbers(5, 3)
print(f"Result: {result}")

Web Development Transition

Moving from Classic ASP with VBScript to Python web development involves learning new frameworks and approaches. Here's how to make that transition.

Flask Framework

Flask is Python's equivalent to Classic ASP - it's lightweight and easy to learn. Here's how familiar Classic ASP concepts translate to Flask:

Classic ASP Page Structure:

<%@ Language="VBScript" %>
<%
Dim userName
userName = Request.Form("username")

If userName <> "" Then
    Response.Write("Hello " & userName)
End If
%>

<html>
<body>
    <form method="post">
        <input type="text" name="username">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Flask Equivalent:

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def home():
    username = ""
    message = ""
    
    if request.method == 'POST':
        username = request.form.get('username', '')
        if username:
            message = f"Hello {username}"
    
    html = '''
    <html>
    <body>
        {% if message %}
            <p>{{ message }}</p>
        {% endif %}
        <form method="post">
            <input type="text" name="username" value="{{ username }}">
            <input type="submit" value="Submit">
        </form>
    </body>
    </html>
    '''
    
    return render_template_string(html, message=message, username=username)

if __name__ == '__main__':
    app.run(debug=True)

Next Steps

Now that you understand the basic syntax differences, here are your next steps:

  1. Practice the basics: Work through the Python practice exercises
  2. Learn Flask: Start building simple web applications
  3. Understand templates: Learn Jinja2 templating (Flask's template engine)
  4. Database integration: Learn how to work with databases in Python
  5. Build projects: Create real applications to solidify your knowledge

Remember, the concepts you know from VBScript and Classic ASP are still valuable - you're just learning a new syntax and some modern approaches to web development!