Book » Writing Python Programs »

 

Writing Python Programs

Python programs are typically constructed by creating a source file using your favorite text editor or Python IDE. Python also provides an interactive mode for testing a single statment or a small code segments.

Basic Structure

The structure of a Python program is similar to that used in other languages but with several important differences. Consider the following program which computes and prints the sum of the first 100 positive integers.

# sum.py
# Compute the sum of the first 100 integer values and print
# the results.

# Initialize a constant variable.
NUM_VALUES = 100

# Compute the sum.
sum = 0
i = 1
while i <= NUM_VALUES:
   sum = sum + i
   i = i + 1

# Print the results.
print "The sum of the first", NUM_VALUES, \
      "integers is", sum
 

Statements

Structure

Main Routine

Python, unlike C, C++, and Java, does not use a main routine as the entry point for execution. Instead, like Perl, Ruby, and Php, the first executable statement at the top-most or global level is the first statement executed. In the sum.py example, the statement

(:codeblock lang=python :)
NUM_VALUES = 100

is the first statement executed. Execution then continues to the next statement and then the next. Functions and classes can also be defined within a Python program. But they are only executed, when the function or a related method is invoked.

Differences

Several important differences include:

  1. Semicolons are not used to flag the end of a statement. In Python, the end of line indicates the end of a statement.
  2. Python does not use a begin/end delimeter to represent statement blocks.

More

programming l Consider the following sample Python program saved in the file first.py A Python program is nothing more than a text file containing the programming instructions. Let’s start with the classic “Hello World” program.

Program Execution

=python print "Hello World"


Book

© 2006 - 2008: Rance Necaise - Page last modified on August 04, 2006, at 03:52 PM