Programming in Python

(Based on the syllabus of II Sem B.Sc.Mathematics, Calicut University) Rajan T K Department of Mathematics Govt Victoria College, Palakkad

Chapter 1

Introduction
Python is a high-level, interpreted, interactive and object oriented-scripting language.Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages. The language was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

1.1 History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands in 1990. He chose the name python for the language as he wanted a curious and simple name which he got from Monty Python’s Flying Circus of which he was a fan. The python language is used for various purposes like • System administration • Graphical interfaces • Internet Scripting • Database Programming • Rapid Application Development . . . Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted, Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the institute, although Rossum still holds a vital role in directing it's progress.

1. 2 Python Features
Python's feature highlights include:
• • • • •

Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time. Easy-to-read: Python code is much more clearly defined and visible to the eyes. Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain. A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code.

• • • •

Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable: Python provides a better structure and support for large programs than shell scripting.

Chapter 2

Python - Basic Syntax
2.1 First Python Program
2.1.1 Interactive Mode Programming
Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
$ python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more info.

Type the following text to the right of the Python prompt and press the Enter key:
>>> print "Hello, Python!" This will produce following result: Hello, Python!

2.1.2 Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Python program in a script. All python files will have extension .py. So put the following source code in a test.py file.
#!/usr/bin/python >>>print "Hello, Python!"

Here I assumed that you have Python interpreter available in /usr/bin directory. Now try to run this program as follows:
$ chmod +x test.py $ python test.py # This is to make file executable

This will produce following result:
Hello, Python!

You have seen a simple Python program in interactive as well as script mode, now lets see few basic concepts related to Python Syntax:

2.2 Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in Python. Here are following identifier naming convention for Python:

Class names start with an uppercase letter and all other identifiers with a lowercase letter.

If the identifier also ends with two trailing underscores. the second block in this example will generate an error: if True: print "Answer" print "True" else: print "Answer" .• • • Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be private. Blocks of code are denoted by line indentation. These reserved words may not be used as constant or variable or any other identifier names. but all statements within the block must be indented the same amount. Starting an identifier with two leading underscores indicates a strongly private identifier. which is rigidly enforced. andexec assertfinally breakfor classfrom continueglobal defif delimport elifin elseis exceptlambda not or pass print raise return try while with yield 2.4 Lines and Indentation There are no braces to indicate blocks of code for class and function definitions or flow control.3 Reserved Words The following list shows the reserved words in Python. the identifier is a language-defined special name. Both blocks in this example are fine: if True: print "True" else: print "False" However. Keywords contain lowercase letters only. 2. The number of spaces in the indentation is variable.

5 Multi-Line Statements Statements in Python typically end with a new line. "w") except IOError: print "There was an error writing to". For example: . Just make sure you understood various blocks even if they are without braces. Python does. "r") except IOError: print "There was an error reading file" sys.exit() try: file = open(file_name.exit() file_text = file. Following is the example having various statement blocks: Note: Don't try to understand logic or different functions used. allow the use of the line continuation character (\) to denote that the line should continue. however. or () brackets do not need to use the line continuation character.read() file. file_name sys.close() file_name = raw_input("Enter filename: ") if len(file_name) == 0: print "Next time please enter something" sys.write("\n") file.close() print file_text 2. For example: total = item_one + \ item_two + \ item_three Statements contained within the [].close break file. file_finish. #!/usr/bin/python import sys try: # open file stream file = open(file_name.exit() print "Enter '". print "' When finished" while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish: # close the file file. in Python all the continuous lines indented with similar number of spaces would form a block. {}.print "False" Thus.write(file_text) file.

'Thursday'. all the following are legal. 2." paragraph = """This is a paragraph. # This is a comment. 'Friday'] 2. 'Wednesday'. Python!". #!/usr/bin/python # First comment print "Hello. as long as the same type of quote starts and ends the string. double (") and triple (''' or """) quotes to denote string literals. The triple quotes can be used to span the string across multiple lines. Strings in triple quotes are normally used for documentation of program files. is known as a blank line.""" 2. For example. 'Tuesday'. which serve the purpose of on line help word = 'word' sentence = "This is a sentence. All characters after the # and up to the physical line end are part of the comment. too. # This is a comment.6 Quotation in Python Python accepts single ('). Python! A comment may be on the same line after a statement or expression: name = "Rajan" # This is again comment You can comment multiple lines as follows: # This is a comment.7 Comments in Python A hash sign (#) that is not inside a string literal begins a comment. # second comment This will produce following result: Hello. and Python totally ignores it. and the Python interpreter ignores them. In an interactive interpreter session. 2.9 Waiting for the User . possibly with a comment. you must enter an empty physical line to terminate a multi line statement.days = ['Monday'. too. # I said that already.8 Using Blank Lines A line containing only whitespace. It is made up of multiple lines and sentences.

Compound or complex statements. ) allows multiple statements on the single line given that neither statement starts a new code block. Command line arguments is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts. This is a nice trick to keep a console window open until the user is done with an application.") Here "\n\n" are being used to create two new lines before displaying the actual line. . for instance. 2. and class.. while. Python enables you to do this with -h: $ python -h usage: python [option].10 Multiple Statements on a Single Line The semicolon ( . x = 'foo'. Options and arguments (and corresponding environment variables): -c cmd : program passed in as string (terminates option list) -d : debug output from parser (also PYTHONDEBUG=x) -E : ignore environment variables (such as PYTHONPATH) -h : print this help message and exit (also --help) [ etc. Once the user presses the key.The following line of the program displays the prompt. def. Example: if expression : suite elif expression : suite else : suite 2. such as if. the program ends.write(x + '\n') 2. are those which require a header line and a suite.. that many programs can be run so that they provide you with some basic information about how they should be run. and waits for the user to press the Enter key: #!/usr/bin/python raw_input("\n\nPress the enter key to exit.11 Multiple Statement Groups as Suites Groups of individual statements making up a single code block are called suites in Python. Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. ] You can also program your script in such a way that it should accept various options. sys.12 Command Line Arguments You may have seen..stdout.[-c cmd | -m mod | file | -] [arg]. Press the enter key to exit. Here is a sample snip using the semicolon: import sys.

For example: >>>a. 3. and one string object with the value "john" is assigned to the variable c. 3. 2. Unlike other programming languages. The equal sign (=) is used to assign values to variables. 1000.1 Assigning Values to Variables Python variables do not have to be explicitly declared to reserve memory space. b. python doesn't require any declaration for variables. The declaration happens automatically when you assign a value to a variable. the interpreter allocates memory and decides what can be stored in the reserved memory. While running this program. You can also assign multiple objects to multiple variables. you can store integers.0 point >>>name = "Syam" >>>print counter >>>print miles >>>print name # An integer # A floating # A string Here 100. "john" Here two integer objects with values 1 and 2 are assigned to variables a and b. The operand to the left of the = operator is the name of the variable.2 Multiple Assignment You can also assign a single value to several variables simultaneously. respectively.0 and "John" are the values assigned to counter. Therefore. miles and name variables. For example: >>> a = b = c = 1 Here. and the operand to the right of the = operator is the value stored in the variable. c = 1. by assigning different data types to variables.0 John 3. This means that when you create a variable you reserve some space in memory. For example: #!/usr/bin/python >>>counter = 100 assignment >>>miles = 1000. this will produce following result: 100 1000. decimals. Based on the data type of a variable. or characters in these variables.Variable Types Variables are nothing but reserved memory locations to store values. and all three variables are assigned to the same memory location. an integer object is created with the value 1.Chapter 3 Python .3 Standard Data Types .

For example. a person.4 Python Numbers Number data types store numeric values. For example: >>> del var >>> del var_a..The data stored in memory can be of many types.var2[.9 32. var_b Python supports four different numerical types: • • • • int (signed integers) long (long integers [can also be represented in octal and hexadecimal]) float (floating point real values) complex (complex numbers) Examples: Here are some examples of numbers: intlong 1051924361L 100-0x19323L -7860122L 0800xDEFABCECBDAEC 0. Python has some standard types that are used to define the operations possible on them and the storage method for each of them.3+e18 float 3..876j complex .j 9..322e-36j .var3[.. Python has five standard data types: • • • • • • Numbers String List Tuple Set Dictionary 3. For example: >>>var1 = 1 >>>var2 = 10 You can also delete the reference to a number object by using the del statement.14j 45. The syntax of the del statement is: >>> del var1[.s age is stored as a numeric value and his or her address is stored as alphanumeric characters.0 15.varN]]]] You can delete a single object or multiple objects by using the del statement. which means that changing the value of a number data type results in a newly allocated object.20 -21. Number objects are created when you assign a value to them. They are immutable data types.

One difference between them is that all the items belonging to a list can be of different data type. A list contains items separated by commas and enclosed within square brackets ([]). To some extent. 3. Python displays long integers with an uppercase L. where a is the real part and b is the imaginary part of the complex number.53e-7j • Python allows you to use a lowercase L with long.6545+0J 3e+26J 4. Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end.54e100 70. and the asterisk ( * ) is the repetition operator. A complex number consists of an ordered pair of real floatingpoint numbers denoted by a + bj.2-E12 -. -32.BFBAEl -0490535633629843L -0x260-052318172735L 0x69-4721885298529L • -90. but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Example: #!/usr/bin/python str = 'Hello World!' print str # print str[0] # of the string print str[2:5] # starting from 3rd to print str[2:] # from 3rd character print str * 2 # print str + "TEST" # string Prints complete string Prints first character Prints characters 6th Prints string starting Prints string two times Prints concatenated This will produce following result: Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST 3.5 Python Strings Strings in Python are identified as a contiguous set of characters in between quotation marks. Python allows for either pairs of single or double quotes. lists are similar to arrays in C. .6 Python Lists Lists are the most versatile of Python's compound data types. The plus ( + ) sign is the string concatenation operator.

while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. 'john'. however. Example: #!/usr/bin/python list = [ 'abcd'. 2. 786 . 70.The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list and working their way to end-1. 123.23. 'john') ) print tuple # Prints complete list print tuple[0] # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd to 4th print tuple[2:] # Prints elements starting from 3rd element print x * 2 # Prints list two times print tuple + x # Prints concatenated lists This will produce following result: . 2.23. tuples are enclosed within parentheses. 'john'] 3. and their elements and size can be changed. 2. 'john'. 'john'] ['abcd'.200000000000003. 'john'.2 x = (123.23. The plus ( + ) sign is the list concatenation operator. Tuples can be thought of as read-only lists. 70. 2. 2.200000000000003] [123. 70. Example: #!/usr/bin/python tuple = ( 'abcd'. and the asterisk ( * ) is the repetition operator.23. 'john'. 123. 70. 'john'.23. 786. 786. 'john'.23] [2. Unlike lists. 70. 786 .200000000000003] abcd [786. 'john'] print list # Prints complete list print list[0] # Prints first element of the list print list[1:3] # Prints elements starting from 2nd to 4th print list[2:] # Prints elements starting from 3rd element print x * 2 # Prints list two times print list + x # Prints concatenated lists This will produce following result: ['abcd'. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ). A tuple consists of a number of values separated by commas.2 ] x = [123.7 Python Tuples A tuple is another sequence data type that is similar to the list.

