Here is a collection of all the statements and functions in Python that this book covers, along with some examples of their use. The examples all take place in the interactive shell, so you can experiment with them yourself by following the examples in the interactive shell.

If you would like to learn more functions and methods, the official Python documentation covers every function that comes with Python. It can be found at http://docs.python.org/

Doug Hellmann also has a blog called "Python Module of the Week" which covers the various modules that come with Python in good detail with plenty of examples. His blog can be found at http://www.doughellmann.com/PyMOTW/

Statements

Assignment Statements

The assignment statement is used to store a value inside a variable. The statement is a variable name, followed by the = operator, followed by a value or expression. The expression is evaluated to the value to be stored in the variable.

>>> spam = 42
>>> spam
42
>>> eggs = 10 + 5
>>> eggs
15
>>>

break Statements

break statements will immediately make the execution jump out of the innermost loop that it is placed in. Notice in the following example that the print() function call is never executed because the break statement moves execution out of the while loop.

>>> while True:
...   break
...   print('Hello!')
...   
>>>

The break statement only breaks out of the innermost loop. Notice that the print('Goodbye!') call is never executed, and that even though print('Hello!') is in a for loop that should iterate three times, it is only called once.

>>> for i in range(3):
...   print('Start of outer #%s' % (i))
...   for j in range(3):
...     print('Hello!')
...     break
...     print('Goodbye!')
...   print('End of outer #%s' % (i))
...   
Start of outer loop #0
Hello!
End of outer loop #0
Start of outer loop #1
Hello!
End of outer loop #1
Start of outer loop #2
Hello!
End of outer loop #2
>>>

continue Statements

continue statements will immediately make the execution jump to the start of the innermost loop that it is placed in. Notice in the following example that the print('Hello!') call is executed by print('Goodbye!') is never executed because the continue statement moves execution back to the start of the loop for the next iteration.

>>> for i in range(3):
...   print('Hello! #%s' % (i))
...   continue
...   print('Goodbye!')
...   
Hello! 0
Hello! 1
Hello! 2
>>>

continue statements only work on the innermost loop. Notice in the following example that the print('Goodbye!') call is skipped by the continue, but the continue does not skip the print('End of outer #%s' % (i)) call.

>>> for i in range(3):
...   print('Start of outer #%s' % (i))
...   for j in range(3):
...     print('Hello!')
...     continue
...     print('Goodbye!')
...   print('End of outer #%s' % (i))
...   
Start of outer loop #0
Hello!
Hello!
Hello!
End of outer loop #0
Start of outer loop #1
Hello!
Hello!
Hello!
End of outer loop #1
Start of outer loop #2
Hello!
Hello!
Hello!
End of outer loop #2
>>>

def Statements

def statements are used to define a new function. The def statement is the def keyword, followed by the function name, the parentheses which contain any parameters, a colon, and a block that contains the function's code. A function cannot be called until after it has been defined.

>>> def foo(name):
...   print('Your name must be %s.' % (name))
...   
>>> foo('Stan')
Your name must be Stan.
>>>

del Statements

del statements will delete, or undefine, a variable. This is useful for removing items in lists and dicts. The del statement is the del keyword followed by the variable or item to be deleted.

>>> spam = ['cats', 'dogs', 'mice']
>>> spam
['cats', 'dogs', 'mice']
>>> del spam[1]
>>> spam
['cats', 'mice']

for Loop Statements

for loops set a variable to each value in a list or each key in a dict. A for loop can be exited early if it encounters a break statement. A continue statment will cause execution to immediately move to the next iteration at the start of the loop.

>>> spam = ['cats', 'dogs', 'mice']
>>> for i in spam:
...   print i
...   
cats
dogs
mice
>>>
>>> spam = {'animal':'cats', 'food':'pasta', 'color':'blue'}
>>> for i in spam:
...   print i
...   
animal
food
color
>>>

import Statements

import statements allow you to use functions and variables located inside other Python scripts (called modules) in your program. There are many modules that come with Python already (such as time, sys, or random). The import statement is the import keyword, followed by the module name. To use a function in a module, put the module name and a period before the function call.

