|
The BasicsProgram Execution Table Of Contents Functions and Methods Page Contents (hide) 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 // Hello World in Java. public class HelloWorld { public static void main( String[] args ) { System.out.println( "Hello World" ); } } and the equivalent in Python # Hello World in Python. print "Hello World" 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. StatementsThe 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 FormatStatements 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 multiple lines // Java statement. System.out.print ( "Hello World!!" ) ; 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 ( result = (someValue * 5 + anotherValue * 12) \ - (originalValue * 2) name = "John "\ "Smith" 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. myFunction( a, b, "name", avg )
CommentsA comment in Python, like most scripting languages, begins with a hash ( # This is a comment. result = 0 # so is this Statement BlocksPython uses the indentation level of statements to define statement blocks instead of begin/end delimiters or braces ( while i <= 20: total = total + i i = i + 1 print "The total = ", total In Java, this code segment would be written as // Java statement block. while( i <= 20 ) { total = total + i; i = i + 1; } print "The total = " + total;
Python statements which require a statement block include a colon ( 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:
IdentifiersIdentifiers 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 Primitive TypesPython 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. NumericPython has four primitive numeric classes including
-9 50 0x4F 077
456L 4567812391234L
3 + 4j 4.25 - 0.01j BooleanWhile Python does not have classes to represent single characters or unsigned integers, it does have a primitive boolean class and defines the two constants error = False continue = True StringsPython 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 ( '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. SequencesPython has two additional primitive sequence classes including
[ 0, 1, 2, 3 ] [ 'abc', 1, 4.5 ] []
1, 2, 3 ( 1, 4, 5.6, 'a' ) (5,) CollectionsPython provides two primitive collection types
{ 123 : "bob", 456 : "sally" }
VariablesAs 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. DeclarationsIn 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 name = "John Smith" idNum = 42 avg = 3.45 which would be equivalent to the following in Java // Java variable declarations String name = "John Smith"; int idNum = 42; double avg = 3.45; 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
AssignmentsPython uses a single equal sign ( When a new reference is assigned to an existing variable, the old reference is replaced. Consider the following code segment idNum = 70 which alters the 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 = "smith" In diagram form, the change would appear as follows When one variable is assigned to another student = name 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. ConstantsConsider 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 OperatorsPython supports the common mathematical operations for both integer and floating-point values as found in Java
and two operators not available in Java
The statement 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 ( Division and RemainderPython supports both integer and real division. The Mixed TypesIf 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 Type ConversionsPython 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. Main RoutineEvery 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 Program: Summation.java File: Summation.java
// Sumation.java // Compute the sum of the first 100 integer values and print // the results. public class Summation { public static void main( String[] args ) { final int NUM_VALUES = 100; int summation = 0; int i = 0; while( i <= NUM_VALUES ) { summation = summation + 1; i = i + 1; } System.out.println( "The sum of the first " + NUM_VALUES + " integers is " + summation ); } } In Python, the first statement to be executed, is the first statement at file level (outside of all functions and class definitions). The Program: summation.py File: summation.py
# summation.py # Compute the sum of the first 100 integer values and print # the results. # Initialize a constant variable. NUM_VALUES = 100 # Compute the sum. summation = 0 i = 1 while i <= NUM_VALUES: summation = summation + i i = i + 1 # Print the results. print "The sum of the first", NUM_VALUES, \ "integers is", summation | |||||||||||||||||||||||||||
© 2006 - 2008: Rance Necaise - Page last
modified on July 30, 2008, at 11:36 PM
|