70. because we attempted to update a tuple. 786 . 786. Keys can be almost any Python type.which is not allowed. Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed usinh square braces ( [] ).200000000000003) abcd (786.200000000000003. 123. 2. 6734. 'john'. Values.('abcd'.200000000000003) (123. 123.2 ) list = [ 'abcd'. 786 .values() # Prints all the values This will produce following result: This is one This is two {'dept': 'sales'.2 ] tuple[2] = 1000 # Invalid syntax with tuple list[2] = 1000 # Valid syntax with list 3. 'name': 'john'} ['dept'. 'name'] ['sales'. 2. 2.23. Similar case is possible with lists: #!/usr/bin/python tuple = ( 'abcd'. 70. 'code': 6734. 70. 'john'] . but are usually numbers or strings. Example: #!/usr/bin/python dict = {} dict['one'] = "This is one" dict[2] = "This is two" x = {'name': 'john'. 'john'. 'john'. 'john') Following is invalid with tuple. on the other hand.'code':6734.23) (2. can be any arbitrary Python object. 2. 70.keys() # Prints all the keys print x. 786. 'code'.8 Python Dictionary Python 's dictionaries are hash table type. 'john'. 70. 'dept': 'sales'} print dict['one'] # Prints value for 'one' key print dict[2] # Prints value for 2 key print x # Prints complete dictionary print x. 'john'. They work like associative arrays or hashes found in Perl and consist of key-value pairs.23.23. 'john') ('abcd'. 2.23. 'john'.23.

base]) long(x [. Converts x to a long integer. Converts an integer to an octal string. . There are several built-in functions to perform conversion from one data type to another. Converts s to a tuple.Dictionaries have no concept of order among elements. Converts s to a set. Converts a single character to its integer value. d must be a sequence of (key. Converts s to a list. Converts object x to an expression string. Creates a complex number.9 Data Type Conversion Sometimes you may beed to perform conversions between the built-in types. base specifies the base if x is a string. Converts an integer to a Unicode character. It is incorrect to say that the elements are "out of order". Function int(x [. To convert between types you simply use the type name as a function. 3. Converts object x to a string representation. Creates a dictionary.base] ) float(x) complex(real [. Converts x to a floating-point number. Converts an integer to a hexadecimal string.imag]) str(x) repr(x) eval(str) tuple(s) list(s) set(s) dict(d) frozenset(s) chr(x) unichr(x) ord(x) hex(x) oct(x) Description Converts x to an integer. base specifies the base if x is a string. Converts an integer to a character. Converts s to a frozen set. Evaluates a string and returns an object. These functions return a new object representing the converted value.value) tuples. they are simply unordered.

Adds values on either side of the operator Subtraction .Divides left hand operand by right hand operand and returns remainder Exponent . .Divides left hand operand by right hand operand Modulus .0 decimal point are removed.1 What is an operator? Simple answer can be given using expression 4 + 5 is equal to 9.Subtracts right hand operand from left hand operand Multiplication .0//2.b will give -10 a * b will give 200 b / a will give 2 b % a will give 0 a**b will give 10 to the power 20 // Floor Division . • • • • • Arithmetic Operators Comparision Operators Logical (or Relational) Operators Assignment Operators Conditional (or ternary) Operators Lets have a look on all operators one by one.The division of operands where the result is the 9//2 is equal to 4 and quotient in which the digits after the 9.2 Python Arithmetic Operators Assume variable a holds 10 and variable b holds 20 then: Operator + * / % ** Description Addition .Basic Operators 4.0 is equal to 4.Chapter 4 Python . Here 4 and 5 are called operands and + is called operator.Performs exponential (power) calculation on operators Example a + b will give 30 a . 4.Multiplies values on either side of the operator Division . Python language supports following type of operators.

It multiplies c *= a is equivalent to c = c right operand with the left operand and assign the *a result to left operand Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a *= /= . 4. (a >= b) is not true. similar to != operator.4 Python Assignment Operators Assume variable a holds 10 and variable b holds 20 then: Operat or = += Description Example Simple assignment operator. Checks if the value of two operands are equal or not.3 Python Comparison Operators Assume variable a holds 10 and variable b holds 20 then: Operator == != <> > Description Example Checks if the value of two operands are equal or not. if yes then condition becomes (a < b) is true.4. if yes then condition becomes (a > b) is not true. true. Checks if the value of left operand is less than the value of right operand. true. Checks if the value of left operand is greater than the value of right operand. if yes then condition becomes true. (a != b) is true. if values are not equal then condition becomes true. This is if values are not equal then condition becomes true. Assigns values from c = a + b will assigne value right side operands to left side operand of a + b into c Add AND assignment operator. if yes then condition becomes true. Checks if the value of two operands are equal or not. Checks if the value of left operand is less than or equal to the value of right operand. Checks if the value of left operand is greater than or equal to the value of right operand. if yes then condition becomes true. (a == b) is not true. < >= <= (a <= b) is true. It subtracts c -= a is equivalent to c = c right operand from the left operand and assign the a result to left operand Multiply AND assignment operator. It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c +a -= Subtract AND assignment operator. (a <> b) is true.

%= Modulus AND assignment operator.5 Python Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. Performs c **= a is equivalent to c = c exponential (power) calculation on operators and ** a assign value to the left operand Floor Dividion and assigns a value. The left operands value is moved left by the a << 2 will give 240 which is number of bits specified by the right 1111 0000 operand. The a >> 2 will give 15 which is . 0011 1101 Binary XOR Operator copies the bit (a ^ b) will give 49 which is if it is set in one operand but not 0011 0001 both. Performs c //= a is equivalent to c = floor division on operators and assign value to the c // a left operand **= //= 4. Assume if a = 60. Binary OR Operator copies a bit if it (a | b) will give 61 which is exists in eather operand. (~a ) will give -60 which is 1100 0011 ~ << >> Binary Left Shift Operator. Now in binary format they will be as follows: >>>a = 0011 1100 >>>b = 0000 1101 >>>a&b = 0000 1000 >>>a|b = 0011 1101 >>>a^b = 0011 0001 >>>~a = 1100 0011 There are following Bitwise operators supported by Python language Operato r & | ^ Description Example Binary AND Operator copies a bit to (a & b) will give 12 which is the result if it exists in both 0000 1100 operands. It takes c %= a is equivalent to c = c modulus using two operands and assign the result %a to left operand Exponent AND assignment operator. Binary Right Shift Operator. Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. and b = 13.

such as strings. which test for membership in a sequence. here not in results in a 1 if x is a member of sequence y. Evaluates to true if it finds a variable in the specified sequence and false otherwise. Example (a and b) is true. If a condition is true then Logical NOT operator will make false. Example x is y.8 Python Identity Operators Identity operators compare the memory locations of two objects. Python has membership operators. Use to reverses the logical state of its operand. There are two Identity operators explained below: Oper ator is is not Description Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. here in results in a 1 if x is a member of sequence y. or tuples. not(a && b) is false. x not in y. lists. There are two membership operators explained below: Operator in Description Evaluates to true if it finds a variable in the specified sequence and false otherwise. here is results in 1 if id(x) equals id(y).7 Python Membership Operators: In addition to the operators discussed previously. becomes true. not 4.6 Python Logical Operators There are following logical operators supported by Python language Assume variable a holds 10 and variable b holds 20 then: Operator and Description Called Logical AND operator. If both the operands are true then then condition becomes true. 0000 1111 4. or Called Logical OR Operator. not in 4. Example x in y. If any of the two operands are non zero then then condition (a or b) is true. Called Logical NOT Operator. here is not results . Evaluates to false if the variables on either side x is not y.left operands value is moved right by the number of bits specified by the right operand.

in 1 if id(x) is not equal to id(y). 4. divide.9 Python Operators Precedence The following table lists all operators from highest precedence to lowest. modulo and floor division Addition and subtraction Right and left bitwise shift Bitwise 'AND' Bitwise exclusive `OR' and regular `OR' Comparison operators Equality operators Assignment operators Identity operators Membership operators Logical operators .of the operator point to the same object and true otherwise. Operator ** ~+* / % // +>> << & ^| <= < > >= <> == != = %= /= //= -= += |= &= >>= <<= *= **= is is not in not in note or and Description Exponentiation (raise to the power) Ccomplement. unary plus and minus (method names for the last two are +@ and -@) Multiply.

This is realized by using special statements called control statement. 5. if its value is nonzero then the statement(s) block are executed.Got a true expression value 100 Good bye! . Example: #!/usr/bin/python var1 = 100 if var1: print "1 . Here we discuss such statements.1. The result of this decision making determines the sequence in which a program will execute instructions. You can control the flow of a program by using conditional constructs. and a decision is made based on the result of the comparison. With the control statement the flow of execution in the program can be controlled. the next statement following the statement(s) block is executed. The syntax of the if statement is: if expression: statement(s) Here if statement. condition is evaluated first. If condition is true that is.Chapter 5 Control Statements Normally a program runs executing the instructions line by line.Got a true expression value" print var1 var2 = 0 if var2: print "2 . But there are cases where we want to skip or repeat a set of statements based on certain conditions. all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code.1 The if statement: The if statement of Python is similar to that of other languages. Otherwise. 5. Note: In Python.1 Branching Conditional constructs are used to incorporate decision making into programs. The if statement contains a logical expression using which data is compared.Got a true expression value" print var2 print "Good bye!" This will produce following result: 1 . Python uses indentation as its method of grouping statements.

3 The elif Statement The elif statement allows you to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true..Got a true expression value 100 2 .elif statement is: if expression1: statement(s) .Got a false expression value" print var1 var2 = 0 if var2: print print else: print print "2 .Got a false expression value" var2 print "Good bye!" This will produce following result: 1 . The else statement is an optional statement and there could be at most only one else statement following if .Got a true expression value" print var1 else: print "1 . for which there can be at most one statement.2 The else Statement: An else statement can be combined with an if statement.Got a true expression value" var2 "2 . there can be an arbitrary number of elif statements following an if. the elif statement is optional..1.5..1.else statement is: if expression: statement(s) else: statement(s)Example: #!/usr/bin/python var1 = 100 if var1: print "1 .Got a false expression value 0 Good bye! 5. The syntax of the if. unlike else. Like the else. The syntax of the if. However. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a false value..

..elif.else Construct There may be a situation when you want to check for another condition after a condition resolves to true. In a nested if construct. you can have an if. In such a situation..1..elif.Got print var print "Good bye!" a true expression value" a true expression value" a true expression value" a false expression value" This will produce following result: 3 .else construct.Got a true expression value 100 Good bye! 5.....elif.Got print var elif var == 150: print "2 .elif expression2: statement(s) elif expression3: statement(s) else: statement(s) Note: Python does not currently support switch or case statements as in other languages.else construct may be: if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: .else construct inside another if. you can use the nested if construct.Got print var else: print "4 ...elif.Got print var2 elif var == 100: print "3 ... The syntax of the nested if... Example: #!/usr/bin/python var = 100 if var == 200: print "1 ..4 The Nested if..

When the condition becomes false.statement(s) Example: #!/usr/bin/python var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50" else: print "Could not find true expression" print "Good bye!" This will produce following result: Expression value is less than 200 Which is 100 Good bye! 5. The while loop continues until the expression becomes false.5 Single Statement Suites: If the suite of an if clause consists only of a single line.1. it may go on the same line as the header statement: Here is an example of a one-line if clause: >>>if ( expression == 1 ) : print "Value of expression is 1" 5. The expression has to be a logical expression and must return either a true or a false value The syntax of the while look is: while expression: statement(s) .2 Python .2. the loop ends and the program control is passed to the statement following the loop. 5.1 The while Loop The while loop is one of the looping constructs available in Python.while Loop Statements A loop is a construct that causes a section of a program to be repeated a certain number of times. The repetition continues while the condition set for the loop remains true.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required. This results in a loop that never ends. the current value of the index count is displayed and then increased by 1. all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. If expression is true that is. count count = count + 1 print "Good bye!" This will produce following result: The count The count The count The count The count The count The count The count The count Good bye! is: is: is: is: is: is: is: is: is: 0 1 2 3 4 5 6 7 8 The block here. is executed repeatedly until count is no longer less than 9. Python uses indentation as its method of grouping statements.2. Note: In Python. then the statement(s) block is executed repeatedly until expression becomes false. Otherwise. consisting of the print and increment statements. num print "Good bye!" . the next statement following the statement(s) block is executed. Example: Following loop will continue till you enter 1 at command prompt: #!/usr/bin/python var = 1 while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ".2 The Infinite Loops You must use caution when using while loops because of the possibility that this condition never resolves to a false value. With each iteration. 5.Here expression statement is evaluated first. Example: #!/usr/bin/python count = 0 while (count < 9): print 'The count is:'. Such a loop is called an infinite loop.

1 The for Loop The for loop in Python has the ability to iterate over the items of any sequence. it is evaluated first. the loop ends and the program control is passed to the statement following the loop. line 5.3 Single Statement Suites Similar to the if statement syntax. 5.for Loop Statements A loop is a construct that causes a section of a program to be repeated a certain number of times. Each item in the list is assigned to iterating_var. Example: #!/usr/bin/python .3 Python . such as a list or a string. the first item in the sequence is assigned to the iterating variable iterating_var. The repetition continues while the condition set for the loop remains true. Next. Note: In Python.3. This tutorial will discuss the for loop construct available in Python. Here is an example of a one-line while clause: >>> while expression : statement 5. The syntax of the loop look is: for iterating_var in sequence: statements(s) If a sequence contains an expression list. 5. in <module> num = raw_input("Enter a number :") KeyboardInterrupt Above example will go in an infite loop and you would need to use CNTL+C to come out of the program. it may be placed on the same line as the while header. the statements block is executed.This will produce following result: Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Enter a number between :Traceback (most recent call last): File "test. Python uses indentation as its method of grouping statements. if your while clause consists only of a single statement. When the condition becomes false. Then.2. all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code.py". and the statements(s) block is executed until the entire sequence is exhausted.

for letter in 'Python': # First Example print 'Current Letter :'. 'mango'] for index in range(len(fruits)): print 'Current fruit :'.3. 'apple'. fruit print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye! 5.2 Iterating by Sequence Index An alternative way of iterating through each item is by index offset into the sequence itself: Example: #!/usr/bin/python fruits = ['banana'. letter fruits = ['banana'. 'mango'] for fruit in fruits: # Second Example print 'Current fruit :'. fruits[index] print "Good bye!" This will produce following result: Current fruit : banana Current fruit : apple Current fruit : mango Good bye! . 'apple'.

Example: #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :'.4 Python break.4. 5. continue and pass statements available in Python. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop.Here we took the assistance of the len() built-in function. Python provides break and continue statements to handle such situations and to have good control on your loop. which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over. var var = var -1 if var == 5: break print "Good bye!" This will produce following result: Current Letter : Current Letter : Current Letter : Current variable Current variable Current variable Current variable Current variable Good bye! P y t value value value value value : : : : : 10 9 8 7 6 5.continue and pass Statements You might face a situation in which you need to exit a loop completely when an external condition is triggered or there may also be a situation when you want to skip a part of the loop and start next execution.2 The continue Statement . This tutorial will discuss the break. letter var = 10 # Second Example while var > 0: print 'Current variable value :'. 5.1 The break Statement: The break statement in Python terminates the current loop and resumes execution at the next statement. just like the traditional break found in C.4. The break statement can be used in both while and for loops.

var var = var -1 if var == 5: continue print "Good bye!" This will produce following result: Current Letter : Current Letter : Current Letter : Current Letter : Current Letter : Current variable Current variable Current variable Current variable Current variable Current variable Current variable Current variable Current variable Current variable Good bye! P y t o n value value value value value value value value value value : : : : : : : : : : 10 9 8 7 6 5 4 3 2 1 5.. letter var = 10 # Second Example while var > 0: print 'Current variable value :'. The pass is also useful in places where your code will eventually go.3 The pass Statement: The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. nothing happens when it executes. Example: #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :'.g. The pass statement is a null operation. in stubs for example): Example: #!/usr/bin/python for letter in 'Python': if letter == 'h': . The continue statement can be used in both while and for loops.4.The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. but has not been written yet (e.

#!/usr/bin/python for num in range(10. 5. the else statement is executed when the condition becomes false.j) break #to move to the next number. You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code. • • If the else statement is used with a for loop. the #first FOR else: # else part of the loop print num.20): #to iterate between 10 to 20 for i in range(2.num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num. letter print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye! The preceding code does not execute any statement or code if the value of letter is 'h'.pass print 'This is pass block' print 'Current Letter :'. Example: The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20.i. 'is a prime number' This will produce following result: . The pass statement is helpful when you have created a code block but it is no longer required. the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop.5 The else Statement Used with Loops Python supports to have an else statement associated with a loop statements.

.10 equals 2 * 11 is a prime number 12 equals 2 * 13 is a prime number 14 equals 2 * 15 equals 3 * 16 equals 2 * 17 is a prime number 18 equals 2 * 19 is a prime number 5 6 7 5 8 9 Similar way you can use else statement with while loop.

For example: del var del var_a. where a and b are floats and J (or j) represents the square root of .322e-36j .. complex (complex numbers) : are of the form a + bJ. float (floating point real values) : or floats. which means that changing the value of a number data type results in a newly allocated object. var_b Python supports four different numerical types: • • • • int (signed integers): often called just integers or ints. are integers of unlimited size.1 (which is an imaginary number). Number objects are created when you assign a value to them.j 9. written like integers and followed by an uppercase or lowercase L. Examples: Here are some examples of numbers: int 10 100 -786 080 -0490 long 51924361L -0x19323L 0122L 0xDEFABCECBDAE CBFBAEl 535633629843L 0. The syntax of the del statement is: del var1[. long (long integers ): or longs. a is the real part of the number.9 32. represent real numbers and are written with a decimal point dividing the integer and fractional parts.var2[.varN]]]] You can delete a single object or multiple objects by using the del statement. with E or e indicating the power of 10 (2.6545+0J complex ..876j -.5e2 = 2..1 Introduction Number data types store numeric values. float 3. and b is the imaginary part.14j 45. They are immutable data types. Complex numbers are not used much in Python programming.3+e18 -90. are positive or negative whole numbers with no decimal point.0 15.var3[.20 -21.Chapter 6 Python – Numbers 6.5 x 102 = 250).. For example: var1 = 1 var2 = 10 You can also delete the reference to a number object by using the del statement. Floats may also be in scientific notation.

Type complex(x) to convert x to a complex number with real part x and imaginary part zero. you'll need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter. y) exp(x) fabs(x) floor(x) log(x) log10(x) max(x1..1 Mathematical Functions: Python includes following functions that perform mathematical calculations.2 Number Type Conversion Python converts numbers internally in an expression containing mixed types to a common type for evaluation. x and y are numeric expressions 6. where a is the real part and b is the imaginary part of the complex number.3. The value of x**y. But sometimes. The floor of x: the largest integer not greater than x The natural logarithm of x.) min(x1.3 Built-in Number Functions 6.. Python displays long integers with an uppercase L.2-E12 3e+26J 4. but it is recommended that you use only an uppercase L to avoid confusion with the number 1. or 1 if x > y The exponential of x: ex The absolute value of x. Function abs(x) ceil(x) cmp(x. y) to convert x and y to a complex number with real part x and imaginary part y. x2..53e-7j • Python allows you to use a lowercase L with long. y) Returns ( description ) The absolute value of x: the (positive) distance between x and zero. . • • • • • Type int(x)to convert x to a plain integer. 6. The integer part is returned as a float. A complex number consists of an ordered pair of real floatingpoint numbers denoted by a + bj.. x2. for x> 0 The base-10 logarithm of x for x> 0 .54e100 70. 0 if x == y.. The ceiling of x: the smallest integer not less than x -1 if x < y. Type float(x) to convert x to a floating-point number. The largest of its arguments: the value closest to positive infinity The smallest of its arguments: the value closest to negative infinity The fractional and integer parts of x in a two-item tuple.. Type long(x) to convert x to a long integer.) modf(x) pow(x. Type complex(x.-0x260 0x69 • -052318172735L -4721885298529L -32. Both parts have the same sign as x.

6. testing. in radians.5) is -1. step) A random float r. such that x is less than or equal to r and r is less than y 6. The square root of x for x > 0 6. Returns None.5) is 1. Return the Euclidean norm. in radians.3 Trigonometric Functions Python includes following functions that perform trigonometric calculations. Return the sine of x radians. in radians. Function acos(x) asin(x) atan(x) atan2(y. tuple.0.2 Random Number Functions Random numbers are used for games.] stop [.0 and round(-0. A random float r.3. or string. Return the tangent of x radians. x) cos(x) hypot(x. y) sin(x) tan(x) degrees(x) radians(x) Description Return the arc cosine of x. sqrt(x*x + y*y). Python includes following functions that are commonly used. Return the cosine of x radians. y) Returns ( description ) A random item from a list.n]) sqrt(x) x rounded to n digits from the decimal point. Return atan(y / x). such that 0 is less than or equal to r and r is less than 1 Sets the integer starting value used in generating random numbers.step]) random() seed([x]) shuffle(lst) uniform(x.3. Return the arc tangent of x.round(x [.4 Mathematical Constants . simulations. A randomly selected element from range(start. Return the arc sine of x. and privacy applications. Converts angle x from radians to degrees. Randomizes the items of a list in place. Returns None. Python rounds away from zero as a tie-breaker: round(0. Converts angle x from degrees to radians. Function choice(seq) randrange ([start. Call this function before calling any other random module function. in radians. stop. security.

The module also defines two mathematical constants: Constant pi e Description The mathematical constant pi. The mathematical constant e. .

var1[:6] + 'Python' This will produce following result: Updated String :Hello Python . Example: #!/usr/bin/python var1 = 'Hello World!' print "Updated String :. var1[0] print "var2[1:5]: ".". The new value can be related to its previous value or to a completely different string altogether. For example: var1 = 'Hello World!' var2 = "Python Programming" 7. var2[1:5] This will produce following result: var1[0]: H var2[1:5]: ytho 7. these are treated as strings of length one. To access substrings.Chapter 7 Python – Strings Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes.2 Updating Strings: You can "update" an existing string by (re)assigning a variable to another string. Creating strings is as simple as assigning a value to a variable. thus also considered a substring. use the square brackets for slicing along with the index or indices to obtain your substring: Example: #!/usr/bin/python var1 = 'Hello World!' var2 = "Python Programming" print "var1[0]: ".1 Accessing Values in Strings Python does not support a character type.

or A. where n is in the range 0. an escape character is interpreted. concatenating multiple copies of the same string Slice .Gives the characters from the given range a*2 will give -HelloHello a[1] will give e a[1:4] will give ell .Gives the character from the given index Range Slice . where n is in the range 0. in a singlequoted string. NOTE: In a doublequoted string. Backslash notation \a \b \cx \C-x \e \f \M-\C-x \n \nnn \r \s \t \v \x \xnn 0x0d 0x20 0x09 0x0b 0x0a 0x1b 0x0c Hexadecimal character 0x07 0x08 Bell or alert Backspace Control-x Control-x Escape Formfeed Meta-Control-x Newline Octal notation.Adds values on either a + b will give HelloPython side of the operator Repetition .f.F Description 7.Creates new strings.7. a.9.3 Escape Characters: Following table is a list of escape or non-printable characters that can be represented with backslash notation.4 String Special Operators: Assume string variable a holds 'Hello' and variable b holds 'Python' then: Operator + * [] [:] Description Example Concatenation . an escape character is preserved.7 Carriage return Space Tab Vertical tab Character x Hexadecimal notation.

in not in

Membership - Returns true if a character exists in the given string Membership - Returns true if a character does not exist in the given string

H in a will give 1 M not in a will give 1

r/R

Raw String - Suppress actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," print r'\n' prints \n and print R'\n' which precedes the quotation marks. prints \n The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. Format - Performs String formatting See at next section

%

7.5 String Formatting Operator:
One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family.

Example:
#!/usr/bin/python print "My name is %s and weight is %d kg!" % ('Zara', 21)

This will produce following result:
My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with %: Format Symbol %c %s %i %d %u %o %x %X %e character string conversion via str() prior to formatting signed decimal integer signed decimal integer unsigned decimal integer octal integer hexadecimal integer (lowercase letters) hexadecimal integer (UPPERcase letters) exponential notation (with lowercase 'e') Conversion

%E %f %g %G

exponential notation (with UPPERcase 'E') floating point real number the shorter of %f and %e the shorter of %f and %E

Other supported symbols and functionality are listed in the following table: Symbol * + <sp> # 0 % (var) m.n. Functionality argument specifies width or precision left justification display the sign leave a blank space before a positive number add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used. pad from left with zeros (instead of spaces) '%%' leaves you with a single literal '%' mapping variable (dictionary arguments) m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

7.6 Triple Quotes:
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python para_str = """this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up. """ print para_str;

This will produce following result. Note how every single special character has been converted to its printed form, right down to the last NEWLINE at the end of the string between the "up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the end of a line or its escape code (\n):
this is a long string that is made up of several lines and non-printable characters such as TAB ( ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ ], or just a NEWLINE within

the variable assignment will also show up.

7.7 Raw String:
Raw strings don't treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it:
#!/usr/bin/python print 'C:\\nowhere'

This would print following result:
C:\nowher e

Mow let's make use of raw string. We would put expression in r'expression' as follows:
#!/usr/bin/python print r'C:\\nowhere'

This would print following result:
C:\\nowhere

7.8 Unicode String:
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following:
#!/usr/bin/python print u'Hello, world!'

This would print following result:
Hello, world!

As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.

7.9 Built-in String Methods:
Python includes following string method: SN 1 2 3 Methods with Description capitalize() Capitalizes first letter of string center() Returns a space-padded string with the original string centered to a total of width columns count(str, beg= 0,end=len(string)) Counts how many times str occurs in string, or in a substring of string if starting

index beg and ending index end are given 3 decode(encoding='UTF-8',errors='strict') Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. encode(encoding='UTF-8',errors='strict') Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'. endswith(suffix, beg=0, end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; Returns true if so, and false otherwise expandtabs(tabsize=8) Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided find(str, beg=0 end=len(string)) Determine if str occurs in string, or in a substring of string if starting index beg and ending index end are given; returns index if found and -1 otherwise index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found isa1num() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise isdigit() Returns true if string contains only digits and false otherwise islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise isnumeric() Returns true if string contains only numeric characters and false otherwise isspace() Returns true if string contains only whitespace characters and false otherwise istitle() Returns true if string is properly "titlecased" and false otherwise isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise join(seq) Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string len(string)

4

5

6

7 8 9

10 11 12 13 14 15 16

17 18

max(str) Returns the max alphabetical character from the string str min(str) Returns the min alphabetical character from the string str replace(old. fillchar]) Returns a space-padded string with the original string right-justified to a total of width columns. and false otherwise strip([chars]) Performs both lstrip() and rstrip() on string swapcase() Inverts case for all letters in string title() 31 32 33 34 35 . max]) Replaces all occurrences of old in string with new.end=len(string)) Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str. split into at most num substrings if given splitlines( num=string.[. but search backwards in string rjust(width.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings. fillchar]) Returns a space-padded string with the original string left-justified to a total of width columns lower() Converts all uppercase letters in string to lowercase lstrip() Removes all leading whitespace in string maketrans() Returns a translation table to be used in translate function. or at most max occurrences if max given rfind(str. Returns true if so. end=len(string)) Same as index(). beg=0. beg=0. new [. beg=0.count('\n')) Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed startswith(str. rstrip() Removes all trailing whitespace of string split(str="".Returns the length of the string 19 20 21 22 23 24 25 26 27 28 29 30 ljust(width[.end=len(string)) Same as find(). num=string. but search backwards in string rindex( str.

all words begin with uppercase. intended for numbers.Returns "titlecased" version of string. deletechars="") Translates string according to translation table str(256 chars). that is. removing those in the del string upper() Converts lowercase letters in string to uppercase zfill (width) Returns original string leftpadded with zeros to a total of width characters. zfill() retains any sign given (less one zero) . and the rest are lowercase 36 37 38 translate(table.

"d"]. 3. 7 ]. 5 ]. multiplying. and for finding its largest and smallest elements. 2000]. concatenated and so on. The first index is zero. Good thing about a list that items in a list need not all have the same type: Creating a list is as simple as putting different comma-separated values between squere brackets. the second index is one. 3. 5. 8. which can be written as a list of commaseparated values (items) between square brackets. and so forth. print "list1[0]: ". These operations include indexing. list1[0] print "list2[1:5]: ". adding.3 Accessing Values in Lists: To access values in lists. 4. In addition. 6. 2.Chapter 8 Python . list2 = [1. 4. Like string indices. or index. list indices start at 0. 3.its position. "b".Lists 8. and lists can be sliced.1 Python Sequences: The most basic data structure in Python is the sequence. Python has six built-in types of sequences. Python has built-in functions for finding the length of a sequence. slicing. list3 = ["a". 4. "c". list2[1:5] This will produce following result: list1[0]: physics list2[1:5]: [2. 'chemistry'. the position index and corresponding value can be retrieved at the same time . There are certain things you can do with all sequence types. 1997. 1997. Each element of a sequence is assigned a number . For example: list1 = ['physics'. 5] When looping through a sequence. 8. but the most common ones are lists and tuples which we would see in this tutorial. use the square brackets for slicing along with the index or indices to obtain value available at that index: Example: #!/usr/bin/python list1 = ['physics'. 'chemistry'.2 Python Lists: The list is a most versatile datatype available in Python. and checking for membership. 2. 2000]. list2 = [1.

print "Value available at index 2 : " print list1[2]. print "New value available at index 2 : " print list1[2]. 2000]. ’toe’]): . 2000]. 'chemistry'. 0 1 2 tic tac toe print i. v 8. print list1.using the enumerate() function. This will produce following result: ['physics'. and you can add to elements in a list with the append() method: Example: #!/usr/bin/python list1 = ['physics'.. .. Example: #!/usr/bin/python list1 = ['physics'. list1[2] = 2001. 1997.5 Delete List Elements: To remove a list element. 'chemistry'... del list1[2]. 2000] . This will produce following result: Value available at index 2 : 1997 New value available at index 2 : 2001 8. >>> for i. you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. 'chemistry'. print "After deleting value at index 2 : " print list1.4 Updating Lists: You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator. v in enumerate([’tic’. 1997. ’tac’. Note: append() method is discussed in subsequent section. 1997.

min(list) .8 Built-in List Functions & Methods Python includes following list functions S N 1 2 3 4 Function with Description cmp(list1. 3] + [4. 6] ['Hi!'] * 4 3 in [1.7 Indexing and Slicing Because lists are sequences. Assuming following input: L = ['spam'. 8. 3 [1. 3]: print x. 'Hi!'. max(list) Returns item from the list with max value. 2. list2) Compares elements of both lists. not a string. they mean concatenation and repetition here too. 4. 'Hi!'] True 123 Results Length Concatenation Repetition Membership Iteration Description 8. 2. 3. 5. 3] for x in [1. 'SPAM!'] 8. len(list) Gives the total length of the list. lists respond to all of the general sequence operations we used on strings in the prior chapter : Python Expression len([1. In fact. 'Hi!'. except that the result is a new list. 2. 2. 'chemistry'. 5. indexing and slicing work the same way for lists as they do for strings. 'SPAM!'] Python Expression L[2] L[-2] L[1:] 'SPAM!' 'Spam' Results Description Offsets start at zero Negative: count from the right Slicing fetches sections ['Spam'. 3]) [1.After deleting value at index 2 : ['physics'. 2. 6] ['Hi!'.6 Basic List Operations: Lists respond to the + and * operators much like strings. 2000] Note: remove() method is discussed in subsequent section. 'Spam'.

insert(index. 5 list(seq) Converts a tuple into list.Returns item from the list with min value.sort([func]) Sorts objects of list.index(obj) Returns the lowest index in list that obj appears list. use compare func if given Methods with Description . obj) Inserts object obj into list at offset index list.pop(obj=list[-1]) Removes and returns last object or obj from list list.remove(obj) Removes object obj from list list.reverse() Reverses objects of list in place list.append(obj) Appends object obj to list list. Python includes following list methods S N 1 2 3 4 5 6 7 8 9 list.extend(seq) Appends the contents of seq to list list.count(obj) Returns count of how many times obj occurs in list list.

The empty tuple is written as two parentheses containing nothing: tup1 = (). tup1[0] print "tup2[1:5]: ". tup2 = (1. 9. tup2[1:5] This will produce following result: tup1[0]: physics tup2[1:5]: [2. 5] 9. 4. 5. Tuples are sequences. and tuples can be sliced. The only difference is that tuples can't be changed ie. concatenated and so on. just like lists. tuples are immutable and tuples use parentheses and lists use square brackets.2 Accessing Values in Tuples: To access values in tuple. 3. 2. 1997. 2000). 3. 3. 'chemistry'. "c". But we able able to take portions of an existing tuples to create a new tuples as follows: . 2.1 Introduction A tuple is a sequence of immutable Python objects. 4. use the square brackets for slicing along with the index or indices to obtain value available at that index: Example: #!/usr/bin/python tup1 = ('physics'.Chapter 9 Python – Tuples 9. 2000). 4. 6. For example: tup1 = ('physics'. 7 ). Like string indices. To write a tuple containing a single value you have to include a comma.). tuple indices start at 0.3 Updating Tuples: Tuples are immutable which means you cannot update them or change values of tuple elements. "b". even though there is only one value: tup1 = (50. 'chemistry'. print "tup1[0]: ". tup3 = "a". Creating a tuple is as simple as putting different comma-separated values and optionally you can put these comma-separated values between parentheses also. tup2 = (1. "d". 1997. 5 ).

nothing wrong with putting together another tuple with the undesired elements discarded. 'chemistry'. 34.56. tup2 = ('abc'. 'xyz') 9. 3) + (4. There is. NameError: name 'tup' is not defined 9.py". except that the result is a new tuple. 'chemistry'. 3)) (1. print tup. this is because after del tup tuple does not exist any more: ('physics'. 4. # So let's create a new tuple as follows tup3 = tup1 + tup2. # Following action is not valid for tuples # tup1 += tup2. not a string. To explicitly remove an entire tuple. they mean concatenation and repetition here too. 2000) After deleting tup : Traceback (most recent call last): File "test. 2. tuples respond to all of the general sequence operations we used on strings in the prior chapter : Python Expression len((1. 1997.56). 5.4 Delete Tuple Elements: Removing individual tuple elements is not possible. 2. 6) 3 (1. line 9. In fact. of course. 2. in <module> print tup. del tup. 'xyz'). 5. 6) Results Length Concatenation Description .5 Basic Tuples Operations: Tuples respond to the + and * operators much like strings. 1997. just use the del statement: Example: #!/usr/bin/python tup = ('physics'. 2000). This will produce following result: (12. 34. This will produce following result.Example: #!/usr/bin/python tup1 = (12. 'abc'. 3. Note an exception raised. print "After deleting tup : " print tup. print tup3.

'Hi!'. 2. etc. 18+6. default to tuples. This will reduce following result: abc -4. print "Value of x . 2. max(tuple) Returns item from the tuple with max value. y = 1.6j) xyz Value of x .e. brackets for lists. 'SPAM!'] 9. print var. 'SPAM!') Python Expression L[2] L[-2] L[1:] 'SPAM!' 'Spam' Results Description Offsets start at zero Negative: count from the right Slicing fetches sections ['Spam'.6 Indexing and Slicing Because tuples are sequences. written without identifying symbols.24e93. y : 1 2 9..8 Built-in Tuple Functions Python includes following tuple functions SN 1 2 3 4 Function with Description cmp(tuple1. -4. parentheses for tuples.7 No Enclosing Delimiters Any set of multiple objects. ('Hi!'.y. 'xyz'. 2. x. 'Hi!'. . 'Hi!') True 123 Repetition Membership Iteration 9. x. Assuming following input: L = ('spam'. 3): print x.6j. 3) for x in (1.['Hi!'] * 4 3 in (1.24e+93 (18+6. i.. min(tuple) Returns item from the tuple with min value. tuple2) Compares elements of both tuples. y : ". 'Spam'. as indicated in these short examples: #!/usr/bin/python print 'abc'. len(tuple) Gives the total length of the tuple. indexing and slicing work the same way for tuples as they do for strings. comma-separated.

5 tuple(seq) Converts a list into tuple. .

dict['Age']. 98. 'Age': 7. or tuples. but the keys must be of an immutable data type such as strings.Chapter 10 Python – Dictionary 10.2 Accessing Values in Dictionary To access dictionary elements. 10.6: 37 }. we get an error as follows: #!/usr/bin/python dict = {'Name': 'Zara'. Keys are unique within a dictionary while values may not be. This will produce following result: dict['Name']: Zara dict['Age']: 7 If we attempt to access a data item with a key which is not part of the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. dict2 = { 'abc': 123. The general syntax of a dictionary is as follows: dict = {'Alice': '2341'. An empty dictionary without any items is written with just two curly braces. Each key is separated from its value by a colon (:). 'Class': 'First'}. print "dict['Alice']: ". 'Class': 'First'}. numbers. The values of a dictionary can be of any type. print "dict['Age']: ". the items are separated by commas. like this: {}. dict['Name'].1 Introduction A dictionary is mutable and is another container type that can store any number of Python objects. dict['Alice']. and the whole thing is enclosed in curly braces. 'Beth': '9102'. print "dict['Name']: ". 'Age': 7. you use the familiar square brackets along with the key to obtain its value: Example: #!/usr/bin/python dict = {'Name': 'Zara'. including other container types. Python dictionaries are also known as associative arrays or hash tables. This will produce following result: . 'Cecil': '3258'} You can create dictionary in the following way as well: dict1 = { 'abc': 456 }.

modifying an existing entry. dict['Age']..iteritems(): . # update existing entry dict['School'] = "DPS School". or deleting an existing entry as shown below: Example: #!/usr/bin/python dict = {'Name': 'Zara'. dict['School']. print "dict['School']: ". 'Class': 'First'}. a key-value pair)...3:345. 'Age': 7.py". 1 2 3 4 123 234 345 456 print I.3 Updating Dictionary You can update a dictionary by adding a new entry or item (i. KeyError: 'Alice' When looping through dictionaries. >>> knights = {1:123. the key and corresponding value can be retrieved at the same time using the iteritems() method.4 Delete Dictionary Elements You can either remove individual dictionary elements or clear the entire contents of a dictionary.e.4:456} >>> for I. # Add new entry print "dict['Age']: ". line 4. To explicitly remove an entire dictionary.. in <module> print "dict['Alice']: ".j in knights. just use the del statement: . dict['Age'] = 8..dict['Zara']: Traceback (most recent call last): File "test. dict['Alice']. This will produce following result: dict['Age']: 8 dict['School']: DPS School 10. .2:234. You can also delete entire dictionary in a single operation.j 10.

# delete entire dictionary print "dict['Age']: ". this is because after del dict dictionary does not exist any more: dict['Age']: Traceback (most recent call last): File "test. Example 1: #!/usr/bin/python dict = {'Name': 'Zara'. in <module> print "dict['Age']: ". 10.Example: #!/usr/bin/python dict = {'Name': 'Zara'. line 8. print "dict['School']: ". Example 2: #!/usr/bin/python dict = {['Name']: 'Zara'. They can be any arbitrary Python object. dict['Name']. dict['Name']. This will produce following result. or tuples as dictionary keys but something like ['key'] is not allowed. numbers. print "dict['Name']: ". same is not true for the keys. This will produce following result: dict['Name']: Manni (b) Keys must be immutable. dict['Age']. TypeError: 'type' object is unsubscriptable Note: del() method is discussed in subsequent section.py". the last assignment wins. This will produce following result. 'Age': 7. 'Name': 'Manni'}. dict['Age']. There are two important points to remember about dictionary keys: (a) More than one entry per key not allowed.clear(). 'Age': 7. Note an exception raised: . However. Note an exception raised. 'Class': 'First'}. Which means no duplicate key is allowed. When duplicate keys encountered during assignment. # remove entry with key 'Name' dict. either standard objects or user-defined objects. del dict['Name']. Which means you can use strings. # remove all entries in dict del dict .5 Properties of Dictionary Keys Dictionary values have no restrictions. dict['School']. 'Age': 7}. print "dict['Name']: ".

get(key. dict2) Compares elements of both dict.Traceback (most recent call last): File "test. This would be equal to the number of items in the dictionary.py". Python includes following dictionary methods SNo 1 2 2 3 4 5 6 7 8 9 Methods with Description dict.update(dict2) Adds dictionary dict2's key-values pairs to dict dict. but will set dict[key]=default if key is not already in dict dict.fromkeys() Create a new dictionary with keys from seq and values set to value. in <module> dict = {['Name']: 'Zara'.has_key(key) Returns true if key in dictionary dict. str(dict) Produces a printable string representation of a dictionary type(variable) Returns the type of the passed variable.values() Returns list of dictionary dict2's values .clear() Removes all elements of dictionary dict dict.copy() Returns a shallow copy of dictionary dict dict.keys() Returns list of dictionary dict's keys dict. len(dict) Gives the total length of the dictionary.6 Built-in Dictionary Functions & Methods: Python includes following dictionary functions SNo 1 2 3 4 Function with Description cmp(dict1. If passed variable is dictionary then it would return a dictionary type. line 3. 'Age': 7}. false otherwise dict. default=None) Similar to get(). returns value or default if key not in dictionary dict. value) tuple pairs dict.setdefault(key. default=None) For key key. TypeError: list objects are unhashable 10.items() Returns a list of dict's (key. dict.

There is a popular time module available in Python which provides functions for working with times. The function time. January 1. ticks This would produce a result something as follows: Number of ticks since 12:00am. Python's time and calendar modules help track dates and times. 1970(epoch). January 1. 11. 1970: 7186862. January 1. 11. as shown below: Index 0 1 2 3 4 5 6 7 4-digit year Month Day Hour Minute Second Day of Week Day of year Field 2008 1 to 12 1 to 31 0 to 23 0 to 59 0 to 61 (60 or 61 are leap-seconds) 0 to 6 (0 is Monday) 1 to 366 (Julian day) Values . 1970(epoch). ticks = time.time() print "Number of ticks since 12:00am.Date and Time A Python program can handle date & time in several ways. # This is required to include time module. However. January 1. Converting between date formats is a common chore for computers. and for converting between representations. Particular instants in time are expressed in seconds since 12:00am. Dates in the far future also cannot be represented this way .2 What is TimeTuple? Many of Python's time functions handle time as a tuple of 9 numbers. 1970:".Chapter 11 Python .the cutoff point is sometime in 2038 for UNIX and Windows. Example: #!/usr/bin/python import time.time() returns the current system time in ticks since 12:00am.73399 Date arithmetic is easy to do with ticks.1 What is Tick? Time intervals are floating-point numbers in units of seconds. dates before the epoch cannot be represented in this form.

pass the floating-point value to a function (e. localtime This would produce following result which could be formatted in any other presentable form: Local current time : (2008.3.time()) print "Local current time :".3 Getting time 11. but simple method to get time in readable format is asctime(): #!/usr/bin/python import time. localtime = time. 5.time()) ) print "Local current time :".localtime(time. 32.g. 0. 55.8 Daylight savings -1. 1.. -1 means library determines DST Values 11. 12. -1 means library determines DST The above tuple is equivalent to struct_time structure. This structure has following attributes: Index 0 1 2 3 4 5 6 7 8 tm_year tm_mon tm_mday tm_hour tm_min tm_sec tm_wday tm_yday tm_isdst Attributes 2008 1 to 12 1 to 31 0 to 23 0 to 59 0 to 61 (60 or 61 are leap-seconds) 0 to 6 (0 is Monday) 1 to 366 (Julian day) -1.asctime( time. 15. 0. localtime) that returns a time-tuple with all nine items valid: #!/usr/bin/python localtime = time.localtime(time. 0.1 Current Time To translate a time instant from a seconds since the epoch floating-point value into a time-tuple. 1. localtime This would produce following result: Local current time : Tue Jan 13 10:17:09 2009 . 136.2 Getting formatted time You can format any time as per your requirement.3. 1) 11.

11. if one is defined. including the UK).4 The time Module There is a popular time module available in Python which provides functions for working with times.ctime([secs]) Like asctime(localtime(secs)) and without arguments is like asctime( ) time. To measure computational costs of different approaches. 1) print "Here is the calendar:" print cal.asctime([tupletime]) Accepts a time-tuple and returns a readable 24-character string such as 'Tue Dec 11 18:07:14 2008'. This would produce following result: Here is the January Mo Tu We Th 1 2 3 7 8 9 10 14 15 16 17 21 22 23 24 28 29 30 31 calendar: 2008 Fr Sa Su 4 5 6 11 12 13 18 19 20 25 26 27 11.mktime(tupletime) 2 3 4 5 6 7 .month(2008.3 Getting calendar for a month The calendar module gives a wide range of methods to play with yearly and monthly calendars.clock( ) Returns the current CPU time as a floating-point number of seconds. Here is the list of all available methods: SN 1 Function with Description time. depending on whether DST applies to instant secs by local rules). time.3.altzone The offset of the local DST timezone. and for converting between representations. in seconds west of UTC.localtime([secs]) Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the local time (t.time(). time.tm_isdst is 0 or 1. the value of time. Only use this if daylight is nonzero.tm_isdst is always 0 time.clock is more useful than that of time. time. Here we print a calendar for a given month ( Jan 2008 ): #!/usr/bin/python import calendar cal = calendar. time.gmtime([secs]) Accepts an instant expressed in seconds since the epoch and returns a time-tuple t with the UTC time. Note : t. This is negative if the local DST timezone is east of UTC (as in Western Europe.

when calendar is first imported. l is the number of lines for each week.l=1.tzname is a pair of locale-dependent strings. w is the width in characters of each date.tzname Attribute time. The environment variable TZ specifies how this is done. 2 11. Here is a list of functions available with the calendar module: S N 1 Function with Description calendar.firstweekday( ) Returns the current setting for the weekday that starts each week.strptime(str. a floating-point number of seconds since the epoch.w=2. 2 3 .isleap(year) Returns True if year is a leap year.Accepts an instant expressed as a time-tuple in local time and returns a floating-point value with the instant expressed in seconds since the epoch. By default. time. time.time( ) Returns the current time instant. <=0 in most of Europe.timezone is the offset in seconds of the local time zone (without DST) from UTC (>0 in the Americas. calendar takes Monday as the first day of the week and Sunday as the last one. including functions to print a text calendar for a given month or year. Africa). time. time.tzset() Resets the time conversion rules used by the library routines. 8 9 10 11 12 time. False. Asia.tupletime]) Accepts an instant expressed as a time-tuple in local time and returns a string representing the instant as specified by string fmt. meaning Monday. By default. respectively. To change this.sleep(secs) Suspends the calling thread for secs seconds. There are following two important attributes available with time module: SN 1 Attribute with Description time.calendar(year. this is 0.5 The calendar Module The calendar module supplies calendar-related functions. calendar.fmt='%a %b %d %H:%M:%S %Y') Parses str according to format string fmt and returns the instant in time-tuple format.c=6) Returns a multiline string with a calendar for year year formatted into three columns separated by c spaces. otherwise. each line has length 21*w+18+2*c. time.timezone Attribute time.setfirstweekday() function. calendar. which are the names of the local time zone without and with DST. call calendar.strftime(fmt[.

monthcalendar(year.w=2.l. 5 6 7 8 9 calendar.prcal(year. calendar.month(year.y2).month.y2) Returns the total number of leap days in the years within range(y1.l).month. calendar. calendar. calendar.month. l is the number of lines for each week.setfirstweekday(weekday) 10 Sets the first day of each week to weekday code weekday.w=2.day) 12 Returns the weekday code for the given date.w. Days outside month month of year year are set to 0. month numbers are 1 (January) to 12 (December).c=6) Like print calendar. The first one is the code of the weekday for the first day of the month month in year year.c).gmtime: accepts a time instant in time-tuple form and returns the same instant as a floating-point number of seconds since the epoch. calendar. one line per week plus two header lines. Weekday codes are 0 (Monday) to 6 (Sunday).w. each line has length 7*w+6. calendar.4 calendar.timegm(tupletime) 11 The inverse of time. w is the width in characters of each date.month) Returns two integers.weekday(year.leapdays(y1. days within the month are set to their day-of-month.w=2. .l=1.month) Returns a list of lists of ints.calendar(year. calendar. Weekday codes are 0 (Monday) to 6 (Sunday). Weekday codes are 0 (Monday) to 6 (Sunday).month(year. month numbers are 1 to 12. 1 and up.monthrange(year.prmonth(year.l=1) Like print calendar. the second one is the number of days in the month. Each sublist denotes a week.month.l=1) Returns a multiline string with a calendar for month month of year year.

Chapter 12 Python-Functions 12. We have already used many built-in functions such as the len and range. so we will explore various aspects of functions in this chapter. Next follows the block of statements that are part of this function. The function concept is probably the most important building block of any non-trivial software (in any programming language). Note that a return statement without a value is equivalent to return None.e.3 The pass statement The pass statement def someFunction(): . An example will show that this is actually very simple: Example: # Filename: function1. Functions are defined using the def keyword. break out of the function.py def maximum(x. Example: # Filename: func_return. This is known as calling the function.1 Introduction Functions are reusable pieces of programs. y): if x > y: return x else: return y The maximum function returns the maximum of the parameters..else statement to find the greater value and then returns that value. This is followed by an identifier name for the function followed by a pair of parentheses which may enclose some names of variables and the line ends with a colon. in this case the numbers supplied to the function. They allow you to give a name to a block of statements and you can run that block using that name anywhere in your program and any number of times.py def sayHello(): print('Hello World!') # block belonging to the function # End of function 12. Every function implicitly contains a return None statement at the end unless you have written your own return statement. 12.2 The return Statement The return statement is used to return from a function i. It uses a simple if. We can optionally return a value from the function as well.

pass . An important note is that if you break out of a for or while loop. even if the loop condition has not become False or the sequence of items has been completely iterated over.pass The pass statement is used in Python to indicate an empty block of statements. any corresponding loop else block is not executed.py while True: s = input('Enter something : ') if s == 'quit': break if len(s) < 3: print('Too small') continue print('Input is of sufficient length') # Do other kinds of processing here. Example: # Filename: continue. len(s)) print('Done') 12. It returns nothing. . 12..5 The continue Statement The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop. stop the execution of a looping statement. This is commonly used for creating minimal classes: >>> class MyEmptyClass: ...4 The break Statement The break statement is used to break out of a loop statement i.py while True: s = (input('Enter something : ')) if s == 'quit': break print('Length of the string is'.e.... Example: # Filename: break.

However. 'is maximum') 12.e.py def printMax(a. they are not related in any way to other variables with the same names used outside the function i. Not inside any kind of scope such as functions or classes). we supply the values in the same way.12. separated by commas. Example: # Filename: func_local. You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). b) else: print(b. 'is equal to'. Using the global statement makes it amply clear that the variable is defined in an outermost block. which are values you supply to the function so that the function can do something utilising those values. # Filename: func_param. When we call the function. Note the terminology used . b): if a > b: print(a.7 Local Variables When you declare variables inside a function definition. this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is.the names given in the function definition are called parameters whereas the values you supply in the function call are called arguments. All variables have the scope of the block they are declared in starting from the point of definition of the name. then you have to tell Python that the name is not local. x) 12. We do this using the global statement. This is called the scope of the variable.py x = 50 def fun(x): print('x is'.8 Using The global Statement If you want to assign a value to a name defined at the top level of the program (i. x) x = 2 print('Changed local x to'.6 Function Parameters A function can take parameters.e. x) fun(x) print('x is still'. Parameters are specified within the pair of parentheses in the function definition. It is impossible to assign a value to a variable defined outside a function without the global statement. These parameters are just like variables except that the values of these variables are defined when we call the function and are already assigned values when the function runs. variable names are local to the function. but it is global. . 'is maximum') elif a == b: print(a.

when we assign a value to x inside the function.9 Default Argument Values For some functions. You can specify default argument values for parameters by following the parameter name in the function definition with the assignment operator (=) followed by the default value.y): ' ' ' Function that returns maximum of two numbers Syntax : mx(x. For example. y. but def func(a=5. You can specify more than one global variable using the same global statement. that change is reflected when we use the value of x in the main block. DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand. z. we can even get the docstring back from. x) x +=3 print('Changed global x to'. when the program is actually running! Example: # filename : maxim. This is done with the help of default argument values.56) ' ' ' if x > y: . usually referred to by its shorter name docstrings.b=1. 12. x) fun() print('Value of x is'.y) Example : mx(32.py x = 50 def fun(): global x print('x is'. you may want to make some of its parameters as optional and use default values if the user does not want to provide values for such parameters.10 DocStrings Python has a nifty feature called documentation strings. In a program def func(a. say a function. Example: def prod(a. b) is not valid.py def mx(x. Amazingly. 12. x) The global statement is used to declare that x is a global variable .c=1): return a*b*c Care should be taken that if there are nondefault arguments also in the function they should come first in the list of arguments.hence. b=5) is valid.Example: # Filename: func_global. global x.

arg2: arg1 + arg2. sum( 20. 20 ) This would produce following result: Value of total : Value of total : 30 40 .. # Now you can call sum as a function print "Value of total : ". 20 ) print "Value of total : ".. which is as follows: lambda [arg1 [. They cannot contain commands or multiple expressions. 12. Doc string is strongly recommended in modules. An anonymous function cannot be a direct call to print because lambda requires an expression. Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. • • • • Lambda forms can take any number of arguments but return just one value in the form of an expression. they are not equivalent to inline statements in C or C++.return x else: return y Doc string is typed within triple quotes.11 The Anonymous Functions You can use the lambda keyword to create small anonymous functions.argn]]:expression Example: Following is the example to show how lambda form of function works: #!/usr/bin/python # Function definition is here sum = lambda arg1. whose purpose is by passing function stack allocation during invocation for performance reasons. Syntax: The syntax of lambda functions contains only a single statement. When help(maxim) is typed in interactive mode the doc string will be displayed. Information like help can be given in this manner.. sum( 10..arg2. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. Although it appears that lambda's are a one-line version of a function..

hello.py. Simply. moduleN] When the interpreter encounters an import statement. Here's an example of a simple module. par return 13.Chapter 13 Python – Modules 13. module2[. A module is a Python object with arbitrarily named attributes that you can bind and reference. you need to put the following command at the top of the script: #!/usr/bin/python # Import module hello import hello # Now you can call defined function that module as follows hello. import has the following syntax: import module1[.py def print_func( par ): print "Hello : ".. a module is a file consisting of Python code. it imports the module if the module is present in the search path. Asearch path is a list of directories that the interpreter searches before importing a module. and variables. Example: The Python code for a module named aname normally resides in a file named aname.. This prevents the module execution from happening over and over again if multiple imports occur. Grouping related code into a module makes the code easier to understand and use. A module can define functions. A module can also include runnable code. classes. Example: To import the module hello.1 Introduction A module allows you to logically organize your Python code.py.2 The import Statement You can use any Python source file as a module by executing an import statement in some other Python source file. regardless of the number of times it is imported. .print_func("Zara") This would produce following result: Hello : Zara A module is loaded only once..

And here is a typical PYTHONPATH from a UNIX system: set PYTHONPATH=/usr/local/lib/python . this default path is normally /usr/local/lib/python/. the Python interpreter searches for the module in the following sequences: • • • The current directory.13. Python checks the default path. consisting of a list of directories.import Statement Python's from statement lets you import specific attributes from a module into the current namespace: Syntax: from modname import name1[. If all else fails. The syntax of PYTHONPATH is the same as that of the shell variable PATH. and the installation-dependent default.. name2[.5. this statement should be used sparingly. 13. 13.path variable.4 The from. Python then searches each directory in the shell variable PYTHONPATH. nameN]] Example: For example.5 Locating Modules When you import a module...path variable contains the current directory.. use the following statement: from fib import fibonacci This statement does not import the entire module fib into the current namespace. 13. .. If the module isn't found.import * Statement It is also possible to import all names from a module into the current namespace by using the following import statement: from modname import * This provides an easy way to import all the items from a module into the current namespace. Here is a typical PYTHONPATH from a Windows system: set PYTHONPATH=c:\python20\lib. The sys. to import the function fibonacci from the module fib. The module search path is stored in the system module sys as the sys.1 The PYTHONPATH Variable The PYTHONPATH is an environment variable. it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.. On UNIX. however. PYTHONPATH.3 The from.

6 Namespaces and Scoping Variables are names (identifiers) that map to objects. Within the function Money. 'floor'.f #!/usr/bin/python Money = 2000 def AddMoney(): # Uncomment the following line to fix the code: # global Money Money = Money + 1 print Money AddMoney() print Money 13. However. 'ceil'. This would produce following result: ['__doc__'. in order to assign a value to a global variable within a function. Uncommenting the global statement fixes the problem. Therefore Python assumes Money is a local variable. 'fabs'. Each function has its own local namespace. we define a variable Money in the global namespace. '__file__'. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). 'e'. you must first use the global statement. 'frexp'. 'log'. A Python statement can access variables in a local namespace and in the global namespace. '__name__'. The list contains the names of all the modules. It assumes that any variable assigned a value in a function is local. the local variable shadows the global variable. 'hypot'. 'cosh'. Python stops searching the local namespace for the variable. 'acos'. 'ldexp'. The statement global VarName tells Python that VarName is a global variable. Example: #!/usr/bin/python # Import built-in module math import math content = dir(math) print content. If a local and a global variable have the same name. Class methods follow the same scoping rule as ordinary functions. 'degrees'. 'exp'. Python makes educated guesses on whether variables are local or global. 'cos'. Therefore. 'asin'. so an UnboundLocalError is the result. and functions that are defined in a module. variables. 'atan'. 'atan2'. we assign Money a value . .7 The dir( ) Function The dir() built-in function returns a sorted list of strings containing the names defined by a module.13. For example. we access the value of the local variable Money before setting it. 'fmod'.

'sqrt'. 13. 'tanh'] Here the special string variable __name__ is the module's name. and so on.py file having function Isdn() Phone/G3. 13. 'sin'.py available in Phone directory. 'pi'. If globals() is called from within a function. you have all of these classes available when you've imported the Phone package: .py file having function G3() Now create one more file __init__.py in Phone directory : • Phone/__init__. it will return all the names that can be accessed locally from that function.py as follows: from Pots import Pots from Isdn import Isdn from G3 import G3 After you've added these lines to __init__. The return type of both these functions is dictionary.'log10'.py. 'tan'. This file has following line of source code: #!/usr/bin/python def Pots(): print "I'm Pots Phone" Similar way we have another two files having different functions with the same name as above: • • Phone/Isdn. 'radians'. and __file__ is the filename from which the module was loaded. it will return all the names that can be accessed globally from that function. If locals() is called from within a function. you need to put explicit import statements in __init__.8 The globals() and locals() Functions The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. 'modf'.9 Packages in Python A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules and subpackages and sub-subpackages. 'pow'. Example: Consider a file Pots.py To make all of your functions available when you've imported Phone. 'sinh'. names can be extracted using the keys() function. Therefore.

