CHAPTER 7

image

Keywords

Keywords are special reserved words that cannot be used as variable names. Keywords will change over time as Python versions change. Below is a short program that will allow you to obtain a list of keywords specific for your version of Python. It is written using Python 3.x syntax, but will work for version 2.7 as well.

Import keyword
print(keyword.kwlist)

List of Python Keywords

Below is a list of Python keywords, in alphabetical order, for version 2.7.1.

and             as               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           with             yield

In addition, Python 3.x adds four keywords and removes one. The additional keywords are:

False            None            True             nonlocal

The keyword exec has been removed from Python 3.x.

The list below is ordered by type.

table07-01.jpg

Keywords Explained

Below we will examine each keyword, what it does and how it would be used. The keywords for Python 2.x are presented in alphabetical order for easy reference with the additional keywords for Python 3.x following. The following format will be used for each keyword:

  • Keyword
  • Used for or in
  • Explanation and code (where appropriate)

and

Boolean Evaluation

The and keyword evaluates two equations, and if both are true then returns true. If either of the two are false, then returns false.

>>> a = 1
>>> b = 2
>>> a > 1 and b == 2
False
>>> b == 2 and a > 1
False
>>> a > 0 and b == 2
True
>>> a < b and b == 2
True

as

Libraries, Modules

Allows us to create a different reference name, or alias, for a module or function imported into our program.

>>> import sys as s
>>> print s.version
2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]

assert

Debugging

The assert keyword forces a test of an expression and the compiler will error out if the expression is false.

>>> c = 3
>>> assert c<1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AssertionError
>>> assert c > 4
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AssertionError
>>> assert c == 3
>>>

break

Loops

The break keyword allows the current loop to be aborted early. The following snippet shows that when the counter variable ‘i’ reaches 5, the loop will be exited.

for i in range(10):
    print i
    if i == 5:
        break

0
1
2
3
4
5

class

Misc.

The class keyword allows you to create a new class, which is important for Object Oriented Programming.

The class must be instantiated by assigning it to a variable. Then we can call any of the functions within the class.

class test1:
    def __init__(self,inval):
        self.a = inval #dummy statement

    def run(self):
        for cntr in range(self.a):
          print cntr

t = test1(20)
t.run()

continue

Conditional Statements, Loops

The continue keyword is used in loops to skip the rest of the code within the loop for that iteration of the loop. In the following snippet, notice that if the cntr variable hits the number 5, it will skip the print statement and continue back to the top of the loop.

for cntr in range(10):
    if cntr == 5:
        continue
    print cntr

0
1
2
3
4
6
7
8
9

def

Functions

The def keyword allows us to create a function.

def log(strng):
    print(strng)

log("This is a test...")

This is a test...

del

Misc

The del keyword removes a value or values from a list given its index.

>>> lst = [1,2,3,4,5,6]
>>> lst
[1, 2, 3, 4, 5, 6]
>>> del lst[3]
>>> lst
[1, 2, 3, 5, 6]

In the above example, we request that the item at index position 3, in list lst be deleted. Remember, all indexes are zero based, so that would be the number 4.

You can also delete items in a list using a slice. The command del lst[:2] would delete the first two items in the list, leaving (after the first del command) [3,5,6].

elif

Conditional Statements

The elif statement is an optional part of the if conditional statement. It is used when the expression(s) above it evaluate to False and you want to test other expressions. The elif statement is at the same indention level as the if statement line and is followed by an additional statement to be evaluated then by a colon. The code block must be indented. There can be as many elif statements as needed and may be followed by an else statement if desired (see below).

a = 3
if a == 1:
    print("Variable A = 1")
elif a == 2:
    print("Variable A = 2")
elif a == 3:
    print("Variable A = 3")
else:
    print("Variable is greater than 3")

else

Conditional Statements

The else keyword is an optional part of the if conditional statement. It is used when the if statement (or any elif statements) evaluates to false. This can be considered an “all else has failed, so do the following code.” The else keyword is at the same indentation level as the if statement line and is followed immediately by a colon. No expressions are allowed on the line containing the else keyword. The logic block that needs to be executed is indented at the same level as the logic block for the main if statement. The else keyword is also an optional part of the for and while loops.

a = 3
if a > 5:
    print("Variable a is greater than 5")
else:
    print("Variable a is less than 5")

except

Error Handling

The except keyword is used with the try keyword for error trapping. If the code within the try block fails for any reason, the code within the except block will be executed. This code can be a simple pass statement, or something that logs or outputs the error information. There may also be several different except statements, each handling a specific error.

try:
    # try block code here
except:
    # except block code here

The except clause may contain some sort of test for the type of error that was encountered.

try:
    # try block code here
except TypeError:
    # except block code here

exec

Misc.

Executes Python statements that are stored in a string or a file. (version 2.x only). This could create a security problem and should only be used as a last resort.

>>> code = 'print "This is a test"'
>>> exec code
'print "This is a test"'

finally

Error Handling

The finally keyword is part of the try / except error handling system. The code in the finally block will be always be run leaving the try code block regardless of whether an error was encountered or not. This is a good place to put code that closes files or releases network resources.