>>> import random
>>> random.randint(0, 10)
6
>>>

if, elif, else Statements

The if, elif, else statements can decide whether or not to execute a block of code. The if and elif statements start with the if or elif keyword, followed by a condition (that is, an expression that evaluates to a boolean value True or False), followed by a colon and a block of code.

If the condition that follows the if statement is True, then the block of code that comes after the if statement is executed. If the condition that follows the if statement is False and the elif's condition is True, then the block that follows the elif statement is executed. If all the if and elif statements are False, then the block that follows the else statement is executed.

Only one of the blocks that follows an if, elif, or else statement will be executed.

The if statement is always first. An if statement does not need to have an elif or else statement after it. If the if statement has both an elif and else statement, the else statement must come after all the elif statements. There can be any number of elif statements.

>>> myPet = 'cat'
>>> if myPet == 'dog':
...   print('Dogs are very friendly.')
... elif myPet == 'bird':
...   print('Bird chirps are very loud.')
... elif myPet == 'cat':
...   print('Cats make me sneeze.')
... else:
...   print('I do not know what type of pet that is.')
...
Cats make me sneeze
>>>

return Statements

return statements immediately send execution out of a function and back to the line where the function was called. They can be followed by a value or expression to be used as the function's return value. return statements can only be used inside of functions (that is, inside a def statement's block).

If the return keyword is by itself, then the function returns the None value.

>>> def foo():
...   return 42
...   
>>> foo()
42
>>>

while Loop Statements

while loops will execute the block of code over and over until their condition (that is, an expression that evaluates to a boolean True or False value) is False. The condition is checked at the beginning of each iteration.

A while loop can be exited early if it encounters a break statement. A continue statement will cause execution to go back to the start of the while loop and recheck the while loop's condition.

>>> i = 0
>>> while i < 3:
...   print('Value of i is %s' % (i))
...   i = i + 1
...   
Value of i is 0
Value of i is 1
Value of i is 2
>>>

Functions

The abs() Function

The abs(n) function returns the absolute value of n. The absolute value of a number is the positive form of the number.

>>> abs(-5)
5
>>> abs(10)
10
>>>

The bool() Function

The bool(x) function returns the boolean value of x. If x is an empty list, string, dict, or the numeric values 0 or 0.0, the bool(x) evaluates to False. Otherwise, bool(x) will return True.

>>> bool('')
False
>>> bool([])
False
>>> bool(42)
True
>>> bool(0)
False
>>>

The chr() Function

The chr(n) function takes an integer ASCII value n and returns a string with that ASCII value's character. A table of all ASCII values can be found in Chapter 13, The Caesar Cipher.

>>> chr(65)
'A'
>>> chr(66)
'B'
>>> chr(53)
'5'
>>>

The float() Function

The float(x) function takes an integer or string x and returns the floating point version of x.

>>> float(42)
42.0
>>>

The input() Function

The input() function pauses the execution of the program and lets the user type in a string from the keyboard. When the user presses Enter, the keystrokes (except for the Enter) are returned as a string.

>>> spam = input()
Albert
>>> spam
Albert
>>>

The int() Function

The int(x) function takes a floating point number or string x and returns the integer version of x. If x is a floating point number, then the integer returned is x rounded down.

>>> int(42.0)
42
>>> int('99')
99

The list() Function

The list(x) function returns the list form of x. Usually, the "range object" returned by the range() function is passed to list() in order to get a list object of the range object's values.

>>> spam = list(range(10))
>>> spam
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

The ord() Function

The ord(c) function takes a single character string c and returns the integer ASCII value of c. A table with all the ASCII values can be found in Chapter 14, The Caesar Cipher.

>>> ord('A')
65
>>> ord('B')
66
>>> ord('5')
53
>>>

The print() Function

The print(x) function takes a value x and displays it on the screen with a newline automatically added to the end. The print() function can take any number of multiple arguments and will display them with a single space placed in between the arguments. A print() function call with no arguments will display just a newline on the screen.

The print() function has two optional keyword arguments. The end keyword argument can change the newline automatically added to the end of the string to any other string. The sep keyword argument can change the single space autoamtically inserted in between multiple arguments to any other string.