G3() This would produce following result: I'm Pots Phone I'm 3G Phone I'm ISDN Phone Note: In the above example. we have taken example of a single functions in each file.Pots() Phone. You can also define different Python classes in those files and then you can create your packages out of those classes. but you can keep multiple functions in your files.Isdn() Phone.#!/usr/bin/python # Now import your Phone Package. . import Phone Phone.

This is optional paramter. If the file does not exist. A complete list of possible values is given below in the table. Opens a file for writing only in binary format.Chapter 14 Python Files I/O 14. This is optional parameter and the default file access mode is read (r) buffering: If the buffering value is set to 0. Now we will see how to play with actual data files. you have been reading and writing to the standard input and output. creates a new file for writing. If the file does not exist. The file pointer is placed at the beginning of the file. buffering]) Here is paramters detail: • • • file_name: The file_name argument is a string value that contains the name of the file that you want to access. no buffering will take place. creates a new file for writing.1 Opening and Closing Files Until now. The file pointer will be at the beginning of the file. access_mode: The access_mode determines the mode in which the file has to be opened ie. access_mode][. Opens a file for writing only. file object = open(file_name [. Here is a list of the different modes of opening a file: Modes r rb r+ rb+ w wb w+ Description Opens a file for reading only. Opens a file for both reading and writing in binary format. Overwrites the existing file if the file exists. . Opens a file for both reading and writing. Overwrites the file if the file exists. you have to open it using Python's built-in open() function. creates a new file for reading and writing. If the buffering value is 1. Python provides basic functions and methods necessary to manipulate files by default. line buffering will be performed while accessing a file. Opens a file for reading only in binary format. then buffering action will be performed with the indicated buffer size. write append etc. read. Before you can read or write a file. You can do your most of the file manipulation using a file object. The file pointer will be at the beginning of the file. If the file does not exist. Opens a file for both writing and reading. Overwrites the file if the file exists. This is the default mode. This is the default mode. The file pointer is placed at the beginning of the file. This function creates a file object which would be utilized to call other support methods associated with it. If you specify the buffering value as an integer greater than 1.

read() will return an empty string ("").read(size).close(). a ab a+ ab+ One can open and use files for reading or writing by creating an object of the file class. If the file does not exist. f. f. mode). Opens a file for both appending and reading. That is. ’r’ will be assumed if it’s omitted. the file is in the append mode. Opens a file for appending. Opens a file for both appending and reading in binary format. it creates a new file for writing. To read a file’s contents. The file opens in the append mode. Opens a file for appending in binary format.txt'. and ’a’ opens the file for appending. The file pointer is at the end of the file if the file exists. where size indicates the no of bytes to be read and it is optional. mode can be ’r’ when the file will only be read. creates a new file for reading and writing.close() method is to close the file f and free up any system resources taken up by the open file. attempts to use the file object will automatically fail.seek() method is to change the position.tell() returns an integer giving the file object’s current position in the file. If the file does not exist. If the file does not exist. f. poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = open('poem.write(string) writes the contents of string to the file. That is. The second argument is another string containing a few characters describing the way in which the file will be used. If the file does not exist. The file pointer is at the end of the file if the file exists.wb+ Opens a file for both writing and reading in binary format. It is a good practice to use the close() method to close a file.readlines() returns a list containing all the lines of data in the file. it creates a new file for reading and writing. ’r+’ opens the file for both reading and writing. The file pointer is at the end of the file if the file exists. Overwrites the existing file if the file exists. it creates a new file for reading and writing.readline() reads a single line from the file. read(). f. f. If the file does not exist. The 'b' mode is to open a binary file and 't' mode is to open a text file. The first argument is a string containing the filename. readline() and write() are methods of file object. Python automatically closes a file when the reference object of a file is reassigned to another file. call f. The file pointer is at the end of the file if the file exists. The close() method of a file object flushes any unwritten information and closes the file object. ’w’ for only writing (an existing file with the same name will be erased). returning None. any data written to the file is automatically added to the end. 'w') # open for 'w'riting . f. the file is in the append mode. If the end of the file has been reached. After calling f. it creates a new file for writing. A file is opened by using open() command in the form f=open(filename. The mode argument is optional. after which no more writing can be done. f. The file opens in the append mode.

remove. we have to first open the file in 'w'rite 'b'inary mode and then call the dump function of the pickle module. 'wb') pickle. The os module has several methods that help you create. and Python has no problem handling these too.write(poem) # write text to file f. You can use the mkdir() method of the os module to create directories in the current directory.chdir("/home/newdir") .3 Directories in Python All files are contained within various directories. which is the name of the directory that you want to make the current directory. and change directories.close() # close the file 14. 'r'ead mode is assumed by default while True: line = f. Following is the example to create a directory test in the current directory #!/usr/bin/python import os # Create a directory "test" os.close() f=open(numberlist. The chdir() method takes an argument.close() # close the file f = open('poem. This process is called pickling.f. import pickle x=range(10) f=open(numberlist.f) f. we retrieve the object using the load function of the pickle module which returns the object.readline() if len(line) == 0: # Zero length indicates EOF break print(line. This process is called unpickling.2 The pickle Module Python provides a standard module called pickle using which you can store any Python object in a file and then get it back later. which contains the name of the directory to be created.txt') # if no mode is specified. #!/usr/bin/python import os # Changing a directory to "/home/newdir" os. To store an object in a file. Next.mkdir("test") You can use the chdir() method to change the current directory.dump(x. end='') f.load(f) print y 14. You need to supply an argument to this method.'rb') y= pickle. See the following example.

