|
The BasicsPage 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. 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 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 ( 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.
CommentsA comment in Python, like most scripting languages, begins with a bash ( # This is a comment. result = 0 # so is this Statement BlocksPython does not use begin/end delimerters or braces ( 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 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 Note: The indentation must be done with actual blank spaces and not physical tab characters.
IdentifiersPython uses identifiers to name things — variables, functions, classes, modules, and etc. — as is done in Java. PropertiesThe 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 Reserved WordsYou 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 TypesPython is entirely object-based which means all data values in Python are represented as objects including the simple primitive types. NumericPython has four numeric types including
-9 50 0x4F 077
456L 4567812391234L
3 + 4j 4.25 - 0.01j Python does not have a data type to represent single characters, boolean values or unsigned integers. Sequence TypesPython has four built-in sequence types including
'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.
[ 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. VariablesAs 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. DeclarationsIn 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 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.
AssignmentsPython also uses a single equal sign ( 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.
The operators have the same order of precedence as that in Java; *= /= %= += -= but it does not have the increment ( 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 rank1. In Python, the ranks of the numeric types are int > long > float > complex Integer RemainderBoth 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. FunctionsWhile Python is an object-oriented language, it allows the use of functions for procedural programming. A function in Python is equivalent to a 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
|