>>> print('Hello')
Hello
>>> print()

>>> print(2, 4, 6)
2 4 6
>>> print(2, 4, 6, sep='XXX')
2XXX4XXX6
>>> print('Hello', end='ZZZ\n'
HelloZZZ
>>>

The range() Function

The range(n) function returns a range object with the values 0 to n-1. This range object can be used in for loops to iterate over the integer values 0 to n-1. If you want an actual list value with these integer values, pass the range object to the list() function.

The range(start, stop) form can provide a different start value other than 0. The range(start, stop, step) form can provide a different start value than 0 and also increment a different value than 1.

>>> for i in range(4):
...   print i
...   
0
1
2
3
>>> for i in range(2, 4):
...   print i
...   
2
3
>>> for i in range(2, 10, 2):
...   print i
...   
2
4
6
8
>>>

The round() Function

The round(f) function will round a floating point number argument either up or down (depending on which is closer), and return the result as an integer value.

>>> round(2.9)
3
>>> round(2.1)
2
>>> round(2.5)
3
>>>

The str() Function

The str(x) function will take a value (commonly an integer or float) and return the string form of x.

>>> str(42)
'42'
>>> str(5.0)
'5.0'
>>>

The type() Function

The type(x) function takes a value x of any data type and returns what data type the value is. The return value itself is of a data type called type.

>>> type(5)
<class 'int'>
>>> type(5.0)
<class 'float'>
>>> type('Hello')
<class 'str'>
>>> type([1, 2, 3])
<class 'list'>
>>> type({'a':42})
<class 'dict'>
>>> type(type('Hello'))
<class 'type'>
>>> str(type(5)) == "<class 'int'>"
True
>>>





Functions in the random Module

The random.choice() Function

The random.choice(li) function returns a random item from the list li. It is equivalent to li[random.randint(0, len(li)-1)].

>>> import random
>>> random.choice(['cat', 'dog', 'mouse'])
dog
>>> random.choice(['cat', 'dog', 'mouse'])
cat
>>> random.choice(['cat', 'dog', 'mouse'])
dog

The random.randint() Function

The random.randint(a, b) function returns a random integer between (and including) the arguments a and b.

>>> import random
>>> random.randint(0, 10)
6
>>> random.randint(0, 10)
7
>>> random.randint(20, 40)
24

The random.shuffle() Function

The random.shuffle(li) function will shuffle the order the items in the list li. Note that this function does not return anything: it shuffles the items in the list in place.

>>> import random
>>> spam = ['cat', 'dog', 'frog', 'fly', 'egg']
>>> random.shuffle(spam)
>>> spam
['cat', 'egg', 'frog', 'dog', 'fly']
>>> random.shuffle(spam)
>>> spam
['cat', 'frog', 'egg', 'fly', 'dog']
>>> random.shuffle(spam)
>>> spam
['fly', 'egg', 'frog', 'dog', 'cat']

Functions in the sys Module

The sys.exit() Function

The sys.exit() function causes your Python program to terminate and stop executing instructions.

>>> import sys
>>> sys.exit()
(The Python interactive shell or your Python program will terminate.

Functions in the time Module

The time.sleep() Function

The time.sleep(n) function causes the Python program to pause execution for n seconds. The argument n can either be an integer or a floating point value.

>>> import time
>>> time.sleep(5)
(There is a 5 second pause here while nothing happens.)
>>>

Methods

Dict Methods

The keys() Dict Method

The keys() dict method returns a list where each item is a key in the dictionary. Because dictionaries are not sorted, the items in the returned list will be in an uncertain order.

>>> spam = {'a':'spam', 'b':'eggs', 42:'ham'}
>>> spam.keys()
['a', 42, 'b']
>>>

The values() Dict Method

The values() dict method returns a list where each item is a value in the dictionary. Because dictionaries are not sorted, the items in the returned list will be in an uncertain order.

>>> spam = {'a':'spam', 'b':'eggs', 42:'ham'}
>>> spam.values()
['spam', 'ham', 'eggs']
>>>

List Methods

The append() List Method

The append(x) list method adds the value x to the end of the items in the list.

>>> spam = ['cat', 'dog', 'mice']
>>> spam.append('horse')
>>> spam
['cat', 'dog', 'mice', 'horse']
>>>

The reverse() List Method

The reverse() list method reverse the order of the items in the list in place. Note that because the items are reversed in place, this method does not return anything.

>>> spam = [1, 2, 3, 4]
>>> spam.reverse()
>>> spam
[4, 3, 2, 1]
>>>

The sort() List Method

The sort() list method puts all the items in the list in sorted order. This is done in place, so the sort() method does not return anything. The sort is alphanumeric, which means that numbers come before letters.

>>> spam = ['Alice', 'Bob', '42', '50', '4 Stars']
>>> spam.sort()
>>> spam
['4 Stars', '42', '50', 'Alice', 'Bob']
>>>

String Methods

The endswith() String Method

The endswith(s) string method returns True if the string ends with the string s, otherwise it returns False.

>>> 'Hello'.endswith('o')
True
>>> 'Hello'.endswith('O')
False
>>> 'Hello'.endswith('llo')
True
>>>

The isalpha() String Method

The isalpha() string method returns True if the string is not blank and only contains letters. If the string has numbers, spaces, or any other non-letter characters, the method returns False.

>>> 'Hello'.isalpha()
True
>>> 'Hello there!'.isalpha()
False
>>> ''.isalpha()
False
>>>

The isdigit() String Method

The isdigit() string method returns True if the string is not blank and only contains numbers. If the string has letters, spaces, or any other non-number characters, the method returns False. Note that periods will also make the method return False.

>>> '42'.isdigit()
True
>>> '10 15 20'.isdigit()
False
>>> '3.5'.isdigit()
False
>>> ''.isdigit()
False
>>>

The islower() string Method

The islower() string method will return True if the all the letters in it are lowercase and the string has at least one lowercase letter.

>>> 'albert'.islower()
True
>>> 'hello world!'.islower()
True
>>> 'hello World!'.islower()
False
>>> ''.islower()
False

The isupper() String Method

The isupper() string method will return True if the all the letters in it are uppercase and the string has at least one uppercase letter.

>>> 'ALBERT'.isupper()
True
>>> 'HELLO WORLD!'.isupper()
True
>>> 'hELLO wORLD!'.isupper()
False
>>> ''.isupper()
False

The join() String Method

The join(li) string method returns a string that contains all of the string items in the list li, with the string in between each of the items. This is most commonly used on a single space string to combine several word strings in a list together into one string.

>>> spam = ['cat', 'dog', 'mouse']
>>> ' '.join(spam)
'cat dog mouse'
>>> 'XXX'.join(spam)
'catXXXdogXXXmouse'
>>> 'XXX'.join([])
''

The lower() String Method

The lower() string method returns a lowercase string version of the string.

>>> spam = 'Hello World!'
>>> spam.lower()
'hello world!'
>>> My name is Al.lower()
'my name is al.'
>>>

The split() String Method

The split() string method returns a list of strings, where each string in the list is from splitting the string by whitespace. Whitespace characters include spaces, tabs, and newlines. The whitespace is not included in the strings in the returned list.

The split(s) version can specify a string s to split the string on.

>>> spam = 'Hello there, young lady.'
>>> spam.split()
['Hello', 'there,', 'young', 'lady.']
>>> 'Man is a wolf to man. - Roman proverb'.split()
['Man', 'is', 'a', 'wolf', 'to', 'man.', '-', 'Roman', 'proverb']
>>> 'Cats and cats and dogs and cats and a mouse.'.split('cats')
['Cats and ', ' and dogs and ', ' and a mouse.']
>>>

The startswith() String Method

The startswith() string method returns True if the string ends with the string s, otherwise it returns False.

>>> 'Hello'.startswith('H')
True
>>> 'Hello'.startswith('h')
False
>>> 'Hello'.startswith('Hel')
True
>>>

The upper() String Method

The upper() string method returns an uppercase string version of the string.

>>> spam = 'Hello world!'
>>> spam.upper()
'HELLO WORLD!'
>>> 'My name is Al.'
'MY NAME IS AL.'
>>>