os.rmdir( "/tmp/test" ) . which is passed as an argument in the method.getcwd() The rmdir() method deletes the directory. all the contents in it should be removed. Before removing a directory. #!/usr/bin/python import os # This would give location of the current directory os.The getcwd() method displays the current working directory. #!/usr/bin/python import os # This would remove "/tmp/test" directory.

Function overloading: The assignment of more than one behavior to a particular function. Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class. The attributes are data members (class variables and instance variables) and methods.1 Overview of OOP Terminology Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class.Chapter 15 Python . 15. Instantiation : The creation of an instance of a class.e. There is another way of organizing your program which is to combine data and . Because of this. 15. If you don't have any previous experience with object-oriented (OO) programming. here is small introduction of Object-Oriented Programming (OOP) to bring you at speed. Method : A special kind of function that is defined in a class definition.2 Classes In all the programs we wrote till now. This chapter helps you become an expert in using Python's object-oriented programming support.Object Oriented Python has been an object-oriented language from day one. An object comprises both data members (class variables and instance variables) and methods. An object obj that belongs to a class Circle. Data member: A class variable or instance variable that holds data associated with a class and its objects. for example. This is called the procedure-oriented way of programming. Class variable: A variable that is shared by all instances of a class. Class variables aren't used as frequently as instance variables are. However. accessed via dot notation. Operator overloading: The assignment of more than one function to a particular operator. Class variables are defined within a class but outside any of the class's methods. blocks of statements which manipulate data. Instance: An individual object of a certain class. Object : A unique instance of a data structure that's defined by its class. creating and using classes and objects are downright easy. is an instance of the class Circle. you may want to consult an introductory course on it or at least a tutorial of some sort so that you have a grasp of the basic concepts. The operation performed varies by the types of objects (arguments) involved. Inheritance : The transfer of the characteristics of a class to other classes that are derived from it. we have designed our program around functions i.

