Book » The Basics »

 


Program Execution Book Statements


The Basics

While Python and Java are both object-oriented languages their syntax differs greatly. In this section, we explore the syntax and program structure of Python needed to construct the most basic programs.

Statements

The Python syntax, as with all languages, is very specific when it comes to statement structure. Being familiar with Java, the structure of a Python program may take some getting used to. On the other hand, if you have experience using a scripting language such as Perl or Ruby, the structure will be more familiar.

Line Format

Statements in Python do not end with a semicolon as they do in Java. Instead, the end of a statment is indicated by the normal line termination (new line or carriage return)

  print "Hello World!!"
  print "How are you today?"

Since statements are terminated with a semicolon in Java, a single statement can span many lines

  // Java statement.
  System.out.print
    (
      "Hello World!!"
    )
  ;

In Python, however, since the end of line indicates the end of a statement, the interpreter expects a statement to stay on a single line. If a statment is too long to fit on a single line, however, you can use a slash (\) at the end of the line and continue the statement onto the next line. String literals can also be spread across multiple lines using the backslash.

  result = (someValue * 5 + anotherValue * 12) \
           - (originalValue * 2)

For function calls and method invocations which use a pair of parentheses, Python will automatically search for the closing parenthesis and thus slashes are not needed to indicate a line continuation.

  myFunction( a, b, 
              "name",
              avg )
Note: String literals can not be broken across lines without the use of the backslash.

Comments

