Lecture notes Python programming

COMPUTER SCIENCE WITH PYTHON and computer science with python class 12. and python scientific lecture notes pdf free download
NathanBenett Profile Pic
NathanBenett,Germany,Researcher
Published Date:11-07-2017
Your Website URL(Optional)
Comment
WITH PYTHON CLASS - XII Shiksha Kendra, 2, Community Centre, Preet Vihar, Delhi-110 092 IndiaComputer Science Chapter-1: Review of Python Learning Objectives: At the end of this chapter the students will be able to understand: 2 Interactive Mode 2 Script Mode 2 Data Types 2 Functions in Python 2 Sequential Statement 2 Selective Statements 2 Looping Statements 2 String and String Methods 2 List and List Methods 2 Tuple and Tuple Methods 2 Dictionary and Dictionary Methods Introduction: We have learnt Python programming language in the 11th class and continue to learn the same language program in class 12th also. We also know that Python is a high level language and we need to have Python interpreter installed in our computer to write and run Python program. Python is also considered as an interpreted language because Python programs are executed by an interpreter. We also learn that Python shell can be used in two ways, viz., interactive mode and script mode. Interactive Mode: Interactive Mode, as the name suggests, allows us to interact with OS. Hear, when we type Python statement, interpreter displays the result(s) immediately. That means, when we type Python expression / statement / command after the prompt (), the Python immediately responses with the output of it. Let's see what will happen when we type print "WELCOME TO PYTHON PROGRAMMING" after the prompt. print "WELCOME TO PYTHON PROGRAMMING" WELCOME TO PYTHON PROGRAMMING Example: print 5+10 15 x=10 2Computer Science Computer Science y=20 print xy 200 Script Mode: In script mode, we type Python program in a file and then use interpreter to execute the content of the file. Working in interactive mode is convenient for beginners and for testing small pieces of code, as one can test them immediately. But for coding of more than few lines, we should always save our code so that it can be modified and reused. Python, in interactive mode, is good enough to learn, experiment or explore, but its only drawback is that we cannot save the statements and have to retype all the statements once again to re-run them. Example: Input any two numbers and to find Quotient and Remainder. Code: (Script mode) a = input ("Enter first number") b = input ("Enter second number") print "Quotient", a/b print "Remainder", a%b Output: (Interactive Mode) Enter first number10 Enter second number3 Quotient 3 Remainder 1 Variables and Types: One of the most powerful features of a programming language is the ability to manipulate variables. When we create a program, we often like to store values so that it can be used later. We use objects (variables) to capture data, which then can be manipulated by computer to provide information. By now, we know that object/variable is a name which refers to a value. Every object has: 2 An Identity, 2 A type, and 2 A value. A. Identity of the object is its address in memory and does not get change once it is created. We may know it by typing id (variable) We would be referring to objects as variable for now. B. Type (i.e data type) is a set of values, and the allowable operations on those values. It can be one of the following: 3Computer Science Data Types None Sets Mappings Numbers Sequences Dictionary Integer Floating Strings List Complex Tuple Point Boolean 1. Number: Number data type stores Numerical Values. This data type is immutable i.e. value of its object cannot be changed. Numbers are of three different types: 2 Integer & Long (to store whole numbers i.e. decimal digits without fraction part) 2 Float/floating point (to store numbers with fraction part) 2 Complex (to store real and imaginary part) 2. None: This is special data type with a single value. It is used to signify the absence of value/false in a situation. It is represented by None. 3. Sequence: A sequence is an ordered collection of items, indexed by positive integers. It is a combination of mutable (a mutable variable is one, whose value may change) and immutable (an immutable variable is one, whose value may not change) data types. There are three types of sequence data type available in Python, they are Strings, Lists & Tuples. 3.1 String- is an ordered sequence of letters/characters. They are enclosed in single quotes (' ') or double quotes ('' "). The quotes are not part of string. They only tell the computer about where the string constant begins and ends. They can have any character or sign, including space in them. These are immutable. A string with length 1 represents a character in Python. 3.2 Lists: List is also a sequence of values of any type. Values in the list are called elements / items. These are mutable and indexed/ordered. List is enclosed in square brackets (). 3.3 Tuples: Tuples are a sequence of values of any type and are indexed by integers. They are immutable. Tuples are enclosed in (). 4. Sets: Set is unordered collection of values of any type with no duplicate entry. It is immutable. 5. Mapping: This data type is unordered and mutable. Dictionaries fall under Mappings. 5.1 Dictionaries: It can store any number of python objects. What they store is a key -value pairs, which are accessed using key. Dictionary is enclosed in curly brackets (). C. Value: Value is any number or a letter or string. To bind value to a variable, we use assignment operator (=). 4Computer Science Keywords - are used to give some special meaning to the interpreter and are used by Python interpreter to recognize the structure of program. A partial list of keywords in Python 2.7 is and del from not while as elif global or with assert else if pass Yield break except import print class exec in Raise continue finally is return def for lambda try Operators and Operands Operators are special symbols that represent computation like addition and multiplication. The values that the operator is applied to are called operands. Operators when applied on operands form an expression. Operators are categorized as Arithmetic, Relational, Logical and Assignment. Following is the partial list of operators: Mathematical/Arithmetic operators: +, -, , /, %, and //. Relational operators: , =, , =, = or and ==. Logical operators: or, and, and not Assignment Operator: =, +=, -=, =, /=, %=, = and //= Input and Output Program need to interact with end user to accomplish the desired task, this is done using Input-Output facility. Input means the data entered by user (end user) of the program. In python, raw_input() and input ( ) functions are available for input. Syntax of raw_input() is: Variable = raw_input (prompt) Example: x = raw_input ('Enter your name: ') Enter your name: ABC Example: y = int(raw_input ("enter your roll no")) will convert the accepted string into integer before assigning to 'y'. 5Computer Science Syntax for input() is: Variable = input (prompt) Example: x = input ('enter data:') Enter data: 2+ ½.0 Will supply 2.5 to x Print: This statement is used to display results. Syntax: print expression/constant/variable Example: print "Hello" Hello Comments: As the program gets bigger and more complicated, it becomes difficult to read it and difficult to look at a piece of code and to make out what it is doing by just looking at it. So it is good to add notes to the code, while writing it. These notes are known as comments. In Python, comments start with '' symbol. Anything written after in a line is ignored by interpreter. For more than one line comments, we use the following; 2 Place '' in front of each line, or 2 Use triple quoted string. ( """ """) Functions in Python: A function is named sequence of statement(s) that performs a computation. It contains line of code(s) that are executed sequentially from top to bottom by Python interpreter. They are the most important building block for any software in Python. For working in script mode, we need to write the Python code in functions and save it in the file having .py extension. Functions can be categorized as belonging to 2 Modules 2 Built in 2 User Defined 1. Module: A module is a file containing Python definitions (i.e. functions) and statements. Standard library of Python is extended as module(s) to a Programmer. Definitions from the module can be used into code of Program. To use these modules in a program, programmer needs to import the module. Once we import a module, we can reference (use) to any of its functions or variables in our code. There are two ways to import a module in our program, they are 6Computer Science 2 import 2 from Import: It is simplest and most common way to use modules in our code. Syntax: import modulename1 , module name 2, - Example: Input any number and to find square and square root. Example: import math x = input ("Enter any number") y = math.sqrt(x) a = math.pow(x,2) print "Square Root value=",y print "square value=",a output: Enter any number25 Square Root value= 5.0 square value= 625.0 From statement: It is used to get a specific function in the code instead of complete file. If we know beforehand which function(s), we will be needing, then we may use 'from'. For modules having large number of functions, it is recommended to use from instead of import. Syntax from modulename import functionname , functionname….. from modulename import will import everything from the file. Example: Input any number and to find square and square root. Example: from math import sqrt,pow x=input("Enter any number") y=sqrt(x) without using math a=pow(x,2) without using math print "Square Root value =",y print "square value =",a 7Computer Science Enter any number100 Square Root value = 10.0 square value = 10000.0 The functions available in math module are: ceil() floor() fabs() exp() log() log10() pow() sqrt() cos() sin() tan() degrees() radians() Some functions from random module are: random() randint() uniform() randrange() 2. Built in Function: Built in functions are the function(s) that are built into Python and can be accessed by Programmer. These are always available and for using them, we don't have to import any module (file). Python has a small set of built-in functions as most of the functions have been partitioned to modules. This was done to keep core language precise. abs() max() min() bin() divmod() len() range() round() bool() chr() float() int() long() str( ) type( ) id( ) tuple( ) 3. User Defined Functions: In Python, it is also possible for programmer to write their own function(s). These functions can then be combined to form module which can be used in other programs by importing them. To define a function, keyword 'def' is used. After the keyword comes an identifier i.e. name of the function, followed by parenthesized list of parameters and the colon which ends up the line, followed by the block of statement(s) that are the part of function. Syntax: def NAME (PARAMETER1, PARAMETER2, …..): Square brackets include optional part of statement statement(s) Example: To find simple interest using function. Example: def SI(P,R,T): return(PRT) Output: SI(1000,2,10) 20000 8Computer Science Parameters and Arguments Parameters are the value(s) provided in the parenthesis when we write function header. These are the values required by function to work. If there is more than one value required by the function to work on, then, all of them will be listed in parameter list separated by comma. Example: def SI (P,R,T): Arguments are the value(s) provided in function call/invoke statement. List of arguments should be supplied in same way as parameters are listed. Bounding of parameters to arguments is done 1:1, and so there should be same number and type of arguments as mentioned in parameter list. Example: Arguments in function call SI (1000,2,10) 1000,2,10 are arguments. An argument can be constant, variable, or expression. Example: Write the output from the following function: def SI(p,r=10,t=5): return(prt/100) if we use following call statement: SI(10000) SI(20000,5) SI(50000,7,3) Output SI(10000) 5000 SI(20000,5) 5000 SI(50000,7,3) 10500 Flow of Execution Execution always begins at the first statement of the program. Statements are executed one after the other from top to bottom. Further, the way of execution of the program shall be categorized into three ways; (i) sequence statements, (ii) selection statements, and (iii) iteration or looping statements. Sequence statements: In this program, all the instructions are executed one after another. Example: Program to find area of the circle. 9Computer Science r = input("enter any radius of the circle") a = 3.14rr print "Area=",a output: enter any radius of the circle7 Area = 153.86 In the above program, all three statements are executed one after another. Selective Statements: In this program, some portion of the program is executed based upon the conditional test. If the conditional test is true, compiler will execute some part of the program, otherwise it will execute other part of the program. This is implemented in python using if statement. Syntax: if (condition): if (condition): statements statements else (or) elif (condition): statements statements else: Statements Example: 1. Program to find the simple interest based upon number of years. If number of years is more than 12 rate of interest is 10 otherwise 15. Code: p = input("Enter any principle amount") t = input("Enter any time") if (t10): si = pt10/100 else: si = pt15/100 print "Simple Interest = ",si output: Enter any principle amount 3000 Enter any time12 Simple Interest = 3600 10Computer Science 2. Write a program to input any choice and to implement the following. Choice Find 1. Area of square 2. Area of rectangle 3. Area of triangle Code: c = input ("Enter any Choice") if(c==1): s = input("enter any side of the square") a = ss print"Area = ",a elif(c==2): l = input("enter length") b = input("enter breadth") a = lb print"Area = ",a elif(c==3): x = input("enter first side of triangle") y = input("enter second side of triangle") z = input("enter third side of triangle") s = (x+y+z)/2 A = ((s-x)(s-y)(s-z))0.5 print"Area=",A else: print "Wrong input" Output: Enter any Choice2 enter length4 enter breadth6 Area = 24 Iterative statements: In some programs, certain set of statements are executed again and again based upon conditional test. i.e executed more than one time. This type of execution is called looping or iteration. Looping statement in python is implemented by using 'for' and 'while' statement. 11Computer Science Syntax: (for loop) for variable in range(start,stop+1,step): statements Syntax: (while loop) while (condition): Statements Example: 1. Write a program to input any number and to print all natural numbers up to given number. Code: n = input("enter any number") for i in range(1,n+1): print i, Output: enter any number10 1 2 3 4 5 6 7 8 9 10 2. Write a program to input any number and to find sum of all natural numbers up to given number. Code: n = input("Enter any number") sum= 0 for i in range(1,n+1): sum = sum+i print "sum=",sum Output: Enter any number5 sum = 15 3. Write a program to input any number and to find reverse of that number. Code: n = input("Enter any number") r = 0 while(n0): r = r10+n%10 n = n/10 12Computer Science print "reverse number is", r Output: Enter any number345 reverse number is 543 Example: Write the output from the following code: 1. sum = 0 for i in range(1,11,2): sum+ = i print "sum = ", sum output: sum = 25 2. sum = 0 i = 4 while (i=20): sum+=i i+= 4 print "Sum = ",sum output: Sum = 60 Example: Interchange for loop into while loop 1. for i in range(10,26,2): print i Ans: i=10 while(i26): print i i+=2 2. s=0 for i in range(10,50,10): s + =i 13Computer Science print " Sum= ", s Ans: s = 0 i = 10 while(i50): s+ = i i+ = 10 print "Sum=",s Example: Interchange while loop in to for loop. i = 5 s = 0 while (i25): s+ = i i + = 5 print " Sum =", s Ans: s = 0 for i in range(5,25,5): s+=i print "Sum = ", s Example: How many times following loop will execute. 1. for i in range(10,50,5): print i Ans: i values are 10,15,20,25,30,35,40,45 8 times 2. i=4 while(i25): print i i+=4 Ans: i values are 4,8,12,16,20,24 6 times 14Computer Science String: In python, consecutive sequence of characters is known as a string. An individual character in a string is accessed using a subscript (index). The subscript should always be an integer (positive or negative) and starts from 0. A literal/constant value to a string can be assigned using a single quotes, double quotes or triple quotes. Strings are immutable i.e. the contents of the string cannot be changed after it is created. Strings Operations: + (Concatenation) (Repetition ) in (Membership) not in range (start, stop,step) slicen:m Example: Write the output from the following code: 1. A = 'Global' B = 'warming' print A+B Ans: Globalwarming 2. A = 'Global' Print 3A Ans: 'GlobalGlobalGlobal' 3. A='Global' 'o' in A Ans: True 4. A='Global' 'g' in A Ans: False 5. A='Global' 'o' not in A Ans: False 6. A='Global' 'g' not in A Ans: True String methods & built in functions: len() capitalize() find(sub,start, end) isalnum() isalpha() 15Computer Science isdigit() lower() islower() isupper() upper() lstrip() rstrip() isspace() istitle() replace(old,new) join () swapcase() partition(sep) split(sep,maxsplit) Example: s='Congratulations' len(s) 15 s.capitalize() 'Congratulations' s.find('al') -1 s.find('la') 8 s0.isalnum() True s0.isalpha() True s0.isdigit() False s.lower() 'congratulations' s.upper() 'CONGRATULATIONS' s0.isupper() True s1.isupper() False s.replace('a','') 'Congrtultions' s.isspace() False s.swapcase() 'cONGRATULATIONS' s.partition('a') ('Congr', 'a', 'tulations') s.split('ra',4) 16Computer Science 'Cong', 'tulations' s.split('a') 'Congr', 'tul', 'tions' a=' abc ' a.lstrip() 'abc ' a.rstrip() ' abc' Examples: Example: Write a program to input any string and count number of uppercase and lowercase letters. Code: s=raw_input("Enter any String") rint s u=0 l=0 i=0 while ilen(s): if (si.islower()==True): l+=1 if (si.isupper()==True): u+=1 i+=1 print "Total upper case letters :", u print "Total Lower case letters :", l Output: Enter any String Python PROG Python PROG Total upper case letters: 5 Total Lower case letters: 5 Example: Write the output from the following code: s = 'Indian FESTIVALS' i = 0 while ilen(s): 17Computer Science if (si.islower()): print si.upper(), if (si.isupper()): print si.lower(), i + =1 Ans: i N D I A N f e s t i v a l s List: Like a string, list is a sequence of values. In a string, the values are characters, whereas in a list, they can be of any type. The values in the list are called elements or items or members. It is an ordered set of values enclosed in square brackets . Values in the list can be modified, i.e. it is mutable. As it is set of values, we can use index in square brackets to identify a value belonging to it. List Slices: Slice operator works on list. This is used to display more than one selected values on the output screen. Slices are treated as boundaries and the result will contain all the elements between boundaries. Syntax: Seq = L start: stop: step Where start, stop & step - all three are optional. If you omit first index, slice starts from '0' and omitting of stop will take it to end. Default value of step is 1. Example: L=10,20,30,40,50 L1=L2:4 print L1 30, 40 List Methods: append() extend () pop() del() remove() insert() sort() reverse() len() Example: L=500,1000,1500,2000 L.append(2500) print L 500, 1000, 1500, 2000, 2500 L1=3000,3500 L.extend(L1) 18Computer Science print L 500, 1000, 1500, 2000, 2500, 3000, 3500 L.pop() 3500 L.pop(3) 2000 print L 500, 1000, 1500, 2500, 3000 del L2 print L 500, 1000, 2500, 3000 L.remove(1000) print L 500, 2500, 3000 L.insert(3,3500) print L 500, 2500, 3000, 3500 L.reverse() print L 3500, 3000, 2500, 500 L.sort() print L 500, 2500, 3000, 3500 print len(L) 4 Note: Operator + & can also be applied on the lists. + is used to concatenate the two lists and is used to repeat the list given number of times. Example: l=10,20,30 m=40,50 l=l+m print l 10, 20, 30, 40, 50 b=m3 19Computer Science print b 40, 50, 40, 50, 40, 50 Dictionaries: A dictionary is like a list, but more in general. In a list, index value is an integer, while in a dictionary index value can be any other data type and are called keys. The key will be used as a string as it is easy to recall. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences and hence maintain no left-to-right order. Key-value pair: We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair. Syntax: my_dict = 'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen' Note: Dictionary is created by using curly brackets(ie. ). Dictionary methods: cmp( ) len( ) clear( ) get() has_key( ) items( ) keys() values() update() dict() Example: month=dict() print month month"one"="January" month"two"="Feb" print month 'two': 'Feb', 'one': 'January' len(month) 2 month.get("one") 'January' month.get("one","feb") 'January' month.keys() 'two', 'one' month.has_key("one") True 20