The fields and methods of the class are listed in an indented block. The method is useful for initialising an object. fields. A class creates a new type where objects are instances of the class. 15.name = sname      def sayHi(self):           print('Hello.py  class Person:      def __init__(self. Now create an object of this class p=student() p. It passes the arguments in the parentheses following the class name when creating a new instance of the class.name field in our methods which is demonstrated in the sayHi method.sayHi()  The __init__ method as taking a parameter name (along with the usual self).sayhi() p is an object of type student. Such functions are called methods of the class. Variables that belong to an object or class are referred to as fields.3 Creating Classes A class is created using the class keyword. It has a method 'sayhi'. One of them is __init__ method. my name is'. Objects can store data using ordinary variables that belong to the object.Classes and objects are the two main aspects of object oriented programming. self.e.name)  p = Person('Swaroop')  p. This is called the object oriented programming. There are many significant methods in python classes. The __init__ method is run as soon as an object of a class is instantiated. Example: #!/usr/bin/python  # Filename: class_init. p. Here we see the self in action. Let us create a new class student. Notice that the sayhi method takes no parameters but still has the self in the function definition. Class student: def sayhi(self): print ' Hello how are you' Here class student is created. i. This is the special significance of this method. We are able to use the self. sname):           self. Fields are of two types .sayhi() will display 'hello how are you'. This means that these names are valid within the context of . for which value is assigned not by user but by python itself. 15. a class has an extra argument called self. One specific difference between a function and class is that.functionality and wrap it inside something called an object. are nothing but ordinary variables that are bound to the namespaces of the classes and objects. the fields and methods can be referred to as the attributes of that class.they can belong to each instance/object of the class or they can belong to the class itself. Collectively. Objects can also have functionality by using functions that belong to a class. They are called instance variables and class variables respectively.4 Class And Object Variables The data part.

