Data Loading...
MF PYTHON (1) Flipbook PDF
MF PYTHON (1)
121 Views
110 Downloads
FLIP PDF 832.96KB
NETTUR TECHNICAL TRAINING FOUNDATION
MASTER FILE
FOR
PYTHON PROGRAMMING
SEMESTER V SUBJECT CODE: CP 04 05 02
Prepared By: Mr. Ramakrishnanand , NEC Approved By: Mrs. Roopa.PB Course Coordinator CP-04
Rev.0
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
JUNE2018
Page1
DETAILED SYLLABUS
SUBJECT CODE
CP 04 05 02
SUBJECT NAME HOURS PER SEMESTER
PYTHON PROGRAMMING 40
REV. NO.
0
REV.DATE
07-06-2018
1.0GENERAL OBJECTIVES: At the end of the semester students will be able to: x Knowledge on basic of python. x Proficient to write coding with python. x Introduction on Framework 2.0 TOPICS: SL.NO. 1 2 3
TOPICS Introduction Python Here, we have three assignment statements. 5 is an integer assigned to the variable a. Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of characters) assigned to the variables b and c respectively. Multiple assignments In Python, multiple assignments can be made in a single statement as follows: a, b, c =5,3.2,"Hello" If we want to assign the same value to multiple variables at once, we can do this as x = y = z ="same" This assigns the "same" string to all the three variables.
Expressions and Arithmetic What is an Operator? Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Perl language supports many operator types, but following is a list of important and most frequently used operators í x Arithmetic Operators x Equality Operators x Logical Operators
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page11
x x x x x
Assignment Operators Bitwise Operators Logical Operators Quote-like Operators Miscellaneous Operat
2.3DECISION MAKING Decision making is required when we want to execute a code only if a certain condition is satisfied. The if…elif…else statement is used in Python for decision making. Python if Statement Syntax if test expression: statement(s) Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True. If the text expression is False, the statement(s) is not executed. In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as True. None and 0are interpreted as False. Python if Statement Flowchart
Python if...else Syntax of if...else if test expression: Body of if else: Body of else
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page12
The if..else statement evaluates test expression and will execute body of if only when test condition is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks. Python if..else Flowchart
Python if...elif...else Syntax of if...elif...else if test expression: Body of if elif test expression: Body of elif else: Body of else The elif is short for else if. It allows us to check for multiple expressions. If the condition for ifis False, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed. Only one block among the several if...elif...else blocks is executed according to the condition. A if block can have only one else block. But it can have multiple elifblocks.
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page13
Flowchart of if...elif...else
Python Nested if statements We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming. In fact, any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. This can get confusing, so must be avoided if we can. Python Nested if Example 2.4 Looping The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal. Syntax of for Loop forval in sequence: Body of for Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation. Flowchart of for Loop
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page14
Python while Loop The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true. We generally use this loop when we don't know beforehand, the number of times to iterate. Syntax of while Loop whiletest_expression: Body of while In while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues untill the test_expression evaluates to False. In Python, the body of the while loop is determined through indentation. Body starts with indentation and the first unindented line marks the end. Python interprets any nonzero value as True. None and 0 are interpreted as False. Flowchart of while Loop
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page15
Python break and continue Statement In Python, break and continue statements can alter the flow of a normal loop. Loops iterate over a block of code until test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without cheking test expression. The break and continue statements are used in these cases. break statement The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If it is inside a nested loop (loop inside another loop), break will terminate the innermost loop. Syntax of break break
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page16
Flowchart of break
The working of break statement in for loop and while loop is shown below.
Python pass Statement In Python programming, pass is a null statement. The difference between a comment and passstatement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored. But nothing happens when it is executed. It results into no operation (NOP). Syntax of pass pass
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page17
We generally use it as a placeholder. Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body that does nothing.
3.0 Using Functions, Class and Objects 3.2 Defining a Function, Calling a Function In Python, function is a group of related statements that perform a specific task. Functions help break our program into smaller and modular chucks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes code reusable. Syntax of Function deffunction_name(parameters): """docstring""" statement(s) Above shown is a function definition which consists of following components. 1. Keyword def marks the start of function header. 2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python. 3. Parameters (arguments) through which we pass values to a function. They are optional. 4. A colon (:) to mark the end of function header. 5. Optional documentation string (docstring) to describe what the function does. 6. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces). 7. An optional return statement to return a value from the function.
3.2 Function Arguments Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters. The return statement The return statement is used to exit a function and go back to the place from where it was called.
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page18
Syntax of return return [expression_list] This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.
3.3 Scope and Lifetime of variables Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope. Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls. Here is an example to illustrate the scope of a variable inside a function. defmy_func(): x =10 print("Value inside function:",x) x =20 my_func() print("Value outside function:",x) Output
Value inside function: 10 Value outside function: 20 Here, we can see that the value of x is 20 initially. Even though the function my_func()changed the value of x to 10, it did not effect the value outside the function. This is because the variable x inside the function is different (local to the function) from the one outside. Although they have same names, they are two different variables with different scope. On the other hand, variables outside of the function are visible from inside. They have a global scope. We can read these values from inside the function but cannot change
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page19
(write) them. In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global.
3.4 Modules Modules refer to a file containing Python statements and definitions. A file containing Python code, for e.g.: example.py, is called a module and its module name would be example. We use modules to break down large programs into small manageable and organized files. Furthermore, modules provide reusability of code. We can define our most used functions in a module and import it, instead of copying their definitions into different programs. Let us create a module. Type the following and save it as example.py. # Python Module example def add(a, b): """This program adds two numbers and return the result""" result= a + b return result
Here, we have defined a functionadd() inside a module named example. The function takes in two numbers and returns their sum.
How to import modules in Python? We can import the definitions inside a module to another module or the interactive interpreter in Python. We use the import keyword to do this. To import our previously defined module example we type the following in the Python prompt. >>> import example
This does not enter the names of the functions defined in example directly in the current symbol table. It only enters the module name example there. Using the module name we can access the function using dot (.) operation. For example:
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page20
>>>example.add(4,5.5) 9.5
Python has a ton of standard modules available. You can check out the full list of Python standard modules and what they are for. These files are in the Lib directory inside the location where you installed Python. Standard modules can be imported the same way as we import our user-defined modules. There are various ways to import modules. They are listed as follows. Python import statement
We can import a module using import statement and access the definitions inside it using the dot operator as described above. import math print("The value of pi is", math.pi) print("The value of pi is", pi)
Import with renaming
We can import a module by renaming it as follows. import math as m Python from...import statement
We can import specific names from a module without importing the module as a whole. from math import pi
Import all names
We can import all names(definitions) from a module from math import * Overview of OOP Terminology
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page21
3.5 Overview of OOP Terminology Python is an object oriented programming language. Unlike procedure oriented programming, in which the main emphasis is on functions, object oriented programming stress on objects. Object is simply a collection of ,# parentheses is optional >>>type(my_tuple)
Accessing Elements in a Tuple
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page38
There are various ways in which we can access the elements of a tuple. Indexing We can use the index operator [] to access an item in a tuple. Index starts from 0. So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't use float or other types, this will result into TypeError. Nested tuple are accessed using nested indexing. >>>my_tuple=['p','e','r','m','i','t'] >>>my_tuple[0] 'p' >>>my_tuple[5] 't' >>>my_tuple[6]# index must be in range ... IndexError: list index out of range >>>my_tuple[2.0]# index must be an integer ... TypeError: list indices must be integers,notfloat >>>n_tuple=("mouse",[8,4,6],(1,2,3)) >>>n_tuple[0][3]# nested index 's' >>>n_tuple[1][1]# nested index 4 >>>n_tuple[2][0]# nested index 1 Negative Indexing Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. >>>my_tuple=['p','e','r','m','i','t'] >>>my_tuple[-1] 't' >>>my_tuple[-6] 'p' Slicing We can access a range of items in a tuple by using the slicing operator (colon). >>>my_tuple=('p','r','o','g','r','a','m','i','z') >>>my_tuple[1:4]# elements 2nd to 4th ('r','o','g')
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page39
>>>my_tuple[:-7]# elements beginning to 2nd ('p','r') >>>my_tuple[7:]# elements 8th to end ('i','z') >>>my_tuple[:]# elements beginning to end ('p','r','o','g','r','a','m','i','z') Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to access a range, we need the index that will slice the portion from the tuple.
Changing or Deleting a Tuple Unlike lists, tuples are immutable. This means that elements of a tuple cannot be changed once it has been assigned. But if the element is itself a mutable datatype like list, its nested items can be changed. We can also assign a tuple to different values (reassignment). >>>my_tuple=(4,2,3,[6,5]) >>>my_tuple[1]=9# we cannot change an element ... TypeError:'tuple'object does not support item assignment >>>my_tuple[3]=9# we cannot change an element ... TypeError:'tuple'object does not support item assignment >>>my_tuple[3][0]=9# but item of mutable element can be changed >>>my_tuple (4,2,3,[9,5]) >>>my_tuple=('p','r','o','g','r','a','m','i','z')# tuples can be reassigned >>>my_tuple ('p','r','o','g','r','a','m','i','z') We can use + operator to combine two tuples. This is also called concatenation. The * operator repeats a tuple for the given number of times. These operations result into a new tuple. >>>(1,2,3)+(4,5,6) (1,2,3,4,5,6)
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page40
>>>("Repeat",)*3 ('Repeat','Repeat','Repeat') We cannot delete or remove items from a tuple. But deleting the tuple entirely is possible using the keyword del. >>>my_tuple=('p','r','o','g','r','a','m','i','z') >>>delmy_tuple[3]# can't delete items ... TypeError:'tuple'object doesn't support item deletion >>>delmy_tuple # can delete entire tuple >>>my_tuple ... NameError: name 'my_tuple' is not defined Advantage of Tuple over List Tuples and list look quite similar except the fact that one is immutable and the other is mutable. We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes. There are some advantages of implementing a tuple than a list. Here are a few of them. x Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight performance boost. x Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible. x If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected. x Set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable. However, the set itself is mutable (we can add or remove items). Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.
4.4Python Dictionaries Python dictionary is an unordered collection of items. While other compound datatypes have only value as an element, a dictionary has a key: value pair. Dictionaries are optimized to retrieve values when the key is known. Creating a Dictionary Creating a dictionary is as simple as placing items inside curly braces {} separated by comma. An item has a key and the corresponding value expressed as a pair, key: value. While values can be of any datatype and can repeat, keys must be of immutable
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page41
type (string, number or tuple with immutable elements) and must be unique. We can also create a dictionary using the built-in function dict(). # empty dictionary my_dict={} # dictionary with integer keys my_dict={1:'apple',2:'ball'} # dictionary with mixed keys my_dict={'name':'John',1:[2,4,3]} # using dict() my_dict=dict({1:'apple',2:'ball'}) # from sequence having each item as a pair my_dict=dict([(1,'apple'),(2,'ball')]) Accessing Elements in a Dictionary While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. The difference while using get() is that it returns None instead of KeyError, if the key is not found. >>>my_dict={'name':'Ranjit','age':26} >>>my_dict['name'] 'Ranjit' >>>my_dict.get('age') 26 >>>my_dict.get('address') >>>my_dict['address'] ... KeyError:'address' Changing or Adding Elements in a Dictionary Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page42
>>>my_dict {'age':26,'name':'Ranjit'} >>>my_dict['age']=27# update value >>>my_dict {'age':27,'name':'Ranjit'} >>>my_dict['address']='Downtown'# add item >>>my_dict {'address':'Downtown','age':27,'name':'Ranjit'} Deleting or Removing Elements from a Dictionary We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value. The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself. >>> squares ={1:1,2:4,3:9,4:16,5:25}# create a dictionary >>>squares.pop(4)# remove a particular item 16 >>> squares {1:1,2:4,3:9,5:25} >>>squares.popitem()# remove an arbitrary item (1,1) >>> squares {2:4,3:9,5:25} >>>del squares[5]# delete a particular item >>> squares {2:4,3:9} >>>squares.clear()# remove all items >>> squares {} >>>del squares # delete the dictionary itself
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page43
>>> squares ... NameError: name 'squares'isnotdefined
4.5Creating a Set in Python A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element. >>># set of integers >>>my_set={1,2,3} >>># set of mixed datatypes >>>my_set={1.0,"Hello",(1,2,3)} >>># set donot have duplicates >>>{1,2,3,4,3,2} {1,2,3,4} >>># set cannot have mutable items >>>my_set={1,2,[3,4]} ... TypeError:unhashable type:'list' >>># but we can make set from a list >>>set([1,2,3,2]) {1,2,3} Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument. >>> a ={} >>>type(a)
>>> a =set()
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page44
>>>type(a)
Changing a Set in Python Sets are mutable. But since they are unordered, indexing have no meaning. We cannot access or change an element of set using indexing or slicing. Set does not support it. We can add single elements using the method add(). Multiple elements can be added using update()method. The update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are avoided. >>>my_set={1,3} >>>my_set[0] ... TypeError:'set'object does not support indexing >>>my_set.add(2) >>>my_set {1,2,3} >>>my_set.update([2,3,4]) >>>my_set {1,2,3,4} >>>my_set.update([4,5],{1,6,8}) >>>my_set {1,2,3,4,5,6,8} Removing Elements from a Set A particular item can be removed from set using methods like discard() and remove(). The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition. The following example will illustrate this. >>>my_set={1,3,4,5,6} >>>my_set.discard(4) >>>my_set {1,3,5,6} >>>my_set.remove(6) >>>my_set {1,3,5} >>>my_set.discard(2) >>>my_set
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page45
{1,3,5} >>>my_set.remove(2) ... KeyError:2 Similarly, we can remove and return an item using the pop() method. Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary. We can also remove all items from a set using clear(). >>>my_set=set("HelloWorld") >>>my_set.pop() 'r' >>>my_set.pop() 'W' >>>my_set {'d','e','H','o','l'} >>>my_set.clear() >>>my_set set() Python Set Operation Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods. Let us consider the following two sets for the following operations. >>> A ={1,2,3,4,5} >>> B ={4,5,6,7,8}
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page46
Set Union
Union of A and B is a set of all elements from both sets. Union is performed using | operator. Same can be accomplished using the method union(). >>> A | B {1,2,3,4,5,6,7,8} >>>A.union(B) {1,2,3,4,5,6,7,8} >>>B.union(A) {1,2,3,4,5,6,7,8} Set Intersection
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page47
Intersection of A and B is a set of elements that are common in both sets. Intersection is performed using & operator. Same can be accomplished using the method intersection(). >>> A & B {4,5} >>>A.intersection(B) {4,5} >>>B.intersection(A) {4,5} Set Difference
Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a set of element in B but not in A. Difference is performed using operator. Same can be accomplished using the method difference(). >>> A - B {1,2,3} >>>A.difference(B) {1,2,3} >>> B - A {8,6,7} >>>B.difference(A) {8,6,7}
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page48
Set Symmetric Difference
Symmetric Difference of A and B is a set of element in both A and B except those common in both. Symmetric difference is performed using ^ operator. Same can be accomplished using the method symmetric_difference(). >>> A ^ B {1,2,3,6,7,8} >>>A.symmetric_difference(B) {1,2,3,6,7,8} >>>B.symmetric_difference(A) {1,2,3,6,7,8}
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page49
5.0 Framework A framework does several things: x x x x
it makes it easier to work with complex technologies it ties together a bunch of discrete objects/components into something more useful it forces the team (or just me) to implement code in a way that promotes consistent coding, fewer bugs, and more flexible applications everyone can easily test and debug the code, even code that they didn't write
If I look at this list of vague framework requirements, I come up with a set of specific classifications that define a framework: x
x
x
Wrappers. A wrapper: o simplifies an interface to a technology o reduces/eliminates repetitive tasks o increases application flexibility through abstraction o are often re-usable regardless of high level design considerations Architectures. An architecture: o manages a collection of discrete objects o implements a set of specific design elements methodologies: A methodology: o enforces the adherence to a consistent design approach o decouples object dependencies o are often re-usable regardless application requirements
So, before talking about frameworks, we need to talk about wrappers, architectures, and methodologies. After that, I'm not sure what will be left to say about frameworks!
A Framework Is... A Wrapper
A wrapper is way of repackaging a function or set of functions (related or not) to achieve one or more of the following goals (probably incomplete):
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page50
x x x x
Simplification of use Consistency in interface Enhancement of core functionality Collecting discrete processes into a logical association (an object)
It's easy to fall into the idea that everything is a wrapper, just like saying "everything is relative" (which is untrue, because that statement itself is an absolute), but if you think about it, not everything is a wrapper. Most of MFC and .NET are wrappers are the core API's. Some are laughably so, providing classes that merely wrap messages into inline methods. Other wrappers are more complex. For example, I've written a wrapper for the Visio COM object that takes all the grunt work out of using Visio's primitive functions (primitive in the sense of "fundamental", as opposed to "poorly implemented") to do basic things like drop shapes, connect shapes, and read a shape collection. But then, you get into implementation that truly provides new functionality. Yes, it utilizes other objects, other API's, even other wrappers, but it isn't a wrapper in itself because it does something totally new, rather than just adding to, subtracting from, or managing a collection of existing work. A wrapper modifies existing behavior. There's a lot of code out there that creates new behavior (thus becoming subject to An Architecture
An architecture is a style that incorporates specific design elements. Obviously, a framework needs to have a design. Its architecture is separate from the collection of wrappers that it implements and from the enforcement of a specific implementation methodology. MFC's document-view classes are an architecture. Essentially, an architecture implements associations between objects--inheritance, container, proxy, collection, etc. Architectures have the interesting attribute that, if you don't like them, you can usually ignore them or replace them (at least at the beginning of a project). Architectures can and are useful because they create a re-usable structure (a collection of objects) that provide some enhanced functionality, but once you start using them, you're pretty much stuck with them unless you do some major refactoring.
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page51
A Methodology
Let's look at this word: x x
Method - a way of doing something -ology - in a "scientific" manner--designed, consistent, repeatable, testable, proven
or, if you want to look it up in the dictionary: A body of practices, procedures, and rules used by those who work in a discipline. OK, we've all worked with design methodologies, but not too many people have worked with a framework that implements a particular methodology. I don't think arguing that MFC is a methodology (with exceptions) is the right way to think about classes. While a class specifies visibility, interface, and inheritance usage, and these, along with language syntax, can certainly be classified as "a body of practices, procedures, and rules", saying that a class or a collection of classes is a methodology is like saying that a bunch of leaves make a tree. A methodology fills in the supporting structure. Is MFC's message mapping implementation a methodology? Mostly, yes. While I view it primarily as an architecture that wraps the underlying API, and you don't have to use it if you don't want to, in some cases you pretty much can't avoid using it, especially when you want to define specialized message handlers. You have to use the method that MFC implements in order to specify and override the base class implementation. And since this is an application wide issue, it fits better into the definition of a methodology than a wrapper (which it is) or an architecture (which it is). So, things can be fuzzy, and sometimes they can feel like splitting hairs, but it doesn't detract from the value of looking at methodology as a classification. While architectures deal with the associations between things, a methodology deals with the interaction between things. The first is a passive relationship and the second is an activity. Most of the methodology that I implement is in the activity of communicating between objects, managing data persistence, responding to user events, etc. Within those activities are architectures that associate interrelated objects.
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page52
Design Patterns Design patterns are both architectures and methodologies. The structural patterns are more architecture, when the creational and behavioral patterns are more methodologies because their usage enforces a particular method of interaction. However you implement, say, behavioral patterns, you're entire application has to adhere to that implementation. However, I will say this one thing--design patterns are in a category that I would call "lightweight methodologies". They are not necessarily heavy handed about how components and objects interact with each other. TYPES OF FRAMEWORKS Frameworks can be used to create most applications on the back end, including web services, web applications, and software. Software frameworks: A software framework is a reusable environment that’s part of a larger software platform. They’re specifically geared toward facilitating the development of software applications and include components, such as libraries of code, support programs, compilers, tool sets, and specific APIs that facilitate the flow of data. Web application frameworks are software frameworks used to streamline web app and website development, web services, and web resources. A popular type of web app framework is the Model-View Controller (MVC) architecture, named for the way it separates the code for each application component into modules. Below are some the most popular frameworks, broken down by the programming languages in which they’re written. Python x
x x
x x
Django framework: an all-in-one Python framework designed for speedy development in fast-paced environments that works well with relational databases. Flask: a Python micro-framework with a minimalist approach—but robust in its own right. It’s ideal for stand-alone apps and quick prototyping. Pyramid: Formerly “Pylons,” a framework that offers great flexibility with NoSQL integration. It’s great for development of APIs, prototyping, and large web apps, like content management systems. Tornado: an event-based, non-blocking Python web server and web app framework for high-traffic volume. Bottle: a simple, light micro-framework
NTTF _DIPLOMA IN ELECTRONICS_SEM5_PYTHONPROGRAMMING REV-0-JUNE 2018
Page53
NETTUR TECHNICAL TRAINING FOUNDATION SEMESTER – V PYTHON PROGRAMMING SUBJECT CODE:CP 04 05 02 Prepared by: Mr. Ramakrishnanand S
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
UNIT 1 INTRODUCTION
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
SYLLABUS
1.1
History of Python
1 Hr
1.2
Python Features
1 Hr
1.3
Getting and Installation of Python
1 Hr
1.4
Running Python
1 Hr
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Context of Software Development Software
Development Tools Compilers Interpreters Debuggers Profilers
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
1.0 INTRODUCTION
Python is a very powerful high-level, object-oriented programming language created by Guido van Rossum. It has a very easy-to-use and simple syntax, making it the perfect language for someone trying to learn computer programming for the first time. Python is an interpreted language
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
1.1 History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula -3, C, C++, Algol - 68, SmallTalk, Unix shell, and other scripting languages.
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
1.2 Python Features
Easy-to-learn Easy-to-read Easy-to-maintain A broad standard library Interactive Mode Portable Extendable Databases GUI Programming Scalable
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
1.3 Getting and Installation of Python
Windows Installation Open a Web browser and go to https://www.python.org/downloads/. Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install. To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI. Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done.
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
1.4 Running Python
Interactive Interpreter You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.
Script from the Command-line A Python script can be executed at command line by invoking the interpreter on your application, as in the following C: >python script.py # Windows/DOS
Integrated Development Environment You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Thank You
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
NETTUR TECHNICAL TRAINING FOUNDATION SEMESTER – V PYTHON PROGRAMMING SUBJECT CODE:CP 04 05 02 Prepared by: Mr. Ramakrishnanand S
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
UNIT 2 PYTHON DATA TYPES,FLOW CONTROL
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
SYLLABUS
2.1
Basic Syntax, Standard Data Types
2.2
Assigning Values to Variables, Types of Operator
2.3
Decision Making
2.4
Loops
DIPLOMA IN ELECTRONICS
3 Hr
3 Hr
3 Hr
3 Hr
5TH SEMESTER
PYTHON
2.1 Python Data type, Flow control
Basic Syntax Standard Data Types The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.
Python Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object.
Reserved Words There are reserved words and you cannot use them as constant or variable or any other identifier names.
Lines and Indentation Multi-Line Statements Quotation in Python Comments in Python Data types in Python Every value in Python has a datatype. Since everything is an object in Python programming, datatypes are actually classes and variables are instance (object) of these classes
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
2.2 Assigning values to Variables, Types of Operator
A variable is a location in memory used to store some data (value). They are given unique names to differentiate between different memory locations. We don't need to declare a variable before using it. In Python, we simply assign a value to a variable and it will exist. We don't even have to declare the type of the variable. This is handled internally according to the type of value we assign to the variable.
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Values and Variables
assignment operator (=) a = 5b = 3.2c = "Hello“
multiple assignments a, b, c = 5, 3.2, "Hello“
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Expressions and Arithmetic
Arithmetic Operators Equality Operators Logical Operators Assignment Operators Bitwise Operators Logical Operators Quote-like Operators Miscellaneous Operators
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
2.3 Decision Making
if test expression: statement(s)
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
if test expression: Body of ifelse: Body of else
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Syntax of if...elif...else if test expression: Body of ifelif test expression: Body of elifelse: of else
DIPLOMA IN ELECTRONICS
5TH SEMESTER
Body
PYTHON
2.4 Loop
Syntax of for Loop for val in sequence: Body of for
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Syntax of while Loop while test_expression: Body of while
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Python break and continue Statement
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Python pass Statement Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body that does nothing.
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Thank You
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
NETTUR TECHNICAL TRAINING FOUNDATION SEMESTER – V PYTHON PROGRAMMING SUBJECT CODE:CP 04 05 02 Prepared by: Mr. Ramakrishnanand S
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
UNIT 3 FUNCTIONS, CLASS AND OBJECTS
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
SYLLABUS
3.1
Defining a Function, Calling a Function
2 Hr
3.2
Function Arguments, Scope of Variables
2 Hr
3.3
Modules
3.4
Overview of OOP Terminology
DIPLOMA IN ELECTRONICS
4 Hr
4 Hr
5TH SEMESTER
PYTHON
3.0 Defining a Function,Calling a Function
Syntax of Function def function_name(parameters): """docstring""" statement(s) Docstring The first string after the function header is called the docstring and is short for documentation string
The return statement is used to exit a function and go back to the place from where it was called. Syntax of return return [expression_list]
SAMPLE def my_func(): x = 10 print("Value inside function:",x) x = 20my_func()print("Value outside function:",x) Output Value inside function: 10Value outside function: 20
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
]
3.2 Function Arguments, Scope of Variables
Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters Ex: return [expression_list]
Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
3.3 Modules
Modules refer to a file containing Python statements and definitions. How to import modules in Python? We use the import keyword to do this. To import our previously defined module example we type the following in the Python prompt. >>> import example
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
3.4 Overview of OOP Terminology
Python is an object oriented programming language. Unlike procedure oriented programming, in which the main emphasis is on functions, object oriented programming stress on objects class MyNewClass: '''This is a docstring. I have created a new class''' pass
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Class and Objects
Python is an object oriented programming language Defining a Class in Python class MyClass: "This is my second class" a = 10 def func(self): print('Hello') Creating an Object in Python ob = MyClass() Constructors in Python def __init__() Deleting Attributes and Objects del ob DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Inheritance
Inheritance is a powerful feature in object oriented programming.
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Python Inheritance Syntax class DerivedClass(BaseClass): body_of_derived_class Example of Inheritance in Python class Polygon: def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for i in range(no_of_sides)] def inputSides(self): self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)] def dispSides(self): for i in range(self.n): print("Side",i+1,"is",self.sides[i])
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Thank You
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
NETTUR TECHNICAL TRAINING FOUNDATION SEMESTER – V PYTHON PROGRAMMING SUBJECT CODE:CP 04 05 02 Prepared by: Mr. Ramakrishnanand S
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
UNIT 4 & 5 FILES, LISTS,TUPLES, DICTIONARIES AND SETS FRAME WORK
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
SYLLABUS
4.1 4.2 4.3
4.4
4.5
Files
2Hr
Lists
2Hr
Tuples
2Hr
Dictionaries
2Hr
2Hr
Sets
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
4.1 Files
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory Open a file f = open("test.txt") # open file in current directory f = open("C:/Python33/README.txt") # specifying full path
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Python File Modes
Mode
Description
'r'
Open a file for reading. (default)
'w'
Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
'x'
Open a file for exclusive creation. If the file already exists, the operation fails.
'a'
Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.
't'
Open in text mode. (default)
'b'
Open in binary mode.
'+'
Open a file for updating (reading and writing)
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
1. 2. 3. 4.
Read or write (perform operation) f = open("test.txt",'r',encoding = 'utf-8') f.read(4) # read the first 4 data 'This‘ f.read(4) # read the next 4 data ' is ‘ f.read() # read in the rest till end of file f.read() # further reading returns empty string '‘ f.tell() # get the current file position 56 f.seek(0) # bring file cursor to initial position 0 for line in f: ... print(line, end = '') #to read line by line Print(f.read()) # read the entire file To read individual lines of a file f.readline() f.readlines() returns a list of remaining lines of the entire file
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Closing a File f.close()
This method is not entirely safe. A safer way is to use a try...finally block. try: f = open("test.txt",encoding = 'utf-8') # perform file operation finally: f.close()
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
4.2 Lists
Creating a List # empty list my_list = [] # list of integers my_list = [1, 2, 3] # list with mixed datatypes my_list = [1, "Hello", 3.4] # nested list my_list = ["mouse", [8, 4, 6]] Accessing Elements in a List • Indexing • Negative indexing • Slicing • Changing or Adding Elements to a List • Deleting or Removing Elements from a List
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
4.3Tuple
• • • • •
Creating a Tuple # empty tuple my_tuple = () # tuple having integers my_tuple = (1, 2, 3) # tuple with mixed datatypes my_tuple = (1, "Hello", 3.4) # nested tuple my_tuple = ("mouse", [8, 4, 6], (1, 2, 3)) # tuple can be created without parentheses # also called tuple packing my_tuple = 3, 4.6, "dog" # tuple unpacking is also possible a, b, c = my_tuple Accessing Elements in a Tuple Indexing Negative indexing Slicing Changing or Adding Elements to a List Deleting or Removing Elements from a List
DIPLOMA IN ELECTRONICS DIP
5TH SEMESTER
PYTHON
4.4 Python Dictionary
Creating a Dictionary my_dict = {1: 'apple', 2: 'ball'} my_dict = dict([(1,'apple'), (2,'ball')])
Accessing Elements in a Dictionary my_dict['name'] my_dict.get('age')
Changing or Adding Elements in a Dictionary my_dict['age'] = 27 # update value my_dict['address'] = 'Downtown' # add item
Deleting or Removing Elements from a Dictionary squares = {1:1, 2:4, 3:9, 4:16, 5:25} squares.pop(4) # remove a particular item squares.popitem() # remove an arbitrary item del squares[5] # delete a particular item squares.clear() # remove all items del squares # delete the dictionary itself
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
4.5Python Sets
Creating a Set in Python my_set = {1.0, "Hello", (1, 2, 3)}
Changing a Set in Python my_set.add(2) my_set.update([2,3,4]) my_set.update([4,5], {1,6,8})
Removing Elements from a Set my_set = {1, 3, 4, 5, 6} my_set.discard(4) my_set.remove(6) my_set.pop() my_set.clear()
Python Set Operation Set Union A.union(B), A | B Set Intersection A & B , A.intersection(B) Set Difference A – B , A.difference(B) Set Symmetric Difference A ^ B, B.symmetric_difference(A)
DIPLOMA OM IN ELECTRONICS
5TH SEMESTER
PYTHON
5.1 Frame work
framework does several things: it makes it easier to work with complex technologies it ties together a bunch of discrete objects/components into something more useful it forces the team (or just me) to implement code in a way that promotes consistent coding, fewer bugs, and more flexible applications everyone can easily test and debug the code, even code that they didn't write A Framework Is...
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON
Thank You
DIPLOMA IN ELECTRONICS
5TH SEMESTER
PYTHON