A comment in Python, like most scripting languages, begins with a bash (#) symbol and continues until the end of the line.

  # This is a comment.
  result = 0   # so is this

Statement Blocks

Python does not use begin/end delimerters or braces ({}) to indicate a statement block. Instead, statement indentation is used to define individual blocks as illustrated below

  while i <= 20:
     total = total + i
     i = i + 1
  print "The total = ", total

In Java, this code segment would appear as

  // Java statement block.
  while( i < 20 ) 
  {
    total = total + i;
    i = i + 1;
  }
  print "The total = " + total;
Note: Good programmers typically use indentation to specify statements within a given block no matter which language they are using. In Python, the indentation is required.

The while loop requires a statement block which is indicted by the colon (:) following the loop condition. The two statements following the line containing while form the body of the loop as indicted with an indentation of three spaces.

The number of spaces the statements within a block are indented does not matter. What is important is that all statements within a block must be indented to the same level. The first statement which is indented less than the previous ones indicates the first statement outside of the statement block. In the previous example, this would be the line containing the print statement.

Note: The indentation must be done with actual blank spaces and not physical tab characters.

Identifiers

Python uses identifiers to name things — variables, functions, classes, modules, and etc. — as is done in Java.

Properties

The rules for naming identifiers in Python are very similar to that of Java. The only difference is that the underscore is the only special character that can be used; a dollar sign is not allowed. Thus, Python identifiers

  • may only contain letters, digits, or the underscore, and
  • may not begin with a digit.

Python is case sensitive. Thus, all of the following identifiers are different:

  Total   ToTaL  total

Reserved Words

You can not use a reserved word as a user-defined identifier. The following is a list of reserved words in Python

and     assert    break     class     continue
def     del       elif      else      except
exec    finally   for       from      global
if      import    in        is        lambda
not     or        pass      print     raise
return  try       while 	

Primitive Types

Python is entirely object-based which means all data values in Python are represented as objects including the simple primitive types.

Numeric

Python has four numeric types including

integer
similar to an int in Java but the size of a Python integer is platform dependent; they consist of at least 32-bits. Octal and hexadecimal literals can also be specified as in Java.
   -9    50     0x4F     077  
long integer
represented in software and provide unlimited precision. There is no equivalent type in Java. The use of this numeric type should be limited since it is implemented in software and requires extra computations. A long integer literal is indicated by following the value with a capital L
   456L      4567812391234L
float
similar to a double in Java but the size is platform dependent.
complex
used to represent complex numbers which contain real and imaginary parts. There is no equivalent type in Java. The two components of a complex value are each stored as a float.
   3 + 4j       4.25 - 0.01j

Python does not have a data type to represent single characters, boolean values or unsigned integers.

Sequence Types

Python has four built-in sequence types including

string
an ordered sequence of characters whose values can not change once assigned. String literals are represented using a pair of either single (@) or double (@) quotes to enclose the character sequence.
  'string'     "another string"     "c"
Characters in Python are represented as a string containing a single character. More information is available on the use of strings in Python.
list (or array)
an ordered sequence of objects of any type. A literal list is specified using square brackets
    [ 0, 1, 2, 3 ]     [ 'abc', 1, 4.5 ]    []
tuple
similar to a list type but a tuple can not be changed once it has been created. A tuple literal is specified using a comma separated list and may be enclosed within parens
   1, 2, 3     ( 1, 4, 5.6, 'a' )     (5,)
dictionary (or hash)
provides a hashing structure in which each item contains a key and a value. A dictionary literal is represented by enclosing one or more key/value pairs within braces
   { 123 : "bob",  456 : "sally" }

The sequence types will be discussed in full detail in later sections.

Variables

As previously indicated, all data types in Python are treated as objects including the primitive types. Thus, all variables in Python store references to objects. In Java, the primitives were stored as static variables while objects were stored as references.

Declarations

In Python, variables are not specifically created using a variable declaration. Instead, variables are created automatically when they are assigned an object reference. The variable’s data type is determined by the type of object it references

  name = "John Smith"
  id = 42
  avg = 3.45

In this example, the literal values are actually nameless objects of their respective types. Thus, a literal value of 42 is actually an integer object which has the value 42. Each literal value within a program results in a unique object.

The equivalent statements in Java would be written as

  // Java variable declarations
  String name = "John Smith";
  int id = 42;
  double avg = 3.45;
Note. As in Java variable can not be used before it has been assigned a reference to some object. Attempting to do so will generate an error.

Assignments

Python also uses a single equal sign (=) for assigning an object reference to a variable. When an assignment statement is used, the reference of the object on the right-hand side is copied and stored in the variable on the left hand side, not the data. Thus, creating an alias as is the case with references in Java.

Constants

Consider the following Java code segment which creates two constant variables

  // Java constants
  final double TAX_RATE = 0.06;
  final int MAX_SIZE = 100;

Python does not support constant variables. Instead, it is common practice for the programmer to specify constant variables as those named with all capital letters. To create the two constant variables, you should write

  TAX_RATE = 0.06
  MAX_SIZE = 100

It is important to note, however, there is no way to enforce the concept of a constant variable and keep its value from being changed. By following the standard convention, however, you provide information to yourself and others that you intend for a variable in all caps to be constant throughout the program.

Mathematical Operators

Python supports the common mathematical operations for both integer and floating-point values as found in Java.

OperatorDescription
*Multiplication
/Division
%Modulus
+Addition
-Subtraction

The operators have the same order of precedence as that in Java; () can be used to override the order of precedence. Python also supports the augmented assignment operators

  *=   /=   %=   +=   -=

but it does not have the increment (++) and decrement () operators.

Mixed Types

If the two operands are of the same type (i.e. float), the type of the resulting value will be the same; if they are different, the operand of lesser rank will be converted to the higher rank1. In Python, the ranks of the numeric types are

    int > long > float > complex

Integer Remainder

Both integer and real division are supported in Python as in Java. If both operands are integers, then integer division is performed with the real part bein truncated. If at least one of the operands is a real value, then real division is used resulting in a real value. The remainder of integer division can be obtained using the modulus operator.

Functions

While Python is an object-oriented language, it allows the use of functions for procedural programming. A function in Python is equivalent to a static method in Java. That is, they are defined and used independent of an object. The main difference is that Python functions are not defined within a class definition but within the file scope. Thus, when invoking or calling a function, only the function name is used.

  y = abs( x )

Multiple parameters are separated with commas as in Java. When passing a parameter to a function, the reference to the object is passed and not the value itself. This is the expected behavior since Python represents all data as objects and all variables contain references.

Python has a number of built-in functions that are always available or you can create your own user-defined functions.

Objects and Methods

1
© 2006 - 2008: Rance Necaise - Page last modified on August 10, 2006, at 08:17 AM