There are two types of fields .name) student.e.name=sname print ' Initialising %s ' %(self. sname): self. marks and fees for students.these classes and objects only. There are many advantages to this approach. strength belongs to student class and hence is a class variable. Class variables are shared . They have some common characteristics such as name. you can add a new ID card field for . The size is actually a method that belongs to the class and not to the object and here it is static method.5 Inhertitance One of the major benefits of object oriented programming is reuse of code and one of the ways to achieve this is through the inheritance mechanism. The variable sname belongs to an object and hence is an object variable.name) def size(): print ' Now the student strength is %d' %(student. each object has its own copy of the field i. age and address. To remove the object p type p. they will become sub-types of this type (class) and then we can add specific characteristics to these sub-types. courses and leaves for teachers and. p. There is only one copy of the class variable and when any one object makes a change to a class variable.strength) size=staticmethod(size)  p=student('Sunil T P') q=student('Rajan T K') r=student('Jalaja M') student.class variables and object variables which are classified depending on whether the class or the object owns the variables respectively. That's why they are called name spaces. Class student: strength=0 def __init__(self. A better way would be to create a common class called SchoolMember and then have the teacher and student classes inherit from this class i.e. You can create two independent classes for each type and process them but adding a new common characteristic would mean adding to both of these independent classes. In this case. An example will make this easy to understand.they can be accessed by all instances of that class. that change will be seen by all the other instances. Suppose you want to write a program which has to keep track of the teachers and students in a college.strength +=1 def remove(self): print 'Removing %s from the roll' %(self. they are not shared and are not related in any way to the field by the same name in a different instance.strength) else: print ' %s is the last student in the roll' %(self. instances of the class. this is automatically reflected in the subtypes as well. If we add/change any functionality in SchoolMember. Inheritance can be best imagined as implementing a type and subtype relationship between classes. They also have specific characteristics such as salary. For example. There is a special method remove() for removing an object created. Object variables are owned by each individual object/instance of the class. This quickly becomes unwieldy.strength ­=1 if student.remove() 15.strength==0: print   'there   are   still   %d   students   in   the   roll'% (student.size() In this example student is the class name.q and r are objects.name) student. Namespace is a function that maps names and objects.

