Python and Java are both object-oriented languages but their syntax differs greatly. In this section, we explore the syntax and program structure of Python needed to construct the most basic programs.
Before we begin, let’s look at the classic “Hello World” program written in Java
and the equivalent in Python
From this example, one obvious difference between the two languages is the wordiness of Java. You will come to see that Python provides built-in operators and shortcuts for many of the common operations performed in computer 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)
Since statements are terminated with a semicolon in Java, a single statement can span multiple lines
Since the end of line indicates the end of a statement, the Python 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 backslash (\
) at the end of the line and continue the statement onto the next line.
For function calls and method invocations which use a pair of parentheses, Python will automatically search for the closing parenthesis and thus backslashes are not needed to indicate line continuation.
![]() | Note:
String literals can not be broken across lines without the use of the backslash. |
A comment in Python, like most scripting languages, begins with a hash (#
) symbol and continues until the end of the line.
Python uses the indentation level of statements to define statement blocks instead of begin/end delimiters or braces ({}
)
In Java, this code segment would be written as
![]() | 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. |
Python statements which require a statement block include a colon (:
) as part of their syntax. In this example, the condition of the while
statement includes a colon which flags a required statement block.
Only statements within a block or the parts of a statement continued from a previous line may be indented. The top-level statements of the program, which are at file level, must have no indentation. A few important notes related to statement blocks:
![]() | Warning:
All statements within a given block must be indented with either blank spaces or tab characters, but not a mixture of the two. |
Identifiers in Python are case senstive and may be of any length. The rules for constructing an indentifier are very similar to those 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
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
There is also a group of identifiers used to name built-in functions and standard classes. You should avoid using these for user-defined identifiers
float int string
Python is entirely object-based which means all data values in Python are represented as objects and are defined by classes including the simple primitive types.
Python has four primitive numeric classes including
int
in Java but the size of a Python integer is platform dependent. Though, a Python integer does 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
While Python does not have classes to represent single characters or unsigned integers, it does have a primitive boolean class and defines the two constants True
and False
error = False continue = True
Python strings are an immutable ordered sequence of characters whose value can not change once created. String literals are represented using a pair of either single (‘
) or double (“
) quotes to enclose the character sequence.
'string' "another string" "c"
Python also allows for the creation of block strings using tripple quotes, details for which are provided in a later chapter. Characters in Python are represented as a string containing a single character.
Python has two additional primitive sequence classes including
[ 0, 1, 2, 3 ] [ 'abc', 1, 4.5 ] []
1, 2, 3 ( 1, 4, 5.6, 'a' ) (5,)
Python provides two primitive collection types
{ 123 : "bob", 456 : "sally" }
As previously indicated, all data types in Python are treated as classes including the primitive types. Thus, all variables in Python store references to objects. In Java, primitives are automatically created and stored directly in memory while objects are dynamically created and stored as references.
In Python, variables are not specifically created using a variable declaration. Instead, they are created automatically when they are assigned an object reference. The following code segment creates three variables
which would be equivalent to the following in Java
A variable itself does not have a type and thus can store a reference to any type of object. It is the object, which has a data type. The following diagram illustrates the creation of the three variables from the example above.
Literal values are actually nameless objects of their respective type. Thus, a literal value of 42
is actually an integer object which has the value 42. Each unique literal value within a program results in a unique object.
![]() | Note:
As in Java, a variable can not be used before it has been assigned a reference to some object. Attempting to do so will generate an error. |
Python 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.
When a new reference is assigned to an existing variable, the old reference is replaced. Consider the following code segment
which alters the idNum
variable reference
An existing variable can be assigned a reference of any type. Thus, no type checking is performed when an assignment operation is performed. In the following code segment, the idNum
variable is assigned a string instead of an integer
In diagram form, the change would appear as follows
When one variable is assigned to another
the result is an alias as in Java since both variables refer to the same object.
When all references to an object are removed, the object is automatically destroyed as is done in Java.
Consider the following Java code segment which creates two constant variables
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
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 |
% | Modulus |
/ | Division |
* | Multiplication |
+ | Addition |
- | Subtraction |
and two operators not available in Java
Operator | Description |
** | Exponentiation |
// | Division (floored) |
The statement x ** y
computes the exponentation x
y while x // y
computes the mathematical floor of x / y
in which the fractional part is truncated. Both of these operators can be used with integer or real values.
The operators have the expected order of precedence as found in mathematics and parentheses can be used to override that order. Python also supports the augmented assignment operators
+= -= *= /= %= **= //=
but it does not have the increment (++
) and decrement (--
) operators.
Python supports both integer and real division. The /
operator works the same as in Java; if both operands are integers, integer division is performed, otherwise the result is real division. The remainder of integer division is computed using the %
operator. Python adds the //
operator which always performs integer division, no matter what type of operands are used. Thus
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 rank. The conversion is only temporary for use in the evaluation of the given operator; the actual object is not modified. In Python, the ranks of the numeric types are
int > long > float > complex
Python will implicitly convert between the numeric types as needed. All other conversions, however, must be explicit. Python provides a number of built-in functions to handle these conversions. Descriptions and examples will be provided in the following chapters.
Every program must have a unique starting point; a first statement to be executed. In Java, the starting point is the first statement within the main() routine. Consider the following Java program
In Python, the first statement to be executed, is the first statement at file level (outside of all functions and class definitions). The Summation.java
program would be written in Python as follows