Programming Using Python 1 PDF
Document Details
Ravinder Sheoran
Tags
Summary
This is an introduction to computer programming using Python. It covers basic concepts such as variables, data types, and lists. The document details how various data types, such as numbers, string, lists, tuples, and dictionaries, are used in Python.
Full Transcript
Computer Programming using Python: by Ravinder Sheoran Python – Introduction Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fe...
Computer Programming using Python: by Ravinder Sheoran Python – Introduction Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages. Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games. 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. 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 Guido van Rossum still holds a vital role in directing its progress. Python Features Python's features include − Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly. Easy-to-read − Python code is more clearly defined and visible to the eyes. 1 Computer Programming using Python: by Ravinder Sheoran Easy-to-maintain − Python's source code is fairly easy-to-maintain. A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. Interactive Mode − Python has support for an interactive mode which allows 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. Apart from the above-mentioned features, Python has a big list of good features, few are listed below − It supports functional and structured programming methods as well as OOP. It can be used as a scripting language or can be compiled to byte-code for building large applications. It provides very high-level dynamic data types and supports dynamic type checking. It supports automatic garbage collection. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. Python- Variables Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 2 Computer Programming using Python: by Ravinder Sheoran Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. Assigning Values to Variables Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example − #!/usr/bin/python counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string print counter print miles print name Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively. This produces the following result − 100 1000.0 John Multiple Assignment Python allows you to assign a single value to several variables simultaneously. For example − a=b=c=1 3 Computer Programming using Python: by Ravinder Sheoran Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example − a,b,c = 1,2,"john" Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c. Standard Data Types The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Python has five standard data types − Numbers String List Tuple Dictionary Python Numbers Number data types store numeric values. Number objects are created when you assign a value to them. For example − var1 = 1 var2 = 10 You can also delete the reference to a number object by using the del statement. The syntax of the del statement is − del var1[,var2[,var3[..... ,varN]]]] You can delete a single object or multiple objects by using the del statement. For example − del var del var_a, var_b 4 Computer Programming using Python: by Ravinder Sheoran Python supports four different numerical types − int (signed integers) long (long integers, they can also be represented in octal and hexadecimal) float (floating point real values) complex (complex numbers) Examples Here are some examples of numbers − int long float complex 10 51924361L 0.0 3.14j 100 -0x19323L 15.20 45.j -786 0122L -21.9 9.322e-36j 080 0xDEFABCECBDAECBFBAEl 32.3+e18.876j -0490 535633629843L -90. -.6545+0J -0x260 -052318172735L -32.54e100 3e+26J 0x69 -4721885298529L 70.2-E12 4.53e-7j Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L. A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit. Python Strings 5 Computer Programming using Python: by Ravinder Sheoran Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. 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. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example − #!/usr/bin/python str = 'Hello World!' print str # Prints complete string print str # Prints first character of the string print str[2:5] # Prints characters starting from 3rd to 5th print str[2:] # Prints string starting from 3rd character print str * 2 # Prints string two times print str + "TEST" # Prints concatenated string This will produce the following result − Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST Python Lists Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. 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 6 Computer Programming using Python: by Ravinder Sheoran way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example − #!/usr/bin/python list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print list # Prints complete list print list # Prints first element of the list print list[1:3] # Prints elements starting from 2nd till 3rd print list[2:] # Prints elements starting from 3rd element print tinylist * 2 # Prints list two times print list + tinylist # Prints concatenated lists This produce the following result − ['abcd', 786, 2.23, 'john', 70.2] abcd [786, 2.23] [2.23, 'john', 70.2] [123, 'john', 123, 'john'] ['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] Python Tuples A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example − #!/usr/bin/python 7 Computer Programming using Python: by Ravinder Sheoran tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print tuple # Prints complete list print tuple # Prints first element of the list print tuple[1:3] # Prints elements starting from 2nd till 3rd print tuple[2:] # Prints elements starting from 3rd element print tinytuple * 2 # Prints list two times print tuple + tinytuple # Prints concatenated lists This produce the following result − ('abcd', 786, 2.23, 'john', 70.2) abcd (786, 2.23) (2.23, 'john', 70.2) (123, 'john', 123, 'john') ('abcd', 786, 2.23, 'john', 70.2, 123, 'john') The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists − #!/usr/bin/python tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tuple = 1000 # Invalid syntax with tuple list = 1000 # Valid syntax with list Python Dictionary Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]). For example − 8 Computer Programming using Python: by Ravinder Sheoran #!/usr/bin/python dict = {} dict['one'] = "This is one" dict = "This is two" tinydict = {'name': 'john','code':6734, 'dept': 'sales'} print dict['one'] # Prints value for 'one' key print dict # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values This produce the following result − This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john'] Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered. Data Type Conversion Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value. 9 Computer Programming using Python: by Ravinder Sheoran Sr.No. Function & Description 1 int(x [,base]) Converts x to an integer. base specifies the base if x is a string. 2 long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string. 3 float(x) Converts x to a floating-point number. 4 complex(real [,imag]) Creates a complex number. 5 str(x) Converts object x to a string representation. 6 repr(x) Converts object x to an expression string. 7 eval(str) Evaluates a string and returns an object. 8 tuple(s) Converts s to a tuple. 9 list(s) Converts s to a list. 10 set(s) 10 Computer Programming using Python: by Ravinder Sheoran Converts s to a set. 11 dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. 12 frozenset(s) Converts s to a frozen set. 13 chr(x) Converts an integer to a character. 14 unichr(x) Converts an integer to a Unicode character. 15 ord(x) Converts a single character to its integer value. 16 hex(x) Converts an integer to a hexadecimal string. 17 oct(x) Converts an integer to an octal string. Basic Operators Operators are the constructs which can manipulate the value of operands. Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator. Types of Operator Python language supports the following types of operators. 11 Computer Programming using Python: by Ravinder Sheoran Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators Let us have a look on all operators one by one. Python Arithmetic Operators Assume variable a holds 10 and variable b holds 20, then − [ Show Example ] Operator Description Example + Addition Adds values on either side of the operator. a+b= 30 - Subtraction Subtracts right hand operand from left hand operand. a–b=- 10 * Multiplies values on either side of the operator a*b= Multiplication 200 / Division Divides left hand operand by right hand operand b/a=2 % Modulus Divides left hand operand by right hand operand and b%a= returns remainder 0 ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20 12 Computer Programming using Python: by Ravinder Sheoran // Floor Division - The division of operands where the 9//2 = 4 result is the quotient in which the digits after the and decimal point are removed. But if one of the operands 9.0//2.0 is negative, the result is floored, i.e., rounded away = 4.0, - from zero (towards negative infinity) − 11//3 = -4, - 11.0//3 = -4.0 Python Comparison Operators These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then − [ Show Example ] Operator Description Example == If the values of two operands are equal, then the condition (a == b) becomes true. is not true. != If values of two operands are not equal, then condition (a != b) becomes true. is true. If values of two operands are not equal, then condition (a b) becomes true. is true. This is similar to != operator. > If the value of left operand is greater than the value of (a > b) right operand, then condition becomes true. is not true. < If the value of left operand is less than the value of right (a < b) operand, then condition becomes true. is true. 13 Computer Programming using Python: by Ravinder Sheoran >= If the value of left operand is greater than or equal to the (a >= b) value of right operand, then condition becomes true. is not true. >> Type the following text at the Python prompt and press the Enter − >>> print "Hello, Python!" If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result − Hello, Python! Script Mode Programming 38 Computer Programming using Python: by Ravinder Sheoran 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. Python files have extension.py. Type the following source code in a test.py file − print "Hello, Python!" We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows − $ python test.py This produces the following result − Hello, Python! Let us try another way to execute a Python script. Here is the modified test.py file − #!/usr/bin/python print "Hello, Python!" We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows − $ chmod +x test.py # This is to make file executable $./test.py This produces the following result − Hello, Python! 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 39 Computer Programming using Python: by Ravinder Sheoran 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 naming conventions for Python identifiers − Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Starting an identifier with a single leading underscore indicates that the identifier is private. Starting an identifier with two leading underscores indicates a strongly private identifier. If the identifier also ends with two trailing underscores, the identifier is a language-defined special name. Reserved Words The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only. and exec not assert finally or break for pass class from print continue global raise def if return 40 Computer Programming using Python: by Ravinder Sheoran del import try elif in while else is with except lambda yield Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example − if True: print "True" else: print "False" However, the following block generates an error − if True: print "Answer" print "True" else: print "Answer" print "False" Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks − Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces. 41 Computer Programming using Python: by Ravinder Sheoran #!/usr/bin/python import sys try: # open file stream file = open(file_name, "w") except IOError: print "There was an error writing to", file_name sys.exit() print "Enter '", file_finish, print "' When finished" while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish: # close the file file.close break file.write(file_text) file.write("\n") file.close() file_name = raw_input("Enter filename: ") if len(file_name) == 0: print "Next time please enter something" sys.exit() try: file = open(file_name, "r") except IOError: 42 Computer Programming using Python: by Ravinder Sheoran print "There was an error reading file" sys.exit() file_text = file.read() file.close() print file_text Multi-Line Statements Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example − total = item_one + \ item_two + \ item_three Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example − days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] Quotation in Python Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal − word = 'word' sentence = "This is a sentence." paragraph = """This is a paragraph. It is made up of multiple lines and sentences.""" Comments in Python A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them. #!/usr/bin/python 43 Computer Programming using Python: by Ravinder Sheoran # First comment print "Hello, Python!" # second comment This produces the following result − Hello, Python! You can type a comment on the same line after a statement or expression − name = "Madisetti" # This is again comment You can comment multiple lines as follows − # This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments: ''' This is a multiline comment. ''' Using Blank Lines A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it. In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement. Waiting for the User The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action − #!/usr/bin/python raw_input("\n\nPress the enter key to exit.") Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a console window open until the user is done with an application. 44 Computer Programming using Python: by Ravinder Sheoran Multiple Statements on a Single Line The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon − import sys; x = 'foo'; sys.stdout.write(x + '\n') Multiple Statement Groups as Suites A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite. 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. For example − if expression : suite elif expression : suite else : suite Command Line Arguments Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h − $ python -h usage: python [option]... [-c cmd | -m mod | file | -] [arg]... 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 [ etc. ] 45 Computer Programming using Python: by Ravinder Sheoran You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic and should be studied a bit later once you have gone through rest of the Python concepts Regular Expressions A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression. We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'. The match Function This function attempts to match RE pattern to string with optional flags. Here is the syntax for this function − re.match(pattern, string, flags=0) Here is the description of the parameters − Sr.No. Parameter & Description 1 pattern This is the regular expression to be matched. 2 string This is the string, which would be searched to match the pattern at the beginning of string. 46 Computer Programming using Python: by Ravinder Sheoran 3 flags You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. The re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression. Sr.No. Match Object Method & Description 1 group(num=0) This method returns entire match (or specific subgroup num) 2 groups() This method returns all matching subgroups in a tuple (empty if there weren't any) Example #!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?).*', line, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: 47 Computer Programming using Python: by Ravinder Sheoran print "No match!!" When the above code is executed, it produces following result − matchObj.group() : Cats are smarter than dogs matchObj.group(1) : Cats matchObj.group(2) : smarter The search Function This function searches for first occurrence of RE pattern within string with optional flags. Here is the syntax for this function − re.search(pattern, string, flags=0) Here is the description of the parameters − Sr.No. Parameter & Description 1 pattern This is the regular expression to be matched. 2 string This is the string, which would be searched to match the pattern anywhere in the string. 3 flags You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression. Sr.No. Match Object Methods & Description 1 group(num=0) 48 Computer Programming using Python: by Ravinder Sheoran This method returns entire match (or specific subgroup num) 2 groups() This method returns all matching subgroups in a tuple (empty if there weren't any) Example #!/usr/bin/python import re line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?).*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!" When the above code is executed, it produces following result − searchObj.group() : Cats are smarter than dogs searchObj.group(1) : Cats searchObj.group(2) : smarter Matching Versus Searching Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while searchchecks for a match anywhere in the string (this is what Perl does by default). 49 Computer Programming using Python: by Ravinder Sheoran Example #!/usr/bin/python import re line = "Cats are smarter than dogs"; matchObj = re.match( r'dogs', line, re.M|re.I) if matchObj: print "match --> matchObj.group() : ", matchObj.group() else: print "No match!!" searchObj = re.search( r'dogs', line, re.M|re.I) if searchObj: print "search --> searchObj.group() : ", searchObj.group() else: print "Nothing found!!" When the above code is executed, it produces the following result − No match!! search --> matchObj.group() : dogs Search and Replace One of the most important re methods that use regular expressions is sub. Syntax re.sub(pattern, repl, string, max=0) This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string. 50 Computer Programming using Python: by Ravinder Sheoran Example #!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'\D', "", phone) print "Phone Num : ", num When the above code is executed, it produces the following result − Phone Num : 2004-959-559 Phone Num : 2004959559 Regular Expression Modifiers: Option Flags Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these − Sr.No. Modifier & Description 1 re.I Performs case-insensitive matching. 2 re.L 51 Computer Programming using Python: by Ravinder Sheoran Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior(\b and \B). 3 re.M Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string). 4 re.S Makes a period (dot) match any character, including a newline. 5 re.U Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B. 6 re.X Permits "cuter" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker. Regular Expression Patterns Except for control characters, (+ ?. * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a control character by preceding it with a backslash. Following table lists the regular expression syntax that is available in Python − Sr.No. Pattern & Description 1 ^ Matches beginning of line. 52 Computer Programming using Python: by Ravinder Sheoran 2 $ Matches end of line. 3. Matches any single character except newline. Using m option allows it to match newline as well. 4 [...] Matches any single character in brackets. 5 [^...] Matches any single character not in brackets 6 re* Matches 0 or more occurrences of preceding expression. 7 re+ Matches 1 or more occurrence of preceding expression. 8 re? Matches 0 or 1 occurrence of preceding expression. 9 re{ n} Matches exactly n number of occurrences of preceding expression. 10 re{ n,} Matches n or more occurrences of preceding expression. 11 re{ n, m} 53 Computer Programming using Python: by Ravinder Sheoran Matches at least n and at most m occurrences of preceding expression. 12 a| b Matches either a or b. 13 (re) Groups regular expressions and remembers matched text. 14 (?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected. 15 (?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected. 16 (?: re) Groups regular expressions without remembering matched text. 17 (?imx: re) Temporarily toggles on i, m, or x options within parentheses. 18 (?-imx: re) Temporarily toggles off i, m, or x options within parentheses. 19 (?#...) Comment. 20 (?= re) Specifies position using a pattern. Doesn't have a range. 54 Computer Programming using Python: by Ravinder Sheoran 21 (?! re) Specifies position using pattern negation. Doesn't have a range. 22 (?> re) Matches independent pattern without backtracking. 23 \w Matches word characters. 24 \W Matches nonword characters. 25 \s Matches whitespace. Equivalent to [\t\n\r\f]. 26 \S Matches nonwhitespace. 27 \d Matches digits. Equivalent to [0-9]. 28 \D Matches nondigits. 29 \A Matches beginning of string. 30 \Z Matches end of string. If a newline exists, it matches just before 55 Computer Programming using Python: by Ravinder Sheoran newline. 31 \z Matches end of string. 32 \G Matches point where last match finished. 33 \b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. 34 \B Matches nonword boundaries. 35 \n, \t, etc. Matches newlines, carriage returns, tabs, etc. 36 \1...\9 Matches nth grouped subexpression. 37 \10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. Regular Expression Examples Literal characters Sr.No. Example & Description 56 Computer Programming using Python: by Ravinder Sheoran 1 python Match "python". Character classes Sr.No. Example & Description 1 [Pp]ython Match "Python" or "python" 2 rub[ye] Match "ruby" or "rube" 3 [aeiou] Match any one lowercase vowel 4 [0-9] Match any digit; same as 5 [a-z] Match any lowercase ASCII letter 6 [A-Z] Match any uppercase ASCII letter 7 [a-zA-Z0-9] Match any of the above 8 [^aeiou] Match anything other than a lowercase vowel 57 Computer Programming using Python: by Ravinder Sheoran 9 [^0-9] Match anything other than a digit Special Character Classes Sr.No. Example & Description 1. Match any character except newline 2 \d Match a digit: [0-9] 3 \D Match a nondigit: [^0-9] 4 \s Match a whitespace character: [ \t\r\n\f] 5 \S Match nonwhitespace: [^ \t\r\n\f] 6 \w Match a single word character: [A-Za-z0-9_] 7 \W Match a nonword character: [^A-Za-z0-9_] Repetition Cases Sr.No. Example & Description 58 Computer Programming using Python: by Ravinder Sheoran 1 ruby? Match "rub" or "ruby": the y is optional 2 ruby* Match "rub" plus 0 or more ys 3 ruby+ Match "rub" plus 1 or more ys 4 \d{3} Match exactly 3 digits 5 \d{3,} Match 3 or more digits 6 \d{3,5} Match 3, 4, or 5 digits Nongreedy repetition This matches the smallest number of repetitions − Sr.No. Example & Description 1 Greedy repetition: matches "perl>" 2 Nongreedy: matches "" in "perl>" Grouping with Parentheses 59 Computer Programming using Python: by Ravinder Sheoran Sr.No. Example & Description 1 \D\d+ No group: + repeats \d 2 (\D\d)+ Grouped: + repeats \D\d pair 3 ([Pp]ython(, )?)+ Match "Python", "Python, python, python", etc. Backreferences This matches a previously matched group again − Sr.No. Example & Description 1 ([Pp])ython&\1ails Match python&pails or Python&Pails 2 (['"])[^\1]*\1 Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches whatever the 2nd group matched, etc. Alternatives Sr.No. Example & Description 1 python|perl Match "python" or "perl" 2 rub(y|le)) 60 Computer Programming using Python: by Ravinder Sheoran Match "ruby" or "ruble" 3 Python(!+|\?) "Python" followed by one or more ! or one ? Anchors This needs to specify match position. Sr.No. Example & Description 1 ^Python Match "Python" at the start of a string or internal line 2 Python$ Match "Python" at the end of a string or line 3 \APython Match "Python" at the start of a string 4 Python\Z Match "Python" at the end of a string 5 \bPython\b Match "Python" at a word boundary 6 \brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone 7 Python(?=!) Match "Python", if followed by an exclamation point. 61 Computer Programming using Python: by Ravinder Sheoran 8 Python(?!!) Match "Python", if not followed by an exclamation point. Special Syntax with Parentheses Sr.No. Example & Description 1 R(?#comment) Matches "R". All the rest is a comment 2 R(?i)uby Case-insensitive while matching "uby" 3 R(?i:uby) Same as above 4 rub(?:y|le)) Group only without creating \1 backreference Exception Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging capabilities in them − Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions available in Python: Standard Exceptions. Assertions − This would be covered in Assertions in Pythontutorial. List of Standard Exceptions − Sr.No. Exception Name & Description 62 Computer Programming using Python: by Ravinder Sheoran 1 Exception Base class for all exceptions 2 StopIteration Raised when the next() method of an iterator does not point to any object. 3 SystemExit Raised by the sys.exit() function. 4 StandardError Base class for all built-in exceptions except StopIteration and SystemExit. 5 ArithmeticError Base class for all errors that occur for numeric calculation. 6 OverflowError Raised when a calculation exceeds maximum limit for a numeric type. 7 FloatingPointError Raised when a floating point calculation fails. 8 ZeroDivisionError Raised when division or modulo by zero takes place for all numeric types. 9 AssertionError Raised in case of failure of the Assert statement. 63 Computer Programming using Python: by Ravinder Sheoran 10 AttributeError Raised in case of failure of attribute reference or assignment. 11 EOFError Raised when there is no input from either the raw_input() or input() function and the end of file is reached. 12 ImportError Raised when an import statement fails. 13 KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c. 14 LookupError Base class for all lookup errors. 15 IndexError Raised when an index is not found in a sequence. 16 KeyError Raised when the specified key is not found in the dictionary. 17 NameError Raised when an identifier is not found in the local or global namespace. 18 UnboundLocalError Raised when trying to access a local variable in a function or method but no value has been assigned to it. 64 Computer Programming using Python: by Ravinder Sheoran 19 EnvironmentError Base class for all exceptions that occur outside the Python environment. 20 IOError Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 21 IOError Raised for operating system-related errors. 22 SyntaxError Raised when there is an error in Python syntax. 23 IndentationError Raised when indentation is not specified properly. 24 SystemError Raised when the interpreter finds an internal problem, but when this error is encountered the Python interpreter does not exit. 25 SystemExit Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes the interpreter to exit. 26 TypeError Raised when an operation or function is attempted that is invalid for the specified data type. 27 ValueError 65 Computer Programming using Python: by Ravinder Sheoran Raised when the built-in function for a data type has the valid type of arguments, but the arguments have invalid values specified. 28 RuntimeError Raised when a generated error does not fall into any category. 29 NotImplementedError Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. Assertions in Python An assertion is a sanity-check that you can turn on or turn off when you are done with your testing of the program. The easiest way to think of an assertion is to liken it to a raise-if statement (or to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes up false, an exception is raised. Assertions are carried out by the assert statement, the newest keyword to Python, introduced in version 1.5. Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output. The assert Statement When it encounters an assert statement, Python evaluates the accompanying expression, which is hopefully true. If the expression is false, Python raises an AssertionError exception. The syntax for assert is − assert Expression[, Arguments] If the assertion fails, Python uses ArgumentExpression as the argument for the AssertionError. AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, they will terminate the program and produce a traceback. Example 66 Computer Programming using Python: by Ravinder Sheoran Here is a function that converts a temperature from degrees Kelvin to degrees Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a negative temperature − #!/usr/bin/python def KelvinToFahrenheit(Temperature): assert (Temperature >= 0),"Colder than absolute zero!" return ((Temperature-273)*1.8)+32 print KelvinToFahrenheit(273) print int(KelvinToFahrenheit(505.78)) print KelvinToFahrenheit(-5) When the above code is executed, it produces the following result − 32.0 451 Traceback (most recent call last): File "test.py", line 9, in print KelvinToFahrenheit(-5) File "test.py", line 4, in KelvinToFahrenheit assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than absolute zero! What is Exception? An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits. Handling an exception If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. 67 Computer Programming using Python: by Ravinder Sheoran Syntax Here is simple syntax of try....except...else blocks − try: You do your operations here;...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block....................... else: If there is no exception then execute this block. Here are few important points about the above-mentioned syntax − A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else- block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection. Example This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all − #!/usr/bin/python try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" 68 Computer Programming using Python: by Ravinder Sheoran fh.close() This produces the following result − Written content in the file successfully Example This example tries to open a file where you do not have write permission, so it raises an exception − #!/usr/bin/python try: fh = open("testfile", "r") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" This produces the following result − Error: can't find file or read data The except Clause with No Exceptions You can also use the except statement with no exceptions defined as follows − try: You do your operations here;...................... except: If there is any exception, then execute this block....................... else: If there is no exception then execute this block. This kind of a try-except statement catches all the exceptions that occur. Using this kind of try-except statement is not considered a good programming practice though, because it catches all exceptions but does 69 Computer Programming using Python: by Ravinder Sheoran not make the programmer identify the root cause of the problem that may occur. The except Clause with Multiple Exceptions You can also use the same except statement to handle multiple exceptions as follows − try: You do your operations here;...................... except(Exception1[, Exception2[,...ExceptionN]]]): If there is any exception from the given exception list, then execute this block....................... else: If there is no exception then execute this block. The try-finally Clause You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this − try: You do your operations here;...................... Due to any exception, this may be skipped. finally: This would always be executed....................... You cannot use else clause as well along with a finally clause. Example 70 Computer Programming using Python: by Ravinder Sheoran #!/usr/bin/python try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print "Error: can\'t find file or read data" If you do not have permission to open the file in writing mode, then this will produce the following result − Error: can't find file or read data Same example can be written more cleanly as follows − #!/usr/bin/python try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print "Going to close the file" fh.close() except IOError: print "Error: can\'t find file or read data" When an exception is thrown in the try block, the execution immediately passes to the finally block. After all the statements in the finally block are executed, the exception is raised again and is handled in 71 Computer Programming using Python: by Ravinder Sheoran the exceptstatements if present in the next higher layer of the try- except statement. Argument of an Exception An exception can have an argument, which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows − try: You do your operations here;...................... except ExceptionType, Argument: You can print value of Argument here... If you write the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception. This variable receives the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location. Example Following is an example for a single exception − #!/usr/bin/python # Define a function here. def temp_convert(var): try: return int(var) 72 Computer Programming using Python: by Ravinder Sheoran except ValueError, Argument: print "The argument does not contain numbers\n", Argument # Call above function here. temp_convert("xyz"); This produces the following result − The argument does not contain numbers invalid literal for int() with base 10: 'xyz' Raising an Exceptions You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as follows. Syntax raise [Exception [, args [, traceback]]] Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None. The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback object used for the exception. Example An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class. Defining new exceptions is quite easy and can be done as follows − def functionName( level ): if level < 1: raise "Invalid level!", level # The code below to this would not be executed # if we raise the exception 73 Computer Programming using Python: by Ravinder Sheoran Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example, to capture above exception, we must write the except clause as follows − try: Business Logic here... except "Invalid level!": Exception handling here... else: Rest of the code here... User-Defined Exceptions Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions. Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught. In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror. class Networkerror(RuntimeError): def init (self, arg): self.args = arg So once you defined above class, you can raise the exception as follows − try: raise Networkerror("Bad hostname") except Networkerror,e: print e.args 74 Computer Programming using Python: by Ravinder Sheoran Python Data Types Data type defines the type of the variable, whether it is an integer variable, string variable, tuple, dictionary, list etc. In this guide, you will learn about the data types and their usage in Python. Python data types Python data types are divided in two categories, mutable data types and immutable data types. Immutable Data types in Python 1. Numeric 2. String 3. Tuple Mutable Data types in Python 1. List 2. Dictionary 3. Set 1. Numeric Data Type in Python Integer – In Python 3, there is no upper bound on the integer number which means we can have the value as large as our system memory allows. # Integer number num = 100 print(num) print("Data Type of variable num is", type(num)) Output: 75 Computer Programming using Python: by Ravinder Sheoran Long – Long data type is deprecated in Python 3 because there is no need for it, since the integer has no upper limit, there is no point in having a data type that allows larger upper limit than integers. Float – Values with decimal points are the float values, there is no need to specify the data type in Python. It is automatically inferred based on the value we are assigning to a variable. For example here fnum is a float data type. # float number fnum = 34.45 print(fnum) print("Data Type of variable fnum is", type(fnum)) Output: Complex Number – Numbers with real and imaginary parts are known as complex numbers. Unlike other programming language such as Java, Python is able to identify these complex numbers with the values. In the following example when we print the type of the variable cnum, it prints as complex number. # complex number cnum = 3 + 4j print(cnum) print("Data Type of variable cnum is", type(cnum)) Binary, Octal and Hexadecimal numbers In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the prefixes. 0b(zero + ‘b’) and 0B(zero + ‘B’) – Binary Number 0o(zero + ‘o’) and 0O(zero + ‘O’) – Octal Number 0x(zero + ‘x’) and 0X(zero + ‘X’) – Hexadecimal Number # integer equivalent of binary number 101 num = 0b101 print(num) 76 Computer Programming using Python: by Ravinder Sheoran # integer equivalent of Octal number 32 num2 = 0o32 print(num2) # integer equivalent of Hexadecimal number FF num3 = 0xFF print(num3) 2. Python Data Type – String String is a sequence of characters in Python. The data type of String in Python is called “str”. Strings in Python are either enclosed with single quotes or double quotes. In the following example we have demonstrated two strings one with the double quotes and other string s2 with the single quotes. To read more about strings, refer this article: Python Strings. # Python program to print strings and type s = "This is a String" s2 = 'This is also a String' # displaying string s and its type print(s) print(type(s)) # displaying string s2 and its type print(s2) print(type(s2)) 3. Python Data Type – Tuple Tuple is immutable data type in Python which means it cannot be changed. It is an ordered collection of elements enclosed in round brackets and separated by commas. To read more about tuple, refer this tutorial: Python tuple. # tuple of integers t1 = (1, 2, 3, 4, 5) # prints entire tuple print(t1) # tuple of strings t2 = ("hi", "hello", "bye") # loop through tuple elements for s in t2: 77 Computer Programming using Python: by Ravinder Sheoran print (s) # tuple of mixed type elements t3 = (2, "Lucy", 45, "Steve") ''' Print a specific element indexes start with zero ''' print(t3) 4. Python Data Type – List List is similar to tuple, it is also an ordered collection of elements, however list is a mutable data type which means it can be changed unlike tuple which is an immutable data type. A list is enclosed with square brackets and elements are separated by commas. To read more about Lists, refer this guide: Python Lists # list of integers lis1 = (1, 2, 3, 4, 5) # prints entire list print(lis1) # list of strings lis2 = ("Apple", "Orange", "Banana") # loop through tuple elements for x in lis2: print (x) # List of mixed type elements lis3 = (20, "Chaitanya", 15, "BeginnersBook") ''' Print a specific element in list indexes start with zero ''' print("Element at index 3 is:",lis3) 5. Python Data Type – Dictionary Dictionary is a collection of key and value pairs. A dictionary doesn’t allow duplicate keys but the values can be duplicate. It is an ordered, indexed and mutable collection of elements. To read more about it refer: Python dictionary. 78 Computer Programming using Python: by Ravinder Sheoran The keys in a dictionary doesn’t necessarily to be a single data type, as you can see in the following example that we have 1 integer key and two string keys. # Dictionary example dict = {1:"Chaitanya","lastname":"Singh", "age":31} # prints the value where key value is 1 print(dict) # prints the value where key value is "lastname" print(dict["lastname"]) # prints the value where key value is "age" print(dict["age"]) 6. Python Data Type – Set A set is an unordered and unindexed collection of items. This means when we print the elements of a set they will appear in the random order and we cannot access the elements of set based on indexes because it is unindexed. Elements of set are separated by commas and enclosed in curly braces. Lets take an example to understand the sets in Python. # Set Example myset = {"hi", 2, "bye", "Hello World"} # loop through set for a in myset: print(a) # checking whether 2 exists in myset print(2 in myset) # adding new element myset.add(99) print(myset) Python If Statement explained with examples BY CHAITANYA SINGH | FILED UNDER: PYTHON TUTORIAL 79 Computer Programming using Python: by Ravinder Sheoran If statements are control flow statements which helps us to run a particular code only when a certain condition is satisfied. For example, you want to print a message on the screen only when a condition is true then you can use if statement to accomplish this in programming. In this guide, we will learn how to use if statements in Python programming with the help of examples. There are other control flow statements available in Python such as if..else, if..elif..else, nested if etc. However in this guide, we will only cover the if statements, other control statements are covered in separate tutorials. Syntax of If statement in Python The syntax of if statement in Python is pretty simple. if condition: block_of_code If statement flow diagram Python – If statement Example flag = True if flag==True: print("Welcome") print("To") print("BeginnersBook.com") Output: Welcome To BeginnersBook.com 80 Computer Programming using Python: by Ravinder Sheoran In the above example we are checking the value of flag variable and if the value is True then we are executing few print statements. The important point to note here is that even if we do not compare the value of flag with the ‘True’ and simply put ‘flag’ in place of condition, the code would run just fine so the better way to write the above code would be: flag = True if flag: print("Welcome") print("To") print("BeginnersBook.com") By seeing this we can understand how if statement works. The output of the condition would either be true or false. If the outcome of condition is true then the statements inside body of ‘if’ executes, however if the outcome of condition is false then the statements inside ‘if’ are skipped. Lets take another example to understand this: flag = False if flag: print("You Guys") print("are") print("Awesome") The output of this code is none, it does not print anything because the outcome of condition is ‘false’. Python if example without boolean variables In the above examples, we have used the boolean variables in place of conditions. However we can use any variables in our conditions. For example: num = 100 if num < 200: print("num is less than 200") Output: num is less than 200 Python If else Statement Example In the last tutorial we learned how to use if statements in Python. In this guide, we will learn another control statement ‘if..else’. 81 Computer Programming using Python: by Ravinder Sheoran We use if statements when we need to execute a certain block of Python code when a particular condition is true. If..else statements are like extension of ‘if’ statements, with the help of if..else we can execute certain statements if condition is true and a different set of statements if condition is false. For example, you want to print ‘even number’ if the number is even and ‘odd number’ if the number is not even, we can accomplish this with the help of if..else statement. Python – Syntax of if..else statement if condition: block_of_code_1 else: block_of_code_2 block_of_code_1: This would execute if the given condition is true block_of_code_2: This would execute if the given condition is false If..else flow control If-else example in Python num = 22 if num % 2 == 0: print("Even Number") else: print("Odd Number") Output: Even Number 82 Computer Programming using Python: by Ravinder Sheoran Python If elif else statement example In the previous tutorials we have seen if statement and if..else statement. In this tutorial, we will learn if elif else statement in Python. The if..elif..else statement is used when we need to check multiple conditions. Syntax of if elif else statement in Python This way we are checking multiple conditions. if condition: block_of_code_1 elif condition_2: block_of_code_2 elif condition_3: block_of_code_3...... else: block_of_code_n Notes: 1. There can be multiple ‘elif’ blocks, however there is only ‘else’ block is allowed. 2. Out of all these blocks only one block_of_code gets executed. If the condition is true then the code inside ‘if’ gets executed, if condition is false then the next condition(associated with elif) is evaluated and so on. If none of the conditions is true then the code inside ‘else’ gets executed. Python – if..elif..else statement example In this example, we are checking multiple conditions using if..elif..else statement. num = 1122 if 9 < num < 99: print("Two digit number") elif 99 < num < 999: print("Three digit number") elif 999 < num < 9999: print("Four digit number") else: print("number is = 9999") 83 Computer Programming using Python: by Ravinder Sheoran Python Nested If else statement In the previous tutorials, we have covered the if statement, if..else statement and if..elif..else statement. In this tutorial, we will learn the nesting of these control statements. When there is an if statement (or if..else or if..elif..else) is present inside another if statement (or if..else or if..elif..else) then this is calling the nesting of control statements. Nested if..else statement example Here we have a if statement inside another if..else statement block. Nesting control statements makes us to check multiple conditions. num = -99 if num > 0: print("Positive Number") else: print("Negative Number") #nested if if -99>> class Snake:... pass... >>> snake = Snake() >>> print(snake) < main.Snake object at 0x7f315c573550> Attributes and Methods in class: A class by itself is of no use unless there is some functionality associated with it. Functionalities are defined by setting attributes, which act as containers for data and functions related to those attributes. Those functions are called methods. Attributes: You can define the following class with the name Snake. This class will have an attribute name. >>> class Snake:... name = "python" # set an attribute `name` of the class... 127 Computer Programming using Python: by Ravinder Sheoran You can assign the class to a variable. This is called object instantiation. You will then be able to access the attributes that are present inside the class using the dot. operator. For example, in the Snake example, you can access the attribute name of the class Snake. >>> # instantiate the class Snake and assign it to variable snake >>> snake = Snake() >>> # access the class attribute name inside the class Snake. >>> print(snake.name) python Methods Once there are attributes that “belong” to the class, you can define functions that will access the class attribute. These functions are called methods. When you define methods, you will need to always provide the first argument to the method with a self keyword. For example, you can define a class Snake, which has one attribute name and one method change_name. The method change name will take in an argument new_name along with the keyword self. >>> class Snake:... name = "python"...... def change_name(self, new_name): # note that the first argument is self... self.name = new_name # access the class attribute with the self keyword... Now, you can instantiate this class Snake with a variable snake and then change the name with the method change_name. >>> # instantiate the class >>> snake = Snake() >>> # print the current object name >>> print(snake.name) python >>> # change the name using the change_name method >>> snake.change_name("anaconda") >>> print(snake.name) anaconda Instance attributes in python and the init method 128 Computer Programming using Python: by Ravinder Sheoran You can also provide the values for the attributes at runtime. This is done by defining the attributes inside the init method. The following example illustrates this. class Snake: def init (self, name): self.name = name def change_name(self, new_name): self.name = new_name Now you can directly define separate attribute values for separate objects. For example, >>> # two variables are instantiated >>> python = Snake("python") >>> anaconda = Snake("anaconda") >>> # print the names of the two variables >>> print(python.name) python >>> print(anaconda.name) anaconda Python classes and object object-oriented programming II Classes are written to organize and structure code into meaningful blocks, which can then be used to implement the business logic. These implementations are used in such a way that more complex parts are abstracted away to provide for simpler interfaces which can then be used to build even simpler blocks. While doing this we will find that there are lots of times when we will need to establish relationships between the classes that we build. These relationships can then be established using either inheritance or composition. At this point it is best you take a look at our [Python Classes tutorial] to get in-depth knowledge on how classes are written in Python. Also, in case you are already doing object oriented programming in some other language, you may want to check out our notes on design patterns. In this tutorial you will get to know how to build relationships between classes using inheritance and composition and the syntax that is needed. Python inheritance What is Inheritance In inheritance an object is based on another object. When inheritance is implemented, the methods and attributes that were defined in the base class will also be present in the inherited class. This is 129 Computer Programming using Python: by Ravinder Sheoran generally done to abstract away similar code in multiple classes. The abstracted code will reside in the base class and the previous classes will now inherit from the base class. How to achieve Inheritance in Python Python allows the classes to inherit commonly used attributes and methods from other classes through inheritance. We can define a base class in the following manner: class DerivedClassName(BaseClassName): pass Let's look at an example of inheritance. In the following example, Rocket is the base class and MarsRover is the inherited class. class Rocket: def init (self, name, distance): self.name = name self.distance = distance def launch(self): return "%s has reached %s" % (self.name, self.distance) class MarsRover(Rocket): # inheriting from the base class def init (self, name, distance, maker): Rocket. init (self, name, distance) self.maker = maker def get_maker(self): return "%s Launched by %s" % (self.name, self.maker) if name == " main ": x = Rocket("simple rocket", "till stratosphere") y = MarsRover("mars_rover", "till Mars", "ISRO") print(x.launch()) print(y.launch()) print(y.get_maker()) The output of the code above is shown below: ➜ Documents python rockets.py simple rocket has reached till stratosphere mars_rover has reached till Mars mars_rover Launched by ISRO Python Composition: 130 Computer Programming using Python: by Ravinder Sheoran What is composition In composition, we do not inherit from the base class but establish relationships between classes through the use of instance variables that are references to other objects. Talking in terms of pseudocode you may say that class GenericClass: define some attributes and methods class ASpecificClass: Instance_variable_of_generic_class = GenericClass # use this instance somewhere in the class some_method(Instance_variable_of_generic_class) So you will instantiate the base class and then use the instance variable for any business logic. How to achieve composition in Python To achieve composition you can instantiate other objects in the class and then use those instances. For example in the below example we instantiate the Rocket class using self.rocket and then using self.rocket in the method get_maker. class MarsRoverComp(): def init (self, name, distance, maker): self.rocket = Rocket(name, distance) # instantiating the base self.maker = maker def get_maker(self): return "%s Launched by %s" % (self.rocket.name, self.maker) if name == " main ": z = MarsRover("mars_rover2", "till Mars", "ISRO") print(z.launch()) print(z.get_maker()) The output of the total code which has both inheritance and composition is shown below: ➜ Documents python rockets.py simple rocket has reached till stratosphere mars_rover has reached till Mars mars_rover Launched by ISRO mars_rover2 has reached till Mars mars_rover2 Launched by ISRO 131 Computer Programming using Python: by Ravinder Sheoran Errors and Exceptions in Python Errors are problems in the program that the program should not recover from. If at any point in the program an error occurs, then the program should exit gracefully. On the other hand, Exceptions are raised when an external event occurs which in some way changes the normal flow of the program. In this tutorial you will learn about common types of Errors and Exceptions in Python and common paradigms in handling them. Handling Exceptions with Try/Except/Finally Errors and Exceptions in Python are handled with the Try: Except: Finally construct. You put the unsafe code in the try: block. You put the fall-back code in the Except: block. The final code is kept in the Finally: block. For example, look at the code below. >>> try:... print("in the try block")... print(1/0)... except:... print("In the except block")... finally:... print("In the finally block")... in the try block In the except block In the finally block Raising exceptions for a predefined condition Exceptions can also be raised if you want the code to behave within specific parameters. For example, if you want to limit the user-input to only positive integers, raise an exception. # exc.py while True: try: user = int(input()) if user < 0: raise ValueError("please give positive number") else: print("user input: %s" % user) except ValueError as e: print(e) So the output of the above program is: 132 Computer Programming using Python: by Ravinder Sheoran ➜ python exc.py 4 user input: 4 3 user input: 3 2 user input: 2 1 user input: 1 -1 please give positive number 5 user input: 5 2 user input: 2 -5 please give positive number ^C Traceback (most recent call last): File "exc.py", line 3, in user = int(input()) KeyboardInterrupt Python Iterators, generators, and the for loop Iterators are containers for objects so that you can loop over the objects. In other words, you can run the "for" loop over the object. There are many iterators in the Python standard library. For example, list is an iterator and you can run a for loop over a list. >>> for lib in popular_python_libs:... print(lib)... requests scrapy pillow SQLAlchemy NumPy In this tutorial you will get to know: 1. How to create a custom iterator 2. How to create a generator 3. How to run for loops on iterators and generators Python Iterators and the Iterator protocol To create a Python iterator object, you will need to implement two methods in your iterator class. 133 Computer Programming using Python: by Ravinder Sheoran iter : This returns the iterator object itself and is used while using the "for" and "in" keywords. next : This returns the next value. This would return the StopIteration error once all the objects have been looped through. Let us create a cool emoticon generator and l iterators. # iterator_example.py """ This should give an iterator with a emoticon. """ import random class CoolEmoticonGenerator(object): """docstring for CoolEmoticonGenerator.""" strings = "!@#$^*_-=+?/,.:;~" grouped_strings = [("(", ")"), (""), ("[", "]"), ("{", "}")] def create_emoticon(self, grp): """actual method that creates the emoticon""" face_strings_list = [random.choice(self.strings) for _ in range(3)] face_strings = "".join(face_strings_list) emoticon = (grp, face_strings, grp) emoticon = "".join(emoticon) return emoticon def iter (self): """returns the self object to be accessed by the for loop""" return self def next (self): """returns the next emoticon indefinitely""" grp = random.choice(self.grouped_strings) return self.create_emoticon(grp) Now you can call the above class as an iterator. Which means you can run the next function on it. from iterator_example import CoolEmoticonGenerator g = CoolEmoticonGenerator() print([next(g) for _ in range(5)]) Running the program above gives us the following output. The exact output may be different from what you get but it will be similar. ➜ python3.5 iterator_example.py ['', '', '', '[~=#]', '{?^-}'] 134 Computer Programming using Python: by Ravinder Sheoran You can use the KeyboardInterrupt to stop the execution. Python Generators Python generator gives us an easier way to create python iterators. This is done by defining a function but instead of the return statement returning from the function, use the "yield" keyword. For example, see how you can get a simple vowel generator below. >>> def vowels():... yield "a"... yield "e"... yield "i"... yield "o"... yield "u"... >>> for i in vowels():... print(i)... a e i o u Now let's try and create the CoolEmoticonGenerator. def create_emoticon_generator(): while True: strings = "!@#$^*_-=+?/,.:;~" grouped_strings = [("(", ")"), (""), ("[", "]"), ("{", "}")] grp = random.choice(grouped_strings) face_strings_list = [random.choice(strings) for _ in range(3)] face_strings = "".join(face_strings_list) emoticon = (grp, face_strings, grp) emoticon = "".join(emoticon) yield emoticon Now, if you run the generator using the runner below from iterator_example import CoolEmoticonGenerator g = create_emoticon_generator() print([next(g) for _ in range(5)]) You should get the following output ➜ python3.5 iterator_example.py ['(+~?)', '', '($?/)', '[#=+]', '{*=.}'] 135 Computer Programming using Python: by Ravinder Sheoran Functions A function is a block of code that takes in some data and, either performs some kind of transformation and returns the transformed data, or performs some task on the data, or both. Functions are useful because they provide a high degree of modularity. Similar code can be easily grouped into functions and you can provide a name to the function that describes what the function is for. Functions are the simplest, and, sometimes the most useful, tool for writing modular code. In this tutorial you will get to know: How to create a function How to call a function How to create a function: In Python to create a function, you need to write it in the following manner. Please note that the body of the function is indented by 4 spaces. def name_of_the_function(arguments): ''' doctring of the function note that the function block is indented by 4 spaces ''' body of the function return the return value or expression You can look at the example below where a function returns the sum of two numbers. def add_two_numbers(num1, num2): '''returns the sum of num1 and num2''' result = num1 + num2 return result Here are all the parts of the function: Keyword def: This is the keyword used to say that a function will be defined now, and the next word that is there, is the function name. Function name: This is the name that is used to identify the function. The function name comes after the defkeyword. Function names have to be a single word. PEP8, which is a style guide for Python, recommends that in case multiple words are used, they should be in lowercase and they should be separated with an underscore. In the example above, add_two_numbers is the parameter name. 136 Computer Programming using Python: by Ravinder Sheoran Parameter list: Parameter list are place holders that define the parameters that go into the function. The parameters help to generalise the transformation/computation/task that is needed to be done. In Python, parameters are enclosed in parentheses. In the example above, the parameters are num1and num2. You can pass as many parameters as needed to a function. Function docstrings: These are optional constructs that provide a convenient way for associated documentation to the corresponding function. Docstrings are enclosed by triple quotes '''you will write the docstring here''' Function returns: Python functions returns a value. You can define what to return by the return keyword. In the example above, the function returns result. In case you do not define a return value, the function will return None. How to call a function Call a function with a return value To call a function means that you are telling the program to execute the function. If there is a return value defined, the function would return the value, else the function would return None. To call the function, you write the name of the function followed by parentheses. In case you need to pass parameters/arguments to the function, you write them inside the parentheses. For example, if you had a function that added two numbers def add_two_numbers(num1, num2): '''returns the sum of num1 and num2''' result = num1 + num2 return result You would call the function like this: add_two_numbers(1, 2) Note that arguments 1 and 2 have been passed. Hence, the return value will be 3. You can put any two numbers in place of 1 and 2, and it will return the corresponding sum of the two numbers. But calling a function and not doing anything with the result is meaningless, isn’t it? So you can now assign it to a variable which may be used later on. In the following example, can just printing it. >>> def add_two_numbers(num1, num2):... '''returns the sum of num1 and num2'''... result = num1 + num2... return result... >>> # call the function add_two_numbers with arguments 4 and 5 and assign it >>> # to a variable sum_of_4_and_5 >>> sum_of_4_and_5 = add_two_numbers(4, 5) >>> >>> # show the value stored in sum_of_4_and_5 137 Computer Programming using Python: by Ravinder Sheoran >>> print(sum_of_4_and_5) 9 Call a function that performs a task and has no return value In case the function is not meant to return anything and just performs some task, like committing something to a database or changing the text of some button in the user interface, then you do not need to assign the function to a variable. You can just call the function. For example, if you had a function that prints a string def printing_side_effects(): '''a function with side effects''' print('this is a function with side effects and performs some task') You can just call the function and it will get executed. >>> printing_side_effects() this is a function with side effects and performs some task How to call a function with arguments Note that in this case you pass parameters in the order in which they are supposed to be processed. For example, if you had a function that duplicates a string by the number of times, where both the string and the number needs to be provided by the function, such as: >>> def string_multiplier(string_arg, number):... '''takes the string_arg and multiplies it with one more than the number'''... return string_arg * (number + 1)... >>> # passing string_arg and number and in that order... >>> print(string_multiplier('a', 5))aaaaaa >>> # below code will return error as the arguments are not in order... >>> print(string_multiplier(5, 'a'))Traceback (most recent call last): File "", line 1, in File "", line 3, in string_multiplier TypeError: must be str, not int Variables 138 Computer Programming using Python: by Ravinder Sheoran A variable can be considered a storage container for data. Every variable will have a name. For example, we can have a variable named speed_of_light. A variable is a good way to store information while making it easy to refer to that information in our code later. A close analogy to variables may be a named box where you can store information. For instance, instead of working with the number 3.14, we can assign it to a variable pi. You may forget that you need to use the number 3.14 when you will need to make relevant calculations later. On the other hand, it will be easier for you to remember to call pi when writing the code. In this tutorial, you will learn how to name a variable and assign values. You will take a closer look at the methods that variables can support. Assignment In Python, assignment can be done by writing the variable name followed by the value separated by an equal =symbol. The skeleton or pseudo-code is “Variable name” = “ value or information ” In the following examples, you assign various numbers and strings to variables. >>> # assign the value 299792458 to the variable speed_of_light >>> speed_of_light = 299792458 >>> print(speed_of_light) 299792458 >>> # assign a decimal number 3.14 to the variable pi >>> pi = 3.14 >>> print(pi) 3.14 139 Computer Programming using Python: by Ravinder Sheoran >>> # assign a string >>> fav_lang = "python" >>> print(fav_lang) 'python' Valid and invalid ways of assigning variables Multiple words Assignment only works when the variable is a single word. >>> multiple word = "multiple word" File "", line 1 multiple word = "multiple word" ^ SyntaxError: invalid syntax So, if you want to have more than one word in the name, the convention is to use underscore "_" in the name. >>> multiple_word = "multiple word" # note the variable name has an underscore _ >>> print(multiple_word) multiple word Do not start with a number You cannot start a variable name with a number. The rest of the variable name can contain a number. For example, 1var is wrong. >>> 1var = 1 File "", line 1 1var = 1 ^ SyntaxError: invalid syntax But var1 is fine. >>> var1 = 1 >>> print(var1) 1 More points to remember while deciding a variable name 140 Computer Programming using Python: by Ravinder Sheoran You can only include a-z, A-Z, _, and 0-9 in your variable names. Other special characters are not permitted. For example, you cannot have hash key # in your variable names. >>> # a_var_containing_# will not work as it has # in the name >>> a_var_containing_# = 1 Traceback (most recent call last): File "", line 1, in NameError: name 'a_var_containing_' is not defined >>> # but if we remove the # then it works >>> a_var_containing_ = 1 >>> print(a_var_containing_) 1 Interestingly, you can have a variable name in your local language. >>> 零 = 0 # chinese >>> print(零) 0 >>> ශුන්ය = 0 # sinhala >>> print(ශුන්ය) 0 More on Assignments Python supports assigning all data structures to variables. For example, we can assign a list to a variable like you see in the following example, where we assign the list of names, denoted by [...], to the variable fav_writers. >>> # assigning list >>> fav_writers = ["Mark Twain", "Fyodor Dostoyevsky"] >>> print(fav_writers) ['Mark Twain', 'Fyodor Dostoyevsky'] Here is another example where you can assign dicts, shown by {...}, to a variable birthdays. >>> # assign dicts... >>> birthdays = {"mom": "9Jan", "daughter": "24Dec"} >>> print(birthdays) {'mom': '9Jan', 'daughter': '24Dec'} 141 Computer Programming using Python: by Ravinder Sheoran Data structures such as lists and dicts will be discussed in later tutorials. You can also assign functions and classes to variables. You will know more about functions and classes in later tutorials. >>> # assigning functions... >>> import functools >>> memoize = functools.lru_cache >>> print(memoize) >>> # class assignment... >>> class MyClass:... pass... >>> give_me_more = MyClass() >>> print(give_me_more) < main.MyClass object at 0x7f512e65bfd0> Working with variables Variables will support any method the underlying type supports. For example, if an integer value is stored in a variable, then the variable will support integer functions such as addition. In the following example, you assign the number 2 to the variable var and then add 3 to var. This will print 5, the result of 3 being added to the value stored in var which is 2. >>> var = 2 >>> print(var + 3) 5 You can make a change in a variable and assign it to the same variable. This is done generally when some kind of data type change is done. For example, you can take a number as input. This will take in the digit as a string. You can then take the string number and convert it to int and assign it to the same number. >>> number = input() 2 >>> type(number) >>> number = int(number) >>> type(number) 142 Computer Programming using Python: by Ravinder Sheoran We will use a function range(3) which returns three values. >>> print(range(3)) [0, 1, 2] Something that returns three values can be unpacked to three variables. This is like saying take whatever is in range(3) and instead of assigning it to a single variable, break it up and assign individual values to the three variables. This is done using a comma between the variables. >>> id1, id2, id3 = range(3) >>> print(id1) 0 >>> print(id2) 1 >>> print(id3) 2 Python String: Strings are sequences of characters. Your name can be considered a string. Or, say you live in Zambia, then your country name is "Zambia", which is a string. In this tutorial you will see how strings are treated in Python, the different ways in which strings are represented in Python, and the ways in which you can use strings in your code. How to create a string and assign it to a variable To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. You can look into how variables work in Python in the Python variables tutorial. For example, you can assign a character ‘a’ to a variable single_quote_character. Note that the string is a single character and it is “enclosed” by single quotes. >>> single_quote_character = 'a' >>> print(single_quote_character) a >>> print(type(single_quote_character)) # check the type of the variable. Similarly, you can assign a single character to a variable double_quote_character. Note that the string is a single character but it is “enclosed” by double quotes. 143 Computer Programming using Python: by Ravinder Sheoran >>> double_quote_character = "b" >>> print(double_quote_character) b >>> print(type(double_quote_character)) Also check out if you can assign a sequence of characters or multiple characters to a variable. You can assign both single quote sequences and double quote sequences. >>> double_quote_multiple_characters = "aeiou" >>> single_quote_multiple_characters = 'aeiou' >>> print(type(double_quote_multiple_characters), type(single_quote_multiple_characters)) Interestingly if you check the equivalence of one to the other using the keyword is, it returns True. >>> print(double_quote_multiple_characters is double_quote_multiple_characters) True Tak