salary = salary           print '(Initialized Teacher: {0})'. marks):           SchoolMember.marks = marks           print '(Initialized Student: {0})'. name.format(self. class SchoolMember:       '''Represents any school member.format(self. name.e. age)           self.format(self.'''       def __init__(self. s]  for member in members:       member. age)           self. 40. name.name = name           self. Let us see the following example.format(self. name.__init__(self. 75)  members = [t.'''       def __init__(self.tell() # works for both Teachers and Students  . Shrividya'. 30000)  s = Student('Swaroop'.name)       def tell(self):           SchoolMember.both teachers and students by simply adding it to the SchoolMember class. name.age) class Teacher(SchoolMember):       '''Represents a teacher.format(self.age = age           print (Initialized SchoolMember: {0})'.marks) t = Teacher('Mrs. self. However.name)      def tell(self):           SchoolMember. age.name)      def tell(self):           '''Tell my details.__init__(self.name. the object can be treated as an instance of the parent class.'''       def __init__(self.format(self.tell(self)           print 'Salary: "{0:d}"'. salary):           SchoolMember. Another advantage is that if you can refer to a teacher or student object as a SchoolMember object which could be useful in some situations such as counting of the number of school members.'''           print 'Name:"{0}" Age:"{1}"'. age. Also observe that we reuse the code of the parent class and we do not need to repeat it in the different classes as we would have had to in case we had used independent classes. changes in the subtypes do not affect other subtypes.tell(self)           print 'Marks: "{0:d}"'.salary) class Student(SchoolMember):       '''Represents a student. The Teacher and Student classes are called the derived classes or subclasses. This is called polymorphism where a sub-type can be substituted in any situation where a parent type is expected i. age):           self. The SchoolMember class in this situation is known as the base class or the superclass. 25.

the try clause (the statement(s) between the try and except keywords) is executed. First. it may cause an error when an attempt is made to execute it.2 Try Statement It is possible to write programs that handle selected exceptions by using Try statement. Otherwise. If no exception occurs. Example: try: text = input('Enter something --> ') except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.format(text)) Note that there has to be at least one except clause associated with every try clause. Only error freed program runs successfully. . 16. . try statement can have many except clauses. The general form of Try statement is try: statement1 . if no handler is found. then the default Python handler is called which just stops the execution of the program and prints an error message. One can also have an else clause associated with a try- . Even if a statement or expression is syntactically correct. . At most one handler will be executed. the rest of the clause is skipped. . The errors in python are classified into three type 1. Errors detected during execution are called exceptions . We have already seen this in action above. . the except clause is executed. it is an unhandled exception and execution stops with a message as shown above. Symantic Error. . . . and then execution continues after the try statement. are certain type of exceptions. If an exception occurs during execution of the try clause.') else: print('You entered {0}'. . The error in the use of python language is syntax error. . . ZeroDivisionError. Then if its type matches the exception named after the except keyword. to specify handlers for different exceptions. . NameError etc. If an exception occurs which does not match the exception named in the except clause.1 Errors in Python Commonly a python program may not be error free. . Syntax Error 2.Chapter 16 Python-Errors and Exceptions 16. Where as the symantic error is the error in the ouput. it is passed on to outer try statements. even if the program is without synatx error and exception. Run time Error ( Exception) 3. except: statement2 . the except clause is skipped and execution of the try statement is finished. . . . TypeError. what's the point of having a try block? If any error or exception is not handled.