try:
    # try block code here
except:
    # except block code here
finally:
    # finally block code here that will always run.

for

Loops

The for keyword creates a loop controlled by the parameters that follow the keyword Like the if statement the keyword is followed by a sequence (iterable such as a list or string) followed by a colon. All programming statements that are to be done within the loop is indented. In its simplest form the for loop looks like this:

for I in range(10):
    print(i)

More about for loops can be found in Chapter 5.

from

Libraries

The from keyword allows us to import a variable or function directly from a specific library module without having to qualify the library name (i.e., sys.path). It also imports only the requested routines from the library. If you wish to import all functions from a library you can use something like "import sys" or "from sys import *".

>>> from sys import path
>>> path
['', 'C:\WINDOWS\system32\python27.zip', 'C:\Python27\DLLs', 'C:\Python27
lib', 'C:\Python27\lib\plat-win', 'C:\Python27\lib\lib-tk', 'C:\Python27
', 'C:\Python27\lib\site-packages']

global

Variables

As I discussed in cCapter 2, variables have a limited scope. If a variable is declared within a function, any manipulation of that variable is limited to that code block within the function, even if the name of the variable is the same of one that is used outside of that function. The global keyword allows the manipulation to affect other variables outside of the scope of that routine.

x = 3
def tryit():
    global x
    x = 6
def tryit2():
    global x
    x = x * 3
>>> x
6
>>> tryit2()
>>> x
18
>>> tryit()
>>> x
6

if

Conditional Statements

The if keyword is used for conditional statements. In its simplest form, the if statement consists of an expression that gets evaluated at run time and a block of code (which can consist of single line) that will get executed at run time if the expression is true. The if statement can be extended by the elif and else keywords explained earlier. The format for the if statement starts with the if keyword, followed by the expression and a colon. The block of code that is to be executed if the expression is true must be indented. All indented code will be considered as part of the logic block. If the expression is not true, the code will pass to the next unindented line of code, which could be an elif, else or just the next line of the program code.

a = 3
if a > 2:
    print("Variable A is greater than 2")

import

Libraries

The import keyword allows code from outside libraries to be included in our code.

>>> import sys
>>> print(sys.version)
2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]

in

Evaluation, Loops

The in keyword can be used to test the existence of a value within a tuple, list or other iterable.

>>> a = (1,2,3)
>>> 4 in a
False
>>> 3 in a
True

You can also use the in keyword as part of a for loop. In the following snippet, a list that contains the values from 0 to 9 is created by the “range” function and that list is iterated or walked to do the loop.

for i in range(10):
    print i,

0 1 2 3 4 5 6 7 8 9

is

Boolean Evaluation

The is keyword evaluates two expressions, checking to see if they are the same object. You can not evaluate two empty lists (x = [] and y = []) because they are not the same object.

>>> m = 2
>>> x = 2
>>> m is x
True
>>> m is 2
True

lambda

Functions

Allows the creation of an anonymous inline function.

>>> a = lambda d,e,f : d+e+f+3
>>> a(1,2,3)
9
>>> t = (lambda a='one',b='two',c='three' : a+b+c)
>>> t('four','five')
'fourfivethree'

not

Boolean Evaluation

The not keyword negates a Boolean value. True becomes False and False becomes True.

>>> a = 1
>>> b = 2
>>> not(a == b) # a==b is false. not(False) becomes True
True

or

Boolean Evaluation

Tests all expressions, and if at least one is True then returns True, otherwise returns False.

a = "Test"
b = "Of"
c = "OR"
if a == "1" or b == "Three" or c == "ORD":
    print("True")
else:
    print("False")

False

if a == "1" or b == "Three" or c == "OR":
    print("True")
else:
    print("False")

True

pass

Conditional Statements, Loops

The pass keyword allows you to “stub” out a function or conditional option that is not yet finished.

Def DummyFunction():
    pass

if a > 2:
    pass
else:
    pass

print

Output, Debugging

The print keyword allows you to send output to the terminal or command prompt during the execution of your code. When in the debugging stage of your program, you can also use the print keyword to display the value of certain variables to help you see where your code might be going wrong.

Python 2.x allows for the print statement to be formatted like this:

>>> x = 3
>>> y = 4
>>> print x,y
3 4

However, Python 3.x changes the print statement to a function, so it requires print to be formatted with parentheses surrounding the statement:

>>> x = 3
>>> y = 4
>>> print(x,y)
3 4

If you try to use the 2.x format in 3.x, you will get a syntax error. Python 2.x does allow the 3.x syntax, so you should use the 3.x format whenever possible when you write new code under Python 2.x.

