0% found this document useful (0 votes)
24 views

CP_Unit_1

Computer programing unit 1 nsut
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views

CP_Unit_1

Computer programing unit 1 nsut
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 6
PYTHON REVISION TOUR (12 Marks) Python is a widely used high-level programming language for general-purpose programming, created by Guido Van Rossum and first released in 1991. My first program in Python is: print(“Hello World”) Python shell can be used in two ways, viz interactive mode and ine mod Smallest individual unit in a program. 1, KEYWORDS Predefined words with special meaning to the language processor; reserved for special purpose and must not be used as normal identifiers names. Example - True, for, if, else, elif, from, is, and, or, break, continue, def, import etc. 2, IDENTIFIERS (1 mark) Names given to different parts of the program viz. variable, objects, classes, functions, _ lists, dictionaries and so forth. The naming rules: ‘© Must only be a non-keyword word with no space in between, Example: salary, maxmarks * Must be made up of only letters, numbers and underscore (_). Ex: salary, cs © Can not start with a number. They can contain numbers. Ex: exam21 Some valid identifiers are: Myfile MYFILE —Salary2021_ _Chk Invalid Identifies are: Myzfile break 2021salary if 3. LITERALS Data items that have a fixed value. 1. String Literals: are sequence of characters surrounded by quotes (single, double or triple) S1="Hello” $2="Hello” $3=”""Hello””” 2. Numerical Literals: are numeric values in decimal/octal/hexadecimal form. Di=10 D2=0056 (Octal) D3=0x12 (Hex) 3, Floating point literals: real numbers and may be written in fractional form (0.45) or exponent form (0.17E2). 4. Complex number literal: are of the form a+b}, where a, b are int/floats and |(or i) represents V=1 ie. imaginary number. Ex: C1=2+3} 5, Boolean Literals: It can have value True or False. Ex: b=False 6. Special Literal None: The None literal is used to indicate absence of value. Ex: c=None 4. OPERATORS (3 marks) Tokens that trigger some computation/action when applied to variables and other objects in an expression, These are Arithmetic Bitwise —:&%,| Identity is not Relational :>,>=,<, Logical nd, or Assignment Membership : in, not in Arithmetic assignment: / =, %=,**s, //= PRECEDENCE OF ARITHMETIC OPERATORS, PE(MD) (AS) = read PEMDAS P=parenthesis () > E=exponential M, D = multiplication and division > A, S=addition and subtraction Ex: 12*(3%4)//2+6 = 24 (Try at your end) 5, PUNCTUATORS Punctuators are symbols that are used to organize sentence structure. Common punctuators used in Python are: ‘“ # @ Means to identify type of data and set of valid operations for it. These are 1, NUMBERS To store and process different types of numeric data: Integer, Boolean, Floating-point, Complex no. 2. STRING Can hold any type of known characters ice. letters, numbers, and special characters, of any known, scripted language. It is immutable datatype means, the value can’t be changed at place. Example: “abed", “12345",/"This is India”, “SCHOOL”. 6 5-4 32d Si ce amon) Ron) er o 1 2 3 4 «5 3. LISTS (2 marks) Represents a group of comma-separated values of any datatype between square brackets. Examples: ist() , 2, 3, 4, 5] ieha’, 25, 36, 45] 45, 67, [34, 78, 87], 98] Inlist, the indexes are numbered from 0 to n-1, (n= total number of elements). List also supports forward and backward traversal. List is mutable datatype (its value can be changed at place) 4, TUPLE (1 mark) Group of comma-separated values of any data type within parenthesis. Tuple are immutable ie, non- changeable; one cannot make change to a tuple. t1=tuple() , 2, 3, 4,5) ‘34, 56, (52, 87, 34), 67, 'a’) 5, DICTIONARY (1 mark) The dictionary is an unordered set of comma separated key:value pairs, within { }, with the requirement that within a dictionary, no two keys can be the same, Following are some examples of dictionary: d4={(mo’:1, ‘name’/lakshay,,‘class':11} In dictionary, key is immutable whereas value is mutable. ‘STRING PROCESSING AND OTHER FUNCTIONS STRING REPLICATION When a string is multiplied by a number, string is replicated that number of times. Note: Other datatype - list and tuple also show the same behavior when multiplied by an integer number. >>> STREHT >>> print(STR*5) >>>HiHiiHiHi >>> L=[1, 2] >>> print{L*5) >>> [1,2,1,2,1,2,1,2,1,2] >>> t=(1, 2) >>> print(t*5) >>> (1,2,1,2,1,2,1,2,1,2) STRING SLICE (2 marks) String Slice refers to part of a string containing some contiguous characters from the string. The syntax is str_variable[start:end:step]. start: from which index number to start end: upto (end-1) index number characters will be extracted step: is step value. (optional) By default it is 1 Example : Suppose S='KENDRIYA’ Backward]- |- |- ]- |- |- |- Indexno | |7 |6 |5 [4 |3 Character |K |E |N [DR [1 |y [a Forward Indexno |o/1|2/3]4/5/)6|7 IN Command | Output KENDRIYA Explanation Will printentire string, KENDRIVA | Will printentire string KENDRIYA | Will printentire string N Will print element at index no 2. [2:6] NDRI From index number 2 to (6-1) i. 5. [16:2] | EDT From index 1 to 5 every 2"4 letter. ‘S[:2] KNRY From start to end .. every 2"4 letter. ‘S[:3] KDY From start to end .. every 3" letter. AYIRDNEK | Will print reverse of the string Will print entire string except last letter St:-1]__ | KENDRIY St-l] A Will print only last letter DRIYA | From index no -5 to end of the string S[-7-4:]_| END From index no -7 to -5. OTHER FUNCTIONS length() istitle() startswith() endswith() count(word) isspace() swapcase() find() IstripQ) strip) strip) CREATING LIST 1) Empty List >>eL=[] OR >>> Lelist() 2) From existing sequence >>>st="HELLO’ >>> L1zlist(st) # from a string >>> t=(1, 2, 3) >>> L2=list(t) # from a tuple 3) from Keyboard entering element one by one >>> L=[] >>> for iin range(5): nzint(input(‘Enter a number :')) Lappend(n) ‘TRAVERSING A LIST >>> Le(1, 2,3, 4,5] >>> for nin Li print(n) JOINING LISTS >>> L1=[1, 2, 3] >>> L2=[33, 44, 55] >>> L1+ 12 # output: (1, 2, 3, 33, 44, 55) SLICING THE LIST (1 mark) >>> L=[10, 11, 12, 13, 14, 15, 16, 18] # it will take from index no 2 to (6-1) ie. 5 >>>seq # output: (12, 13, 14, 15] General syntax for slicing is L[start ; end : step] APPENDING ELEMENT >>> L=[10, 11, 12] >>>L.append(20) — # Will append 20 at last >>> # output : [10, 11, 12, 20] >>>L.append((4,5]) # Appended data will be treated as asingle element sn # output: (10, 11, 12, 20, [4, 5]] EXPANDING LIST >>> L=(10, 11, 12] >>al.extend([44,55]) # Will extend given item as separate elements J # output: (10, 11, 12, 44, 55] UPDATING LIST >>> L=[10, 11, 12] # Suppose we want to change 11 to 50 >>> L[1]=50 >>>L # output: [10, 50, 12] DELETING ELEMENTS del List{index}# Will delete the item at given index del List[start : end}## Will delete from index no start to (end-1) >>> L=[x for x in range(1,11)] >>>, # list is (1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> del L[2:5] >>> # now listis [1, 2, 6, 7, 8, 9, 10] OTHER FUNCTIONS 1 mark) Ten() clear() | sum(List)_| | pop(index) remove() | min(List) insert(pos, value) _| sort() max(List) index(value) pop() count() Tuples (is immutable) We can not change value in place. List (Mutable) ‘we can change the value in place Dictionaries are a collection of some unordered key:value pairs; are indexed by keys (keys must be of any non-mutable type). ‘TRAVERSING A DICTIONARY >>> d={1:'one’, 2:'two’, 3:'three’) >>> for key in d: print(key, "”, d{key}, sep="\t’) l:one 2:two 3: three ADDING ELEMENT TO DICTIONARY >>>d[4]=four _# will add a new element >>> print(d) {1s ‘one’, 2: ‘two’, ‘three’, 4: four’) BIKVS - Regional Offi DELETING ELEMENTS FROM DICTIONARY >>> del d[3] # will delete entire key:value whose key is 3 >>> print(d)_# op: {1: one’, 2: ‘two’, 4: four’) OTHER FUNCTIONS Here is.a list of functions to recall them which work on dictionaries. pop(key) Ten) values() items() keys() update() WORKING WITH FUNCTIONS Block of statement(s) for doing a specific task. Advantages of function: > Cope-up with complexity > Hiding details - Abstraction > Fewer lines of code - lessor scope for bugs > Increase program readability > Re-usability of the code In python, a function may be declared as: def function_name([Parameter list]) : “"Doc-string ie. documentation of fir Body of the function return value Remember: Implicitly, Python returns None, which is also a built-in, immutable data type. >>> def f(a,b) lemo of a function”” +b return >>>f(10, 20) # calling of function def is a keyword to declare a function fis the name of the function a, b~ parameter argument of the function return is a keyword Functions can be categorized in three types: 1. Built-in function 2. Modules _ 3. User-defined #doc-string > Pre-defined functions available in Python. > Need not import any module (file). > Example of some built-in functions are: strQ, eval(), input(), min(), max(), abs(), e(), len(), round(), range(), dir(), he) > Module in Python is a file (name.py) which contains the definition of variables and functions. A module may be used in other programs. We can use any module in two ways 1. import 2. from import Some well-known modules are: math, random, matplotlib, numpy, pandas, datetime JAIPUR | Session e, 2020-21 ‘USER-DEFINED FUNCTIONS = > UDFsare the functions which are created by the user as per requirement. > After creating them, we can call them in any part of the program. > Use ‘def keyword for UDF. Formal Parameter appear in function definition Actual Parameter appear in function call statement. Example: def findSum(a, b): _ #a, b formal parameter print("The sum is ‘,(a+b)) #main-program 0,30 ees 4 #X, Yare actual parameer > Arguments are local > Variable inside functions are local > If variable is not defined , look in parent scope > Use the global statement to assign to global variables Python supports four types of arguments: 1. Positional 2 Default 3. Keyword 4. Variable Length 1. POSITIONAL ARGUMENTS Arguments passed to function in correct positional order. If we change the position of their order, then the result will change. >>> def subtract(a, b): print(a-b) >>> subtract(25, 10) # output: 15, >>> subtract(10, 25) # output: - 15 2. DEFAULT ARGUMENTS To provide default values to positional arguments; If value is not passed, then default values used. Remember - If we are passing default arguments, then do not take non-default arguments, otherwise it will result in an error. def findSum(a=30, b=20, c=10): print('Sum is ,(a+b+e)) 0, b=20, c): print('Sum is ',(a+b+c)) #Error that non-default argument follows default, arguments #main-program p,q, =100, 200, 300 findSum(p,qr) _ #output - Sum is 600 findSum(p,q) output - Sum is 310 findSum(r) #output - Sum is 330 findSum(,r) output - Sum is 510 findSum() #output -Sum is 60 3, KEYWORD ARGUMENTS we can pass arguments value by keyword, Le. by passing parameter name to change the sequence of arguments, instead of their position. Example: int_kv(kvnm, ronm): print(kvname,'comes under’ roname, region’) #main-program print_kv(kvnm='Rly Gandhi a pur’, kvnm="Bharatpur’) 4, VARIABLE LENGTH ARGUMENTS In certain situations, we can pass variable number of arguments to a function. Such types of arguments are called variable length argument. They are declared with * (asterisk) symbol. def findSum(*n) sm=0 fori inn: sm=sm+i print('Sum is ',sm) #main-program findSum() #output - Sum is 0 findSum(10) output - Sum is 10 Beds 10,20, im ovina Sum is 60 def countVowel(s): vow="AEIOUaeiou' ctr=0 for chin s: ifch in vow: ctr=ctr+1 print(Number of vowels in’, #main-program data=input(‘Enter a word to count vowels :') countVowel(data ham’, ronm='Ahmd’) sare’, ctr) def calAverage(L): sm=0 for i in range(len(L)): sm=sm+L[i] av=sm/len(L) return av #main-program marks=[25, 35, 32, 36, 28] print(’Marks are :'marks) avg=calAverage(marks) print("The average is’, avg) | PASSING TUPLES TO FUNCTION def midPoint(tt, t2): m=((t1[0]+t2[0})/2.0, (t1[4]+t2[1))/2.0) return m #main-program mp=midPoint(p1,p2) print("The Mid-Point of s', mp) FUNCTIONS USING LIBRARIES Math library (import math) (1 mark) Function [Description __| Example pi value of pi 3.14159 ceil(x) integer >=x | ceil 1.2) > 2.0 floor(x) __| integer <=x__| floor(1.2) > 1.0 pow(xy) | xraise y pow(3,2) >9 sqrt(n) square root | sqrt(2)> 1.414 String library (1 mark) PASSING DICTIONARY TO FUNCTION _ | | capitalize() [ Convert ist letter to upper case def printMe(d): index(ch) | Return index-no of Ist occurrence ™"Bunction to print values of given | [isalnum() _| True, if entire string is (a-2, A-Z, 0-9) dictionary isalpha() _ | True, if entire string is (a-z, AZ) for key in isdigit() | True, if entire string is (0-9) print(d{key|) islower() __| True, if entire string is in lower isupper() | True, if entire string is in upper #main-program TenQ) Return length of the string d=(1:'mon', 2:'tue', 3:'wed! } printMe(d) Random library (import random) (2 Marks) random() Return floating value between 0 and 1. randrange(0.N) This generates integer number from 0 to (N-1). randint(a, b) Return any number b/w given number a and b including them uuniform(a, b) Return floating number b/w given numbers aand b. Sno [ Question Answer 1_| Find the invalid identifier(s) from the following: b) True, as itis a keyword a) MyName b) True c) 2ndName, Because it is starting ¢) 2ndName d) My_Name with a digit. 2_ | Given the lists L=[1, 3, 6, 82, 5, 7, 11, 92], [6,82,5], as it will start from index no write the output of print(L[2:5)). 2to (5-1) ie. 4. 3 | Identify the valid arithmetic operator in Python from | c)** as itis used to find power the following: a)? b)< d) and 4 | Suppose tuple Tis T= (10, 12, 43, 39), Find incorrect? | b) T[2]= -29 (as tuple is immutable a) print(T[1]) b) T[2] =-29 and we can’t change its value) c) print(max(T)) d) print(len(T)) 5 | Declare a dictionary Colour, whose keys are 1, 2, 3 | Colour=(1:'Red’, 2:'Green’, 3:'Blue’} and values are Red, Green and Blue respectively. © | Atuple is declared asT = (2, 5, 6,9, 8) Tt will give the sum ofall elements of What will be the value of sum(T)? tuple i.e, 2+5+6+9+8 = 30 7 | Name the built-in mathematical function / method | abs() that is used to return an absolute value of a number. 8 | Identify declaration of L = [‘Mon','23",Bye’, '6.5'] ) list, asa list is collection of a) dictionary _b) string c)tuple —_d) list__| heterogeneous data. 9 | Find the output of the following code? It will print string from index no 3 to >>>name="ComputerSciencewithPython" (10-1) ie. 9 means 7 characters. So >>>print(name[3:10]) ‘outout will be puterSe 10 Write the full form of IDLE. Integrated Development Learning Environment cy Find the output: >>>A =[17, 24, 15, 30] >>>A.insert(2, 33) >>>print (A[-4]) ‘Ainsert(2,33) will insert 33 at index no 2. Now the list is [17, 24, 33, 15, 30]. So print(A[-4)) will start counting from last element starting from -1, -2... Hence will give 24. 12 imported to invoke the following functions: (a) ceil) (b) randrangeQ) Name the Python Library modules which need to be (a) math (b) random 13 What will be the result of the following code? popdl = {"abc" :5, “def” : 6, “ghi” : 7} >>>print (d1[0]) (a) abe (b)S (c) {“abe":5} (4) Error (@ Error, because dictionary works on the principle of key:value. These no key as 0, so it will produce an error. 14 ‘STR="VIBGYOR’ colors=list(STR) >>>del colors[4] >>>colors.remove("B") >>>colors.pop(3) >>>print(colors) It will create a list as colors=['V’, ,'B’,'G’,'Y,'0', 'R'] del colors[4] will delete the element at index no 4 ie. so list will be ['V','T, colors.remove("B") i, 'R']. colors.pop(3) will " So finally colors will be [V!,'T, ‘GR’. 15 ‘Suppose list Lis declared as L= [5 *i for iin range (0,4)], list Lis a) (0,1, 2,3) b) [0, 1,2, 3, 4] ©) [0, 5, 10, 15) d) (0,5, 10, 15, 20] Itis List Comprehension. Expression L = [i for iin range (0,4)] will generate [0, 1, 2, 3]. Since here we are writing S*i, so correct answer will be c) [0, 5, 10, 15] Sno | Question ‘Answer 1 | Find possible o/p (s) at the time of execution of the | Lower = r.randint(1,3) means Lower will program from the following code? Also specify the | have value 1,2, or 3 maximum values of variables Lower and Upper. | Upper =r.randint(2,4) means Upper will import random as r have value 2, 3, or 4 AR=[20, 30, 40, 50, 60, 70]; So K will be from (1, 2, 3) to (2, 3, 4) Lower =r.randint(1,3) Means if K=1, then upper limit (2,3,4) Upper =r.randint(2,4) If K=2, then upper limit (2,3,4) for K in range(Lower, Upper +1): If K=3, then upper limit (2,3,4) print (AR[K],end="#") (i) 10#40#70# (ii) 30#40#50# | So correct answer (ii) 30#40#50# (iii) 50#60#708 (iv) 40#50870# 2. | Write a function Lshift(Arr,n), which accepts a list | def LShift(Arr, n): Arr of numbers and n is a numeric value by which | L=Arr{n:] + Arr[:n] all elements of the list are shifted to left. return L Sample Input Data of the list Arr= [10,20,30,40,12,11] Arr= [ 10,20,30,40,12,11], n=2 n=: Output: Li=LShift(Arrn) Arr = [30,40,12,11,10,20] print(L1) 3 |Write a function in python _ named | def SwapHalfList(Array): SwapHalfList(Array), which accepts a list Array of | mid=len(Array)//2 numbers and swaps the elements of 1st Half of the | _ifsum(Array[:mid]) > sum(Array{mid:]): print(Arrayfmid:] + Arrayf:mid])

You might also like