Understanding Python Syntax


The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. This section is designed to quickly get you up to speed on the syntax that is expected in Python.

Using Code Indentation

One of the first caveats programmers encounter when learning Python is the fact that there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. Both blocks in this example are fine:

if True:     print "True" else:   print "False"


However, the second block in this example will generate an error:

if True:     print "Answer"     print "True" else:     print "Answer"   print "False"


Creating MultiLine Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example:

total_sum = sum_item_one + \             sum_item_two + \             sum_item_three


Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example:

week_list = ['Monday', 'Tuesday', 'Wednesday',              'Thursday', 'Friday']


Quotation

Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes can be used to span the string across multiple lines. For example, all the following are legal:

word = 'word' sentence = "This is a sentence. paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""


Formatting Strings

Python allows for strings to be formatted using a predefined format string with a list of variables. The following is an example of using multiple format strings to display the same data:

>>>list = ["Brad", "Dayley", "Python Phrasebook", 2006] >>>letter = """ >>>Dear Mr. %s,\n >>>Thank you for your %s book submission. >>>You should be hearing from us in %d.""" >>>display = """ >>>Title: %s >>>Author: %s, %s >>>Date: %d""" >>>record = "%s|%s|%s|%08d" >>>print letter % (list[1], list[2], list[3]) Dear Mr. Dayley, Thank you for your Python Phrasebook book submission. You should be hearing from us in 2006. >>>print display % (list[2], list[1], list[0], list[3]) Title: Python Phrasebook Author: Dayley, Brad Date: 2006 >>>print record % (list[0], list[1], list[2], list[3]) Brad|Dayley|Python Phrasebook|00002006


Using Python Flow Control Statements

Python supports the if, else, and elif statements for conditional execution of code. The syntax is if expression: block. If the expression evaluates to true execute the block of code. The following code shows an example of a simple series of if blocks:

if x = True:     print "x is True" elif y = true:     print "y is True" else:     print "Both are False"


Python supports the while statement for conditional looping. The syntax is while expression: block. While the expression evaluates to true, execute the block in looping fashion. The following code shows an example of a conditional while loop:

x = 1 while x < 10:     x += 1


Python also supports the for statement for sequential looping. The syntax is for item in sequence: block. Each loop item is set to the next item in the sequence, and the block of code is executed. The for loop continues until there are no more items left in the sequence. The following code shows several different examples of sequential for loops.

The first example uses a string as the sequence to create a list of characters in the string:

>>>word = "Python" >>>list = [] >>>for ch in word: >>>    list.append(ch) >>>print list ['P', 'y', 't', 'h', 'o', 'n']


This example uses the range() function to create a temporary sequence of integers the size of a list so the items in the list can be added to a string in order:

>>>string = "" >>>for i in range(len(list)): >>>    string += list[i] >>>print string Python


This example uses the enumerate(string) function to create a temporary sequence. The enumerate function returns the enumeration in the form of (0, s[0]), (1, s[1]), and so on, until the end of the sequence string, so the for loop can assign both the i and ch value for each iteration to create a dictionary:

>>>dict = {} >>>for i,ch in enumerate(string): >>>    dict[i] = ch >>>print dict {0: 'P', 1: 'y', 2: 't', 3: 'h', 4: 'o', 5: 'n'}


This example uses a dictionary as the sequence to display the dictionary contents:

>>>for key in dict: >>>    print key, '=', dict[key] 0 = P 1 = y 2 = t 3 = h 4 = o 5 = n


The Python language provides break to stop execution and break out of the current loop. Python also includes continue to stop execution of the current iteration and start the next iteration of the current loop. The following example shows the use of the break and continue statements:

>>>word = "Pithon Phrasebook" >>>string = "" >>>for ch in word: >>>    if ch == 'i': >>>        string +='y' >>>        continue >>>    if ch == ' ': >>>        break >>>    string += ch >>>print string Python


Note

An else statement can be added after a for or while loop just the same as an if statement. The else is executed after the loop successfully completes all iterations. If a break is encountered, then the else statement is not executed.


There is currently no switch statement in Python. Often this is not a problem and can be handled through a series of if-elif-else statements. However, there are many other ways to handle the deficiency. The following example shows how to create a simple switch statement in Python:

>>>def a(s): >>>    print s >>>def switch(ch): >>>    try: >>>      {'1': lambda : a("one"), >>>       '2': lambda : a("two"), >>>       '3': lambda : a("three"), >>>       'a': lambda : a("Letter a") >>>      }[ch]() >>>    except KeyError: >>>      a("Key not Found") >>>switch('1') one >>>switch('a') Letter a >>>switch('b') Key not Found




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net