ex. def divide(x..4 Try .except block.close() print('(Cleaning up: Closed the file)') A finally clause is always executed before leaving the try statement. atleast): Exception.txt') while True: # our usual file-reading idiom line = f.Finally A try statement can have another clause called finally.') 16.length. whether an exception has occurred or not.') finally: f. y): .atleast = atleast try: text = input('Enter something --> ') if len(text) < 3: raise ShortInputException(len(text). See the example import time try: f = open('poem. The else clause is executed if no exception occurs. 16. length.''' def __init__(self.__init__(self) self.sleep(2) # To make sure it runs for a while except KeyboardInterrupt: print('!! You cancelled the reading from the file. 3) # Other work can continue as usual here except EOFError: print('Why did you do an EOF on me?') except KeyboardInterrupt: print('You cancelled the operation.3 Raising Exceptions You can raise exceptions using the raise statement by providing the name of the error/exception and the exception object that is to be thrown. class ShortInputException(Exception): '''A user-defined exception class. expected at least {1}'. Let us create our won exception type called ShortInputException having 2 fields length and minimum length for input.atleast)) else: print('No exception was raised.format(ex.length = length self. The error or exception that you can raise should be class which directly or indirectly must be a derived class of the Exception class.') except ShortInputException as ex: print('ShortInputException: The input was {0} long.readline() if len(line) == 0: break print(line) time.

1) result is 2 executing finally clause >>> divide(2.result = x / y except ZeroDivisionError: print "division by zero!" else: print "result is". result finally: print "executing finally clause" >>> divide(2. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed. 0) division by zero! executing finally clause >>> divide("2". "1") executing finally clause try: TypeError: unsupported operand type(s) for /: ’str’ and ’str’ The finally clause is executed in any event. .

system(‘time 0:02’) 0 >>> os. ’archive. >>> import os >>> dir(os) <returns a list of all module functions> >>> help(os) <returns an docstrings> extensive manual page created from the module’s # Return the current working directory For daily file and directory management tasks. >>> import glob >>> glob.Chapter 17 BRIEF TOUR OF THE STANDARD LIBRARY Operating System Interface: The os module provides dozens of functions for interacting with the operating system.getcwd() ’C:>Python26’ >>> os. ’installdir’) The glob module provides a function for making file lists from directory wildcard searches.move(’/build/executables’.db’. >>> import os >>> os. the shutil module provides a higher level interface that is easier to use: >>> import shutil >>> shutil.db’) >>> shutil.copyfile(‘data.chdir(’/server/accesslogs’) The builtin dir() and help() functions are useful as interactive aids for working with large modules like os.py’) .glob(’*.

. # random integer chosen from range(6) # random float / if ’EST’ in line or ’EDT’ in line: # look for Eastern Time print line .navy. 33] >>> random. 18.org/’) >>>html = response.mil cgi-bin / timer.pi / 4..urlopen(’http://www. 50. Two of the simplest are urllib2 for retrieving data from urls and smtplib for sending mail.py’] The math module gives access to the underlying C library functions for floating point math.py’.0 The random module provides tools for making random selections.usno.py’. >>> import random >>> random.choice([’apple’. ’random. 16. ’banana’]) ’apple’ >>> random.pl’): . 83.. Example 1 >>>import urllib2 >>>response = urllib2.random() 0.0) 0.tycho.sample(xrange(100).[’primes. 2) 10. 8.. ’quote.cos(math. 81.17970987693706186 >>> random.70710678118654757 >>> math. replacement 10) # sampling without [30.read() Example 2 >>> import urllib2 >>>for line in urllib2.log(1024. 41. ’pear’.randrange(6) 4 There are a number of modules for accessing the internet and processing internet protocols. >>> import math >>> math..urlopen(’http://python. 4.

""") >>> server..org .SMTP(’localhost’) >>>server.’ # dates support calendar arithmetic >>> birthday = date(1964. 7. . %d %b %Y is a %A on the %d day of %B..today() >>> now datetime.. 02 Dec 2003 is a Tuesday on the 02 day of December..date(2003.birthday >>> age. 12.days 14368 Output Formatting: The repr module provides a version of repr() customized for abbreviated displays of large or . From: soothsayer@example. 31) >>> age = now .strftime("%m-%d-%y..") ’12-02-03.. .sendmail(’soothsayer@example. Beware the Ides of March.. jcaesar@example.org . """To: jcaesar@example. .org’. # dates are easily constructed and formatted >>> from datetime import date >>> now = date. 2) >>> now..org’..Example 3 >>> import smtplib >>> server = smtplib..quit() The datetime module supplies classes for manipulating dates and times in both simple and complex ways.

])" The pprint module offers more sophisticated control over printing both built-in and user defined objects in a way that is readable by the interpreter. [[’magenta’. . width=30) [[[[’black’. . >>> import repr >>> repr. width=40) The wrap() method is just like fill() except that it returns .. ’blue’]]] The textwrap module formats paragraphs of text to fit a given screen width.deeply nested containers.. >>> pprint.pprint(t.. ’red’]]. a list of strings instead of one big string with newlines to separate .fill(doc.. the wrapped lines. ’g’. ’c’.... When the result is longer than one line. >>> print textwrap. the “pretty printer” adds line breaks and indentation to more clearly reveal data structure. ’cyan’].repr(set(’supercalifragilisticexpialidocious’)) "set([’a’. >>> import textwrap >>> doc = """The wrap() method is just like fill() except that it returns . ’white’.. ’white’. ’yellow’]. [[’magenta’... ’blue’]]] . . [’green’. a list of strings instead of one big string with ’cyan’].""" .. ’red’]]. ’f’.. ’yellow’]. ’d’. [’green’.. >>> import pprint >>> t = [[[[’black’.. ’e’.

grouping=True) ’1. (conv[’currency_symbol’]. cause=’the ditch fund’) ’Nottinghamfolk send $10 to the ditch fund. The format uses placeholder names formed by $ with valid Python identifiers in brace brackets.234. x.*f".234.. grouping=True) .05 0..substitute(village=’Nottingham’.567’ >>> locale. x).’) >>> t.7350") >>> .80’ The string module includes a versatile Template class with a simplified syntax suitable for editing by end users.format("%d"..73499999999999999 conv[’frac_digits’].format("%s%.567.05’) Decimal("0. >>> from decimal import * >>> Decimal(’0.’ The decimal module offers a Decimal datatype for decimal floating point arithmetic.70’) * Decimal(’1.8 >>> locale.newlines to separate .70 * 1. the wrapped lines. The locale module accesses a database of culture specific data formats.. ’$1. >>> from string import Template >>> t = Template(’${village}folk send $$10 to $cause. . This allows users to customize their applications without having to alter the application. The grouping attribute of locale’s format function provides a direct way of formatting numbers with group separators: >>> import locale >>> x = 1234567.

Sign up to vote on this title
UsefulNot useful