The print keyword will normally add an escape sequence new line character (‘ ') to the output unless a comma is placed at the end of the statement.

for x in range(10):
    print x,

0 1 2 3 4 5 6 7 8 9

For more information on escape sequences, see the Escape Sequence below.

raise

Error Handling

The raise keyword forces a specified error to occur. This is helpful for testing and debugging purposes.

y = 3
if y < 10:
    raise ValueError
Traceback (most recent call last):
 File "<stdin>", line 2, in <module>
ValueError

return

Functions

The return keyword will pass a value or values back to the line of code that called the function.

def returntest():
    a = 4
    b = 2
    return a * b

>>> print(returntest())
8

It is possible to return multiple values from a function. In this case, the return value is a tuple.

def returntest2():
    a = 4
    b = 2
    c = a * b
    return a,b,c
>>> print(returntest2())
(4, 2, 8)

try

Error Handling

The try keyword is part of a very versatile error handling system that Python provides. The try statement should always be used with a matching except statement. The general format looks something like this:

try:
    # code here to attempt to execute
except:
    # code here to attempt to recover from the error

The code between the try and except keywords is run. If no error occurs, the except portion of the routine is bypassed. If an error does occur, the code after the except keyword will be run. See also except and finally, above. There is also an optional else clause, which can contain code that will be executed if the try clause did not raise an error. The else clause must follow the except clause.

while

Loops

The while keyword creates a loop that is executed over and over until a condition becomes true.

cntr = 0
while cntr < 9:
    print cntr
    cntr += 1
0
1
2
3
4
5
6
7
8

with

Unmanaged resources

The with keyword allows you to deal with unmanaged resources, like files. If you need to quickly write to a file and make sure that it gets saved when the code is finished automatically, you can use the with keyword. In the snippet below, the with keyword opens the output file and then after the code below it is finished processing, it automatically closes the file for you.

with open('output.txt','w') as f:
    f.write('Welcome to Python')

yield

Iterators, Generators

Returns a generator. Generators are a simple and yet powerful tool for creating iterators. They are written like a regular function but use the yield statement whenever they want to return data. Each time next() is called, the generator resumes where it left off (it remembers all data values and which statement was last executed). In the code sample below, each time the loop executes, it automatically calls the next() statement.

def CreateGen():
    mylist = range(5)
    print mylist
    for i in mylist:
        yield i*i
    
mygen = CreateGen()
for cntr in mygen:
    print(cntr)

[0, 1, 2, 3, 4]
0
1
4
9
16

False

Evaluation (Version 3.x only)

In Python 2.x, False was simply a built-in constant. You were welcome to override it and, in fact, could write the following:

False = True

and it would be prefectly legal. In version 3.x it has been promoted to a keyword and is used to mean "0".

None

Evaluation, Variables (Version 3.x only)

The None keyword represents the concept of empty and nothing. If a variable has not been assigned a value it is automatically given a value of None. When a function is created that does not explicitly return a value, the function returns a None value.

>>> fred = None
>>> print fred
None

True

Evaluation (Version 3.x only)

In Python 2.x, True was simply a built-in constant. You were welcome to override it and, in fact, could write the following:

True = False

and it would be prefectly legal. In version 3.x it has been promoted to a keyword and is used to mean "not 0".

nonlocal

Variables (Version 3.x only)

Similar to the global keyword but is only relevant within a function. Functions may have nested functions. Without the nonlocal keyword, any declared variables have the scope of a normal function, even if they are nested within another function. By using the nonlocal keyword within the nested function, the variable value may be changed within the nested routine. In the following example, there are two functions, each with a nested function. The two functions are identical with the exception of the nonlocal keyword in Funct1. The variable test in Funct2 has a local scope within the Within function, so the outer variable test is not changed. In Funct1, however, it is set as a nonlocal variable, so that the outer variable test gets modified by the Within function nested in Funct1.

def Funct1():
    test = 1
    def Within():
        nonlocal test
        test = 2
        print("Routine Funct1|Within- test = ", test)
    Within()
    Print("Routine Funct1 – test = ", test)
  
def Funct2():
    test = 1
    def Within():
        test = 2
        print("Routine Funct2|Within - test = ", test)
    Within()
    print("Routine Funct2 - test = ",test)
  
Funct2()
Funct1()

Routine Funct2|Within - test = 2
Routine Funct2 - test = 1
Routine Funct1|Within- test = 2
Routine Funct1 - test = 2

Escape Sequences

Python allows for certain characters such as a Tab or Carriage Return to be embedded within strings to allow extra control over printing. There are also times that you have a string that requires a single or double quote that would normally cause problems. For example, let’s say you decided to create a string using the single quote as the string delimiter. Without using an escape sequence you can’t have a single quote within the string. While you could use double quotes to delimit the string, that might be an issue.

>>> test = 'This is a test of the ' (single quote) character'
>>> test
"This is a test of the ' (single quote) character"

The escape sequence starts with a backslash () character then followed by a character. This will be interpreted by Python as a special character. Refer to Table 7-1.

Table 7-1. List of Escape Sequences

Escape Sequence

Meaning

\

Backslash ()

'

Single Quote (')

"

Double Quote (")

a

ASCII Bell (BEL)



ASCII Backspace (BS)

f

ASCII Formfeed (FF)

ASCII Linefeed (LF)

N

Character named name in the Unicode database

ASCII Charriage Return (CR)

ASCII Horizontal Tab (TAB)

uxxxx

Character with 16-bit hex value (Unicode only)

Uxxxxxxxx

Character with 32 bit hex value (Unicode only)

v

ASCII Vertical Tab(VT)

ooo

Charcter with octal value ooo

xhh

Character with hex value hh

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset