Page Contents (hide)
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.
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.
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 )
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
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;
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.
Python uses identifiers to name things — variables, functions, classes, modules, and etc. — as is done in Java.
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
Python is case sensitive. Thus, all of the following identifiers are different:
Total ToTaL total
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
Python is entirely object-based which means all data values in Python are represented as objects including the simple primitive types.
Python has four numeric types including
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
L
456L 4567812391234L
double
in Java but the size is platform dependent.
3 + 4j 4.25 - 0.01j
Python does not have a data type to represent single characters, boolean values or unsigned integers.
Python has four built-in sequence types including
@) or double (@’
) quotes to enclose the character sequence.
'string' "another string" "c"
[ 0, 1, 2, 3 ] [ 'abc', 1, 4.5 ] []
1, 2, 3 ( 1, 4, 5.6, 'a' ) (5,)
{ 123 : "bob", 456 : "sally" }
The sequence types will be discussed in full detail in later sections.
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.
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;
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.
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.
Python supports the common mathematical operations for both integer and floating-point values as found in Java.
Operator | Description |
* | 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.
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
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.
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.
—