python Raghukumar D S
Python is • Low-level versus high-level • General versus targeted to an application domain • Interpreted versus compiled • A Python program, sometimes called a script, is a sequence of definitions and commands. These definitions are evaluated and the commands are executed by the Python interpreter in something called the shell. • A command, often called a statement, instructs the interpreter to do something. For example, the statement print ‘im learning python!’
• The sequence of commands print ‘im learning python!’ print ‘from today!' print ‘im learning python!,’ , ‘from today!’ causes the interpreter to produce the output im learning python! from today! im learning python!,from today!
Objects, Expressions, and Numerical Types • Objects are the core things that Python programs manipulate. Every object has a type that defines the kinds of things that programs can do with objects of that type. • Scalar(without internal structure) and non-scalar(with internal structure ) are the types • Scalars : int, float, bool, None(is a type with a single value). • Non-scalars : String
• Expressions : Objects and operators can be combined to form expressions, each of which evaluates to an object of some type. We will refer to this as the value of the expression. • i+j is the sum of i and j • i–j is i minus j. • i*j is the product of i and j. • i//j is integer division. • i/j is i divided by j. • i%j is the remainder when the int i is divided by the int j. • i**j is i raised to the power j. • The comparison operators are == (equal), != (not equal), > (greater),>= (at least), <, (less) and <= (at most). • The operators on type bool are: a and b is True if both a and b are True, and False otherwise. a or b is True if at least one of a or b is True, and False otherwise. not a is True if a is False, and False if a is True.
Variables and Assignment • Variables provide a way to associate names with objects. Consider the code pi = 3 radius = 11 area = pi * (radius**2) radius = 14 • In Python, a variable is just a name, nothing more. An assignment statement associates the name to the left of the = symbol with the object denoted by the expression to the right of the =. Remember this too. An object can have one, more than one, or no name associated with it.
IDLE • IDLE provides • a text editor with syntax highlighting, auto completion, and smart indentation, • a shell with syntax highlighting, and • an integrated debugger, which you should ignore for now.
Branching Programs • Programs are 2 types:Straightline programs and Branching programs • Branching programs are more interesting. The simplest branching statement is a conditional. As depicted in Figure below, a conditional statement has three parts: • a test, i.e., an expression that evaluates to either True or False; • a block of code that is executed if the test evaluates to True; and • an optional block of code that is executed if the test evaluates to False.
• In Python, a conditional statement has the form if Boolean expression: block of code else: block of code Eg: if x%2 == 0: print 'Even' else: print 'Odd' print 'Done with conditional‘ (*Indentation)
if x%2 == 0: if x%3 == 0: print 'Divisible by 2 and 3' else: print 'Divisible by 2 and not by 3' elif x%3 == 0: print 'Divisible by 3 and not by 2‘ • The elif in the above code stands for “else if.”
Strings and Input • Objects of type str are used to represent strings of characters. Literals of type str can be written using either single or double quotes, e.g., 'abc' or "abc". The literal '123' denotes a string of characters, not the number one hundred twenty-three. >>> 'a' >>> 3*4 >>> 3*'a' >>> 3+4 >>> 'a'+'a‘ • That type checking exists is a good thing • The length of a string can be found using the len function. For example, the value of len('abc') is 3. • Indexing can be used to extract individual characters from a string. Eg : 'abc'[0] is ‘a’ , abc'[-1] is 'c'. • Slicing is used to extract substrings of arbitrary length. If s is a string, the expression s[start:end]
Input • Python has two functions that can be used to get input directly from a user, input and raw_input. >>> name = raw_input('Enter your name: ') (* Treated as string) Enter your name: George Washington >>> name = input('Enter your name: ') Enter your name: George Washington • Type conversions (also called type casts) are used often in Python code. We use the name of a type to convert values to that type. So, for example, the value of int('3')*4 is 12. When a float is converted to an int, the number is truncated (not rounded), e.g., the value of int(3.9) is the int 3.
Iteration • generic iteration (also called looping) mechanism is depicted in Figure. Like a conditional statement it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement. for and while loop
• Consider the following example: # Square an integer, the hard way x = 3 ans = 0 itersLeft = x while (itersLeft != 0): ans = ans + x itersLeft = itersLeft - 1 print str(x) + '*' + str(x) + ' = ' + str(ans)
FUNCTIONS, SCOPING, AND ABSTRACTION • So far, we have introduced numbers, assignments, input/output, comparisons, and looping constructs. How powerful is this subset of Python? In a theoretical sense, it is as powerful as you will ever need. Such languages are called Turing complete. This means that if a problem can be solved via computation, it can be solved using only those statements you have already seen
Functions and Scoping • We’ve already used a number of built-in functions, e.g., max and abs The ability for programmers to define and then use their own functions, as if they were built-in, is a qualitative leap forward in convenience. • In Python each function definition is of the form def name of function (list of formal parameters): body of function • For example, we could define the function max by the code def max(x, y): if x > y: return x else: return y
• formal parameters • actual parameters • Keyword parameter
Scoping • Let’s look at another small example, def f(x): #name x used as formal parameter y = 1 x = x + y print 'x =', x return x x = 3 y = 2 z = f(x) #value of x used as actual parameter print 'z =', z print 'x =', x print 'y =', y • It is important to note that though the actual and formal parameters have the same name, they are not the same variable. Each function defines a new name space, also called a scope. When run, this code prints, x = 4 z = 4 x = 3 y = 2
• Here’s one way to think about this: • At top level, i.e., the level of the shell, a symbol table keeps track of all names defined at that level and their current bindings. • When a function is called, a new symbol table (sometimes called a stack frame) is created. This table keeps track of all names defined within the function (including the formal parameters) and their current bindings. If a function is called from within the function body, yet another stack frame is created. • When the function completes, its stack frame goes away.
Recursion • You may have heard of recursion, and in all likelihood think of it as a rather subtle programming technique. but it’s not so subtle, and it is more than a programming technique. • In general, a recursive definition is made up of two parts. There is at least one base case that directly specifies the result for a special case, and there is at least one recursive (inductive) case that defines the answer in terms of the answer to the question on some other input • 1! = 1 • (n + 1)! = (n + 1) * n! • The first equation defines the base case. The second equation defines factorial for all natural numbers, except the base case, in terms of the factorial of the previous number.
Iteration v/s Recursion def factI(n): """Assumes that n is an int > 0 Returns n!""" result = 1 while n > 1: result = result * n n -= 1 return result def factR(n): """Assumes that n is an int > 0 Returns n!""" if n == 1: return n else: return n*factR(n - 1)
Modules • Python modules allow us to easily construct a program from code in multiple files • A module is a .py file containing Python definitions and statements. We could create, for example, a file circle.py containing pi = 3.14159 def area(radius): return pi*(radius**2) def circumference(radius): return 2*pi*radius • A program gets access to a module through an import statement. So, for example, the code #Calling circle Module import circle print circle.pi print circle.area(3) print circle.circumference(3)
Files • Every computer system uses files to save things from one computation to the next. Python provides many facilities for creating and accessing files. Here we illustrate some of the basic ones. • Each operating system (e.g., Windows and MAC OS) comes with its own file system for creating and accessing files. Python achieves operating-system independence by accessing files through something called a file handle. • The code nameHandle = open('kids', 'w')
Consder a example nameHandle = open('kids', 'w') for i in range(2): name = raw_input('Enter name: ') nameHandle.write(name + 'n') nameHandle.close() * Here instruct to take two times input (2 names) “” it is escape sequence
• Some of the common operations on files are • open(fn, 'w') Creates a file for writing and returns a file handle. • open(fn, 'r') Opens an existing file for reading and returns a file handle. • open(fn, 'a') Opens an existing file for appending and returns a file handle. • fh.read() returns a string containing the contents of the file associated with the file handle fh. • fh.readline() returns the next line in the file associated with the filehandle fh. • fh.readlines() returns a list each element of which is one line of the file associated with the file handle fh. • fh.write(s) write the string s to the end of the file associated with the file handle fh. • fh.writeLines(S) S is a sequence of strings. Writes each element of S to the file associated with the file handle fh. • fh.close() closes the file associated with the file handle fh.
TESTING AND DEBUGGING • Testing is the process of running a program to try and ascertain whether or not it works as intended. Debugging is the process of trying to fix a program that you already know does not work as intended. • Testing • The most important thing to say about testing is that its purpose is to show that bugs exist, not to show that a program is bug-free. Eg : def isBigger(x, y): """Assumes x and y are intsReturns True if x is less than y and False otherwise.""“ • The best we can do is to run it on pairs of integers that have a reasonable probability of producing the wrong answer if there is a bug in the program.
• The key to testing is finding a collection of inputs, called a test suite. • A partition of a set divides that set into a collection of subsets to find bugs • x positive, y positive • x negative, y negative • x positive, y negative • x negative, y positive • x = 0, y = 0 • x = 0, y ≠ 0 • x ≠ 0, y = 0 • Heuristics based on exploring paths through the code fall into a class called glass-box testing. • Heuristics based on exploring paths through the specification fall into a class called black-box testing.
Black-Box Testing • In principle, black-box tests are constructed without looking at the code to be tested. Black-box testing allows testers and implementers to be drawn from separate populations. When those of us who teach programming courses generate test cases for the problem sets we assign students, we are developing black-box test suites. Glass-Box Testing Despite the limitations of glass-box testing, there are a few rules of thumb that are usually worth following: • Exercise both branches of all if statements. • Make sure that each except clause (Exception Handling) is executed.
• For each for loop, have test cases in which • The loop is not entered (e.g., if the loop is iterating over the elements of a list, make sure that it is tested on the empty list), • The body of the loop is executed exactly once, and • The body of the loop is executed more than once. • For each while loop, • Look at the same kinds of cases as when dealing with for loops, and • Include test cases corresponding to all possible ways of exiting • the loop. For example, for a loop starting with while len(L) > 0 and not L[i] == e find cases where the loop exits because len(L) is greater than zero and cases where it exits because L[i] == e.
• For recursive functions, include test cases that cause the function to return with no recursive calls, exactly one recursive call, and more than one recursive call. • Conducting Test has two phases they are 1.Unit Testing , 2.Integration testing Debugging • how the process of fixing flaws in software came to be known as debugging. • Runtime bugs can be categorized along two dimensions: 1. Overt → covert 2. Persistent → intermittent
• 1. Overt → covert: An overt bug has an obvious manifestation, e.g., the program crashes or takes far longer (maybe forever) to run than it should. A covert bug has no obvious manifestation. The program may run to conclusion with no problem—other than providing an incorrect answer. Many bugs fall between the two extremes, and whether or not the bug is overt can depend upon how carefully one examines the behavior of the program. • 2. Persistent → intermittent: A persistent bug occurs every time the program is run with the same inputs. An intermittent bug occurs only some of the time, even when the program is run on the same inputs and seemingly under the same conditions.
EXCEPTIONS AND ASSERTIONS • An “exception” is usually defined as “something that does not conform to the norm,” and is therefore somewhat rare. Open a Python shell and enter, test = [1,2,3] test[3] and the interpreter will respond with something like Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> test[3] IndexError: list index out of range
Handling Exceptions • When an exception is raised, the program terminates (crashes might be a more appropriate word in this case), and we go back to our code and attempt to figure out what went wrong. When an exception is raised that causes the program to terminate, we say that an unhandled exception has been raised. • Consider the code successFailureRatio = numSuccesses/float(numFailures) print 'The success/failure ratio is', successFailureRatio print 'Now here‘ • The attempt to divide by zero will cause the Python runtime • system to raise a ZeroDivisionError exception
It would have been better to have written something along the lines of try: successFailureRatio = numSuccesses/float(numFailures) print 'The success/failure ratio is', successFailureRatio except ZeroDivisionError: print 'No failures so the success/failure ratio is undefined.' print 'Now here'
Assertions • The Python assert statement provides programmers with a simple way to confirm that the state of the computation is as expected. An assert statement can take one of two forms: assert Boolean expression or assert Boolean expression, argument • When an assert statement is encountered, the Boolean expression is evaluated.
STRUCTURED TYPES, MUTABILITY, AND HIGHERORDER FUNCTIONS • we introduce three structured types. One, tuple, is a rather simple generalization of str. The other two, list and dict, are more interesting—in part because they are mutable Tuples • Like strings, tuples are ordered sequences of elements. The difference is that the elements of a tuple need not be characters. The individual elements can be of any type, and need not be of the same type as each other.
t1 = () t2 = (1, 'two', 3) print t1 print t2 Unsurprisingly, the print statements produce the output () (1, 'two', 3) Lists and Mutability • Like a tuple, a list is an ordered sequence of values, where each value is identified by an index. The syntax for expressing literals of type list is similar to that used for tuples; the difference is that we use square brackets rather than parentheses. The empty list is written as []
L = ['I did it all', 4, 'love'] for i in range(len(L)): print L[i] • produces the output, I did it all 4 love L1 = [1,2,3] L2 = [4,5,6] L3 = L1 + L2 print 'L3 =', L3 L1.extend(L2) print 'L1 =', L1 L1.append(L2) print 'L1 =', L1 will print L3 = [1, 2, 3, 4, 5, 6] L1 = [1, 2, 3, 4, 5, 6] L1 = [1, 2, 3, 4, 5, 6, [4, 5, 6]]
• L.append(e) adds the object e to the end of L. • L.count(e) returns the number of times that e occurs in L. • L.insert(i, e) inserts the object e into L at index i. • L.extend(L1) adds the items in list L1 to the end of L. • L.remove(e) deletes the first occurrence of e from L. • L.index(e) returns the index of the first occurrence of e in L. It raises an exception ,if e is not in L. • L.pop(i) removes and returns the item at index i in L. If i is omitted, it defaults to -1, to remove and return the last element of L. • L.sort() sorts the elements of L in ascending order. • L.reverse() reverses the order of the elements in L.
Functions as Objects • In Python, functions are first-class objects. That means that they can be treated like objects of any other type, e.g., int or list. They have types, e.g., the expression type(fact) has the value <type 'function'>; they can appear in expressions, e.g., as the right-hand side of an assignment statement or as an argument to a function; they can be elements of lists; etc applyToEach(L, factR) print 'L =', L print 'Apply Fibonnaci to each element of', L applyToEach(L, fib) print 'L =', L
Strings, Tuples, and Lists • We have looked at three different sequence types: str, tuple, and list. They are similar in that objects of all of these types can be operated upon as described in below • seq[i] returns the ith element in the sequence. • len(seq) returns the length of the sequence. • seq1 + seq2 returns the concatenation of the two sequences. • n * seq returns a sequence that repeats seq n times. • seq[start:end] returns a slice of the sequence. • e in seq is True if e is contained in the sequence and False otherwise. • e not in seq is True if e is not in the sequence and False otherwise. • for e in seq iterates over the elements of the sequence.
• Some of their other similarities and differences are summarized
Strings Functions • s.count(s1) counts how many times the string s1 occurs in s. • s.find(s1) returns the index of the first occurrence of the substring s1 in s, and -1 if s1 is not in s. • s.rfind(s1) same as find, but starts from the end of s (the “r” in rfind stands for reverse). • s.index(s1) same as find, but raises an exception (see Chapter 7) if s1 is not in s. • s.rindex(s1) same as index, but starts from the end of s. • s.lower() converts all uppercase letters in s to lowercase. • s.replace(old, new) replaces all occurrences of the string old in s with the string new. • s.rstrip() removes trailing white space from s. • s.split(d) Splits s using d as a delimiter. Returns a list of substrings of s. For example, the value of 'David Guttag plays basketball'.split(' ') is ['David', 'Guttag', 'plays', 'basketball']. If d is omitted, the substrings are separated by arbitrary strings of whitespace characters (space, tab, newline, return, and formfeed).
Dictionaries • Objects of type dict (short for dictionary) are like lists except that “indices” need not be integers—they can be values of any immutable type. Since they are not ordered, we call them keys rather than indices. Think of a dictionary as a set of key/value pairs. Literals of type dict are enclosed in curly braces, and each element is written as a key followed by a colon followed by a value. For example, the code, monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'} print 'The third month is ' + monthNumbers[3] dist = monthNumbers['Apr'] - monthNumbers['Jan'] print 'Apr and Jan are', dist, 'months apart' will print The third month is Mar Apr and Jan are 3 months apart

An Introduction : Python

  • 1.
  • 2.
    Python is • Low-levelversus high-level • General versus targeted to an application domain • Interpreted versus compiled • A Python program, sometimes called a script, is a sequence of definitions and commands. These definitions are evaluated and the commands are executed by the Python interpreter in something called the shell. • A command, often called a statement, instructs the interpreter to do something. For example, the statement print ‘im learning python!’
  • 3.
    • The sequenceof commands print ‘im learning python!’ print ‘from today!' print ‘im learning python!,’ , ‘from today!’ causes the interpreter to produce the output im learning python! from today! im learning python!,from today!
  • 4.
    Objects, Expressions, andNumerical Types • Objects are the core things that Python programs manipulate. Every object has a type that defines the kinds of things that programs can do with objects of that type. • Scalar(without internal structure) and non-scalar(with internal structure ) are the types • Scalars : int, float, bool, None(is a type with a single value). • Non-scalars : String
  • 5.
    • Expressions :Objects and operators can be combined to form expressions, each of which evaluates to an object of some type. We will refer to this as the value of the expression. • i+j is the sum of i and j • i–j is i minus j. • i*j is the product of i and j. • i//j is integer division. • i/j is i divided by j. • i%j is the remainder when the int i is divided by the int j. • i**j is i raised to the power j. • The comparison operators are == (equal), != (not equal), > (greater),>= (at least), <, (less) and <= (at most). • The operators on type bool are: a and b is True if both a and b are True, and False otherwise. a or b is True if at least one of a or b is True, and False otherwise. not a is True if a is False, and False if a is True.
  • 6.
    Variables and Assignment •Variables provide a way to associate names with objects. Consider the code pi = 3 radius = 11 area = pi * (radius**2) radius = 14 • In Python, a variable is just a name, nothing more. An assignment statement associates the name to the left of the = symbol with the object denoted by the expression to the right of the =. Remember this too. An object can have one, more than one, or no name associated with it.
  • 7.
    IDLE • IDLE provides •a text editor with syntax highlighting, auto completion, and smart indentation, • a shell with syntax highlighting, and • an integrated debugger, which you should ignore for now.
  • 8.
    Branching Programs • Programsare 2 types:Straightline programs and Branching programs • Branching programs are more interesting. The simplest branching statement is a conditional. As depicted in Figure below, a conditional statement has three parts: • a test, i.e., an expression that evaluates to either True or False; • a block of code that is executed if the test evaluates to True; and • an optional block of code that is executed if the test evaluates to False.
  • 9.
    • In Python,a conditional statement has the form if Boolean expression: block of code else: block of code Eg: if x%2 == 0: print 'Even' else: print 'Odd' print 'Done with conditional‘ (*Indentation)
  • 10.
    if x%2 ==0: if x%3 == 0: print 'Divisible by 2 and 3' else: print 'Divisible by 2 and not by 3' elif x%3 == 0: print 'Divisible by 3 and not by 2‘ • The elif in the above code stands for “else if.”
  • 11.
    Strings and Input •Objects of type str are used to represent strings of characters. Literals of type str can be written using either single or double quotes, e.g., 'abc' or "abc". The literal '123' denotes a string of characters, not the number one hundred twenty-three. >>> 'a' >>> 3*4 >>> 3*'a' >>> 3+4 >>> 'a'+'a‘ • That type checking exists is a good thing • The length of a string can be found using the len function. For example, the value of len('abc') is 3. • Indexing can be used to extract individual characters from a string. Eg : 'abc'[0] is ‘a’ , abc'[-1] is 'c'. • Slicing is used to extract substrings of arbitrary length. If s is a string, the expression s[start:end]
  • 12.
    Input • Python hastwo functions that can be used to get input directly from a user, input and raw_input. >>> name = raw_input('Enter your name: ') (* Treated as string) Enter your name: George Washington >>> name = input('Enter your name: ') Enter your name: George Washington • Type conversions (also called type casts) are used often in Python code. We use the name of a type to convert values to that type. So, for example, the value of int('3')*4 is 12. When a float is converted to an int, the number is truncated (not rounded), e.g., the value of int(3.9) is the int 3.
  • 13.
    Iteration • generic iteration(also called looping) mechanism is depicted in Figure. Like a conditional statement it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement. for and while loop
  • 14.
    • Consider thefollowing example: # Square an integer, the hard way x = 3 ans = 0 itersLeft = x while (itersLeft != 0): ans = ans + x itersLeft = itersLeft - 1 print str(x) + '*' + str(x) + ' = ' + str(ans)
  • 15.
    FUNCTIONS, SCOPING, ANDABSTRACTION • So far, we have introduced numbers, assignments, input/output, comparisons, and looping constructs. How powerful is this subset of Python? In a theoretical sense, it is as powerful as you will ever need. Such languages are called Turing complete. This means that if a problem can be solved via computation, it can be solved using only those statements you have already seen
  • 16.
    Functions and Scoping •We’ve already used a number of built-in functions, e.g., max and abs The ability for programmers to define and then use their own functions, as if they were built-in, is a qualitative leap forward in convenience. • In Python each function definition is of the form def name of function (list of formal parameters): body of function • For example, we could define the function max by the code def max(x, y): if x > y: return x else: return y
  • 17.
    • formal parameters •actual parameters • Keyword parameter
  • 18.
    Scoping • Let’s lookat another small example, def f(x): #name x used as formal parameter y = 1 x = x + y print 'x =', x return x x = 3 y = 2 z = f(x) #value of x used as actual parameter print 'z =', z print 'x =', x print 'y =', y • It is important to note that though the actual and formal parameters have the same name, they are not the same variable. Each function defines a new name space, also called a scope. When run, this code prints, x = 4 z = 4 x = 3 y = 2
  • 19.
    • Here’s oneway to think about this: • At top level, i.e., the level of the shell, a symbol table keeps track of all names defined at that level and their current bindings. • When a function is called, a new symbol table (sometimes called a stack frame) is created. This table keeps track of all names defined within the function (including the formal parameters) and their current bindings. If a function is called from within the function body, yet another stack frame is created. • When the function completes, its stack frame goes away.
  • 20.
    Recursion • You mayhave heard of recursion, and in all likelihood think of it as a rather subtle programming technique. but it’s not so subtle, and it is more than a programming technique. • In general, a recursive definition is made up of two parts. There is at least one base case that directly specifies the result for a special case, and there is at least one recursive (inductive) case that defines the answer in terms of the answer to the question on some other input • 1! = 1 • (n + 1)! = (n + 1) * n! • The first equation defines the base case. The second equation defines factorial for all natural numbers, except the base case, in terms of the factorial of the previous number.
  • 21.
    Iteration v/s Recursion deffactI(n): """Assumes that n is an int > 0 Returns n!""" result = 1 while n > 1: result = result * n n -= 1 return result def factR(n): """Assumes that n is an int > 0 Returns n!""" if n == 1: return n else: return n*factR(n - 1)
  • 22.
    Modules • Python modulesallow us to easily construct a program from code in multiple files • A module is a .py file containing Python definitions and statements. We could create, for example, a file circle.py containing pi = 3.14159 def area(radius): return pi*(radius**2) def circumference(radius): return 2*pi*radius • A program gets access to a module through an import statement. So, for example, the code #Calling circle Module import circle print circle.pi print circle.area(3) print circle.circumference(3)
  • 23.
    Files • Every computersystem uses files to save things from one computation to the next. Python provides many facilities for creating and accessing files. Here we illustrate some of the basic ones. • Each operating system (e.g., Windows and MAC OS) comes with its own file system for creating and accessing files. Python achieves operating-system independence by accessing files through something called a file handle. • The code nameHandle = open('kids', 'w')
  • 24.
    Consder a example nameHandle= open('kids', 'w') for i in range(2): name = raw_input('Enter name: ') nameHandle.write(name + 'n') nameHandle.close() * Here instruct to take two times input (2 names) “” it is escape sequence
  • 25.
    • Some ofthe common operations on files are • open(fn, 'w') Creates a file for writing and returns a file handle. • open(fn, 'r') Opens an existing file for reading and returns a file handle. • open(fn, 'a') Opens an existing file for appending and returns a file handle. • fh.read() returns a string containing the contents of the file associated with the file handle fh. • fh.readline() returns the next line in the file associated with the filehandle fh. • fh.readlines() returns a list each element of which is one line of the file associated with the file handle fh. • fh.write(s) write the string s to the end of the file associated with the file handle fh. • fh.writeLines(S) S is a sequence of strings. Writes each element of S to the file associated with the file handle fh. • fh.close() closes the file associated with the file handle fh.
  • 26.
    TESTING AND DEBUGGING •Testing is the process of running a program to try and ascertain whether or not it works as intended. Debugging is the process of trying to fix a program that you already know does not work as intended. • Testing • The most important thing to say about testing is that its purpose is to show that bugs exist, not to show that a program is bug-free. Eg : def isBigger(x, y): """Assumes x and y are intsReturns True if x is less than y and False otherwise.""“ • The best we can do is to run it on pairs of integers that have a reasonable probability of producing the wrong answer if there is a bug in the program.
  • 27.
    • The keyto testing is finding a collection of inputs, called a test suite. • A partition of a set divides that set into a collection of subsets to find bugs • x positive, y positive • x negative, y negative • x positive, y negative • x negative, y positive • x = 0, y = 0 • x = 0, y ≠ 0 • x ≠ 0, y = 0 • Heuristics based on exploring paths through the code fall into a class called glass-box testing. • Heuristics based on exploring paths through the specification fall into a class called black-box testing.
  • 28.
    Black-Box Testing • Inprinciple, black-box tests are constructed without looking at the code to be tested. Black-box testing allows testers and implementers to be drawn from separate populations. When those of us who teach programming courses generate test cases for the problem sets we assign students, we are developing black-box test suites. Glass-Box Testing Despite the limitations of glass-box testing, there are a few rules of thumb that are usually worth following: • Exercise both branches of all if statements. • Make sure that each except clause (Exception Handling) is executed.
  • 29.
    • For eachfor loop, have test cases in which • The loop is not entered (e.g., if the loop is iterating over the elements of a list, make sure that it is tested on the empty list), • The body of the loop is executed exactly once, and • The body of the loop is executed more than once. • For each while loop, • Look at the same kinds of cases as when dealing with for loops, and • Include test cases corresponding to all possible ways of exiting • the loop. For example, for a loop starting with while len(L) > 0 and not L[i] == e find cases where the loop exits because len(L) is greater than zero and cases where it exits because L[i] == e.
  • 30.
    • For recursivefunctions, include test cases that cause the function to return with no recursive calls, exactly one recursive call, and more than one recursive call. • Conducting Test has two phases they are 1.Unit Testing , 2.Integration testing Debugging • how the process of fixing flaws in software came to be known as debugging. • Runtime bugs can be categorized along two dimensions: 1. Overt → covert 2. Persistent → intermittent
  • 31.
    • 1. Overt→ covert: An overt bug has an obvious manifestation, e.g., the program crashes or takes far longer (maybe forever) to run than it should. A covert bug has no obvious manifestation. The program may run to conclusion with no problem—other than providing an incorrect answer. Many bugs fall between the two extremes, and whether or not the bug is overt can depend upon how carefully one examines the behavior of the program. • 2. Persistent → intermittent: A persistent bug occurs every time the program is run with the same inputs. An intermittent bug occurs only some of the time, even when the program is run on the same inputs and seemingly under the same conditions.
  • 32.
    EXCEPTIONS AND ASSERTIONS •An “exception” is usually defined as “something that does not conform to the norm,” and is therefore somewhat rare. Open a Python shell and enter, test = [1,2,3] test[3] and the interpreter will respond with something like Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> test[3] IndexError: list index out of range
  • 33.
    Handling Exceptions • Whenan exception is raised, the program terminates (crashes might be a more appropriate word in this case), and we go back to our code and attempt to figure out what went wrong. When an exception is raised that causes the program to terminate, we say that an unhandled exception has been raised. • Consider the code successFailureRatio = numSuccesses/float(numFailures) print 'The success/failure ratio is', successFailureRatio print 'Now here‘ • The attempt to divide by zero will cause the Python runtime • system to raise a ZeroDivisionError exception
  • 34.
    It would havebeen better to have written something along the lines of try: successFailureRatio = numSuccesses/float(numFailures) print 'The success/failure ratio is', successFailureRatio except ZeroDivisionError: print 'No failures so the success/failure ratio is undefined.' print 'Now here'
  • 35.
    Assertions • The Pythonassert statement provides programmers with a simple way to confirm that the state of the computation is as expected. An assert statement can take one of two forms: assert Boolean expression or assert Boolean expression, argument • When an assert statement is encountered, the Boolean expression is evaluated.
  • 36.
    STRUCTURED TYPES, MUTABILITY,AND HIGHERORDER FUNCTIONS • we introduce three structured types. One, tuple, is a rather simple generalization of str. The other two, list and dict, are more interesting—in part because they are mutable Tuples • Like strings, tuples are ordered sequences of elements. The difference is that the elements of a tuple need not be characters. The individual elements can be of any type, and need not be of the same type as each other.
  • 37.
    t1 = () t2= (1, 'two', 3) print t1 print t2 Unsurprisingly, the print statements produce the output () (1, 'two', 3) Lists and Mutability • Like a tuple, a list is an ordered sequence of values, where each value is identified by an index. The syntax for expressing literals of type list is similar to that used for tuples; the difference is that we use square brackets rather than parentheses. The empty list is written as []
  • 38.
    L = ['Idid it all', 4, 'love'] for i in range(len(L)): print L[i] • produces the output, I did it all 4 love L1 = [1,2,3] L2 = [4,5,6] L3 = L1 + L2 print 'L3 =', L3 L1.extend(L2) print 'L1 =', L1 L1.append(L2) print 'L1 =', L1 will print L3 = [1, 2, 3, 4, 5, 6] L1 = [1, 2, 3, 4, 5, 6] L1 = [1, 2, 3, 4, 5, 6, [4, 5, 6]]
  • 39.
    • L.append(e) addsthe object e to the end of L. • L.count(e) returns the number of times that e occurs in L. • L.insert(i, e) inserts the object e into L at index i. • L.extend(L1) adds the items in list L1 to the end of L. • L.remove(e) deletes the first occurrence of e from L. • L.index(e) returns the index of the first occurrence of e in L. It raises an exception ,if e is not in L. • L.pop(i) removes and returns the item at index i in L. If i is omitted, it defaults to -1, to remove and return the last element of L. • L.sort() sorts the elements of L in ascending order. • L.reverse() reverses the order of the elements in L.
  • 40.
    Functions as Objects •In Python, functions are first-class objects. That means that they can be treated like objects of any other type, e.g., int or list. They have types, e.g., the expression type(fact) has the value <type 'function'>; they can appear in expressions, e.g., as the right-hand side of an assignment statement or as an argument to a function; they can be elements of lists; etc applyToEach(L, factR) print 'L =', L print 'Apply Fibonnaci to each element of', L applyToEach(L, fib) print 'L =', L
  • 41.
    Strings, Tuples, andLists • We have looked at three different sequence types: str, tuple, and list. They are similar in that objects of all of these types can be operated upon as described in below • seq[i] returns the ith element in the sequence. • len(seq) returns the length of the sequence. • seq1 + seq2 returns the concatenation of the two sequences. • n * seq returns a sequence that repeats seq n times. • seq[start:end] returns a slice of the sequence. • e in seq is True if e is contained in the sequence and False otherwise. • e not in seq is True if e is not in the sequence and False otherwise. • for e in seq iterates over the elements of the sequence.
  • 42.
    • Some oftheir other similarities and differences are summarized
  • 43.
    Strings Functions • s.count(s1)counts how many times the string s1 occurs in s. • s.find(s1) returns the index of the first occurrence of the substring s1 in s, and -1 if s1 is not in s. • s.rfind(s1) same as find, but starts from the end of s (the “r” in rfind stands for reverse). • s.index(s1) same as find, but raises an exception (see Chapter 7) if s1 is not in s. • s.rindex(s1) same as index, but starts from the end of s. • s.lower() converts all uppercase letters in s to lowercase. • s.replace(old, new) replaces all occurrences of the string old in s with the string new. • s.rstrip() removes trailing white space from s. • s.split(d) Splits s using d as a delimiter. Returns a list of substrings of s. For example, the value of 'David Guttag plays basketball'.split(' ') is ['David', 'Guttag', 'plays', 'basketball']. If d is omitted, the substrings are separated by arbitrary strings of whitespace characters (space, tab, newline, return, and formfeed).
  • 44.
    Dictionaries • Objects oftype dict (short for dictionary) are like lists except that “indices” need not be integers—they can be values of any immutable type. Since they are not ordered, we call them keys rather than indices. Think of a dictionary as a set of key/value pairs. Literals of type dict are enclosed in curly braces, and each element is written as a key followed by a colon followed by a value. For example, the code, monthNumbers = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May'} print 'The third month is ' + monthNumbers[3] dist = monthNumbers['Apr'] - monthNumbers['Jan'] print 'Apr and Jan are', dist, 'months apart' will print The third month is Mar Apr and Jan are 3 months apart