12_computerscience_eng_sm_2024_231221_220606.pdf

Document Details

LucidWhite9591

Uploaded by LucidWhite9591

GBSSS

2023

CBSE

Tags

computer science python programming data structures

Full Transcript

List of group leader and subject – experts for preparation of support material Class – Xii (2023-24) Subject: Computer Science 1. Mr. Ravi Kant Principal GBSSS ,Hastsal , Delhi (1618058) 2. Ms. Preeti Dalal Lecturer...

List of group leader and subject – experts for preparation of support material Class – Xii (2023-24) Subject: Computer Science 1. Mr. Ravi Kant Principal GBSSS ,Hastsal , Delhi (1618058) 2. Ms. Preeti Dalal Lecturer Computer Science Govt. Co-ed SSS, Sec 2 Dwarka (1821029) 3. Ms. Ruby Rana Lecturer Computer Science , SBV Ashok Nagar (1515002) 4. Mr. Anuj Kumar Lecturer Computer Science , Dagar G Co.ed SV,Jaffarpur kalan (1822055) 5. Mr. Rohit Ahlawat Lecturer Computer Science , GBSSS ,Hastsal (1618058) 6. Mr. Sunny Dagar Lecturer Computer Science GBSSS No 3, Najafgarh (1822057) 7. Mr. Vinay Gahlot Lecturer Computer Science GBSSS No 1, Najafgarh ( 1822063) S.No Chapters Page No. 1 Python revision tour 1-21 2 Functions 22-49 3 Exception Handing 50-61 4 File Handling 62-101 5 Data Structures 102-112 6 Computer Networks 113-156 7 Database Management system 157-224 8 CBSE Previous Year Question Paper 2023 225-239 9 CBSE Sample paper 2023-24 239-270 10 Practice set 1 (unsolved) 271-278 11 Practice set 2 ( unsolved) 279-287 1|Page CHAPTER- 1 PYTHON REVISION TOUR ABOUT PYTHON: 1. Python is a high-level programming language developed by Guido Van Rossum. The language was released in February 1991 and got its name from a BBC comedy series “Monty Python’s Flying Circus”. 2. It is an interpreted and platform independent language i.e. the same code can run on any operating system. 3. It can be used to follow both procedural and object-oriented approaches to programming. 4. It is free to use and based on two programming languages: ABC language and Modula-3. BASIC TERMS USED IN PYTHON: 1. Token / Lexical Unit: The smallest individual unit in a python program is known as Token or Lexical Unit. A token has a specific meaning for a python interpreter. Examples of tokens are: Keywords, Identifiers, Literals, Operators and Punctuators. 2. Keywords: Keywords are the reserved words and have special meaning for Python Interpreters. Each keyword can be used only for that purpose which it has been assigned. Examples: and, while, del, with, True, None, False, return, try etc. 3. Identifiers: These are the names given to variables, objects, classes or functions etc. there are some predefined rules for forming identifiers which should be followed else the program will raise Syntax Error. 2|Page 4. Literals: The data items that have a fixed value are called Literals. If a data item holds numeric values it will be known as Numeric Literal, if it contains String values it will be known as String Literal and so on. It means the type of value stored by the data item will decide the type of Literal. Python has one special literal which is None to indicate absence of value. 5. Operators: These are the symbols that perform specific operations on some variables. Operators operate on operands. Some operators require two operands and some require only one operand to operate. The operator precedence in Python is as follows: NOTE: When we compare two variables pointing to same value, then both Equality (==) and identity (is) will return True. But when same value is assigned to different objects, then == operator will return True and is operator will return False. 6. Punctuators: These are the symbols that are used to organize sentence structure in programming languages. Common punctuators are: ‘ ‘’ # $ @ [] {} = : ; () ,. 7. Variables: In Python, variables are not storage containers like other programming languages. These are the temporary memory locations used to store values which will be used in the program further. Each time we assign a new value to a variable it will point to a new memory location where the assigned value is stored. In Python we do not specify the size and type of variable, besides these are decided as per the value we assign to that variable. 8. Data Type: It specifies the type of data we will store in the variable according to which memory will be allocated to that variable and it will also specify the type of operations that can be performed on that variable. Examples: integer, string, float, list etc. 3|Page 9. Dynamic Typing: It means that it will be decided at the run time that which type of value the variable will store. It is also called implicit conversion. For example, Here, we need not to specify the type of value a will store besides we can assign any type of value to a directly. Similarly, the data type of c will be decided at run time on the basis of value of a and b. 10. Type Casting: In Type casting, the data type conversion of a variable is done explicitly by using some built-in functions. Here, we can say that we force the variable by applying a built-in function to change the data type and it is not done at run time. Some common type casting functions are int(), float(), str(), list(), tuple(), dict() etc. DATA TYPES IN PYTHON: 4|Page Above data types are classified in two basic categories: Mutable data types and Immutable data types. Mutable data types are those data types whose value can be changed without creating a new object. It means mutable data types hold a specific memory location and changes are made directly to that memory location. Immutable data types are those data types whose value cannot be changed after they are created. It means that if we make any change in the immutable data object then it will be assigned a new memory location. 1. In Numeric data types, Integers allow storing whole numbers only which can be positive or negative. Floating point numbers are used for storing numbers having fractional parts like temperature, area etc. In Python, Floating point numbers represent double precision i.e. 15-digit precision. Complex numbers are stored in python in the form of A + Bj where A is the real part and B is the imaginary part of complex numbers. 2. Dictionary is an unordered set of comma separated values where each value is a key:value pair. We represent the dictionary using curly brackets {}. Keys in the dictionary should be unique and they cannot be changed while values of the keys can be changed. 3. Boolean allows to store only two values True and False where True means 1 and False means 0 internally. 4. Sequence data types store a collection or set of values in an ordered manner. We can traverse the values/elements using indexing. The sequence data types are: A. STRING: In Python, string is a sequence having Unicode characters. Any value written/assigned in “ “ or ‘ ‘ is considered as a string in python. Each character is at a particular place called Index having starting value 0 if traversing forward. Indexing can also be done in backward direction starting from the last element/character of string where starting value will be -1 in backward direction. Strings are immutable. Joining operation in a string can be done between two strings only. We cannot join a number and a string using ‘+’. Concatenation operation in a string can be done between a string and a number only using ‘*’. Slicing is defined as extracting a part of string from the main string using unique index positions starting from 0. In slicing we can specify start, stop and step values to extract substring from the given string. 5|Page B. LIST: Lists can hold multiple elements of the same or different data types. Lists are mutable in nature which means the values can be updated without assigning a new memory location. It is denoted by square brackets []. ‘for’ loop can be used to traverse a list. We can add (join) a list with another list only and not with int, float or string type. Joining of 2 or more can be done using ‘+’. We can concatenate a list with an integer only. Concatenation (Replication) can be done in a list using ‘*’. Slicing means extracting a part of list. Slicing in a list is done in same way as in String. C. TUPLE: Tuples can also hold multiple elements of the same or different data types like lists but tuples are immutable in nature. These are denoted by round brackets (). If multiple values are assigned to a single variable then by default the type of variable will be tuple. Tuples can be traversed in same way as Strings using ‘for’ loop. Slicing, Concatenation (Replication) and Joining operations can also be performed on Tuples in same way as of Strings. 6|Page WIDELY USED BUILT-IN FUNCTIONS IN PYTHON: STRING FUNCTIONS: len (string) It returns the number of characters in any string including spaces. capitalize() It is used to convert the first letter of sentences in capital letter. title() It is used to convert first letter of every word in string in capital letters. upper() It is used to convert the entire string in capital case letters. lower() It is used to convert entire string in small case letters. count(substring, It is used to find the number of occurrences of substring in a string. [start], [end]) We can also specify starting and ending index to specify a range for searching substring. find(substring, This function returns the starting index position of substring in the [start],[end]) given string. Like count(), we can specify the range for searching using starting and ending index. It returns -1 if substring not found. index(substring) It returns the starting index position of substring. If substring not found then it will return an error “Substring not found”. isalnum() It is used to check if all the elements in the string are alphanumeric or not. It returns either True or False. islower() It returns True if all the elements in string are in lower case, otherwise returns False. isupper() It returns True if all the elements in string are in upper case, otherwise returns False. isspace() It returns True if all the elements in string are spaces, otherwise returns False. isalpha() It returns True if all the elements in string are alphabets, otherwise returns False. isdigit() It returns True if all the elements in string are digits, otherwise returns False. split([sep]) This function is used to split the string based on delimiter/separator value which is space by default. It returns a list of n elements where the value of n is based on delimiter. The delimiter is not included in the output. partition(sep) It divides the string in three parts: head, separator and tail, based on the sep value which acts as a delimiter in this function. It will always return a tuple of 3 elements. The delimiter/separator will be included as 2nd element of tuple in the output. replace(old, It is used to replace old substring inside the string with a new value. new) strip([chars]) It returns a copy of string after removing leading and trailing white spaces by default. We can also provide chars value if we want to remove characters instead of spaces. If chars is given then all possible combination of given characters will be checked and removed. lstrip([chars]) It returns a copy of string after removing leading white spaces. If chars value is given then characters will be removed. rstrip([chars]) It returns a copy of string after removing trailing white spaces. If chars value is given then characters will be removed. 7|Page LIST FUNCTIONS: index() Used to get the index of first matched item from the list. It returns index value of item to search. If item not found, it will return ValueError: n is not in the list. append() Used to add items to the end of the list. It will add the new item but not return any value extend() Used for adding multiple items. With extend we can add multiple elements but only in form of a list to any list. Even if we want to add single element it will be passed as an element of a list. insert() Used to add elements to list at position of our choice i.e. we can add new element anywhere in the list. pop() Used to remove item from list. It raises an exception if the list is already empty. By default, last item will be deleted from list. If index is provided then the given indexed value will be deleted. remove() Used to remove an element when index is not known and we want to delete by provided the element value itself. It will remove first occurrence of given item from list and return error if there is no such item in the list. It will not return any value. clear() Use to remove all the items of a list at once and list will become empty. Del del statement is used to delete the structure of existing list. count() Used to count the number of occurrences of the item we passed as argument. If item does not exist in list, it returns Zero. reverse() Used to reverse the items of a list. It made the changes in the original list and does not return anything. sort() Used to sort the items of a list. It made the changes in the original list and sort the items in increasing order by default. We can specify reverse argument as True to sort in decreasing order. sorted() Used to sort the items of a sequence data type and returns a list after sorting in increasing order by default. We can specify reverse argument as True to sort in decreasing order. TUPLE FUNCTIONS: len() Returns number of elements in a tuple max() Returns the element having maximum value in the tuple min() Returns the element having minimum value index() Returns index value of given element in the tuple. It item doesn’t exist, it will raise ValueError exception. count() It returns the number of occurrences of the item passed as an argument. If not found, it returns Zero. 8|Page sorted() Used to sort the items of a sequence data type and returns a list after sorting in increasing order by default. We can specify reverse argument as True to sort in decreasing order. Dictionary Functions: clear() Used to remove all items from dictionary get() Used to access the value of given key, if key not found it raises an exception. items() Used to return all the items of a dictionary in form of tuples. keys() Used to return all the keys in the dictionary as a sequence of keys. values() Used to return all the values in the dictionary as a sequence of values. update() Merges the key:value pair from the new dictionary into original dictionary. The key:value pairs will be added to the original dictionary, if any key already exists, the new value will be updated for that key. fromkeys() Returns new dictionary with the given set of elements as the keys of the dictionary. copy() It will create a copy of dictionary. popitem() Used to remove the last added dictionary item (key:value pair) max() Used to return highest value in dictionary, this will work only if all the values in dictionary are of numeric type. min() Used to return lowest value in dictionary, this will work only if all the values in dictionary are of numeric type. sorted() Used to sort the key:value pair of dictionary in either ascending or descending order based on the keys. Statements in Python: Instructions given to computer to perform any task are called Statements. In Python, we have 3 type of statements: EMPTY STATEMENTS: When a statement is required as per syntax but we don’t want to execute anything or do not want to take any action we use pass keyword. Whenever pass is encountered, python interpreter will do nothing and control will move to the next statement in flow of control. SIMPLE STATEMENT: All the single executable statements in Python are Simple Statements. COMPOUND STATEMENTS: A group of statements executed as a unit are called compound statements. Compound statements has a Header which begins with a 9|Page keyword and ends with colon (:). There can be at least one or more statements in the body of the compound statement, all indented at same level. Conditional statements in Python: When the execution of any statement depends on some condition then such statements are considered as Conditional Statements. In Python, we use if keyword for Conditional statements. It must contain valid condition which evaluates to either True or False. Condition must follow by Colon (:), it is mandatory. Statement inside if must be at same indentation level. if statement can be of many forms:  if without false statement  if with else  if with elif  Nested if Iterative statements in Python: In Python, to perform repetition we have two keywords, for (Counting Loop) and while (Conditional Loop) 10 | P a g e for loop in python is used when we know the number of iterations. for loop is used to create loop where we are working on sequence data types. To repeat the loop n number of times in for loop we use range function in which we can specify lower limit and upper limit. range function will generate set of values from lower limit to upper limit. We can also specify the step value which is +1 by default. Step value can be in -ve also to generate set of numbers in reverse orders. while loop in python is also called as entry-controlled loop in which entry is loop is allowed only if the condition is true. There are 4 main elements of while loop: Initialization: In while loop, we cannot use a variable in test condition without initializing it with a starting value. So, we will specify the starting value to the variable to be used in loop. Test Condition: We will specify a test condition in the header of the loop. If this condition will be True then only the body of the loop will be executed else the loop will not get executed at all. Body of loop: We will write the statements to be executed if the test condition will be True. Update Statement: In while loop, we have to increase and decrease the value of variable used in test condition else the loop will result in infinite loop. break keyword is used to take control out of the loop for any given condition. When break is encountered in a loop the flow of control jumps to the very next statement after the loop. continue keyword is used to skip the execution of remaining statements inside the loop and takes control to next iteration.. 11 | P a g e MULTIPLE CHOICE QUESTION 1 Find the invalid identifier from the following a) None b) address c) Name d) pass 2 Write the type of tokens from the following: a) If b) roll_no 3 Consider a declaration L = (1, 'Python', '3.14'). Which of the following represents the data type of L? a) List b) Tuple c) Dictionary d) String 4 Identify the valid arithmetic operator in Python from the following. a) ? b) < c) ** d) And 5 Which of the following statements is/are not python keywords? a) False b) Math c) WHILE d) Break 6 Which of the following is a valid keyword in Python? a) False b) return c) non_local d) none 7 State True or False. "Identifiers are names used to identify a variable, function in a program". 8 Identify the invalid identifier out of the options given below. a) Qwer_12 b) IF c) Play123 d) Turn.over 9 One of the following statements will raise error. Identify the statement that will raise the error. 12 | P a g e a) b) c) d) None of above will raise error 10 Given the following Tuple Tup (10, 20, 30, 50) Which of the following statements will result in an error? a) print (Tup ) b) print (Tup [1:2]) c) Tup.insert (2,3) d) print(len (Tup)) 11 Consider the given expression : 57 or not 7>4 Which of the following will be the correct output, if the given expression is evaluated? a) True b) False c) NULL d) NONE 12 Which of the following will give output as [5,14,6] if lst=[1,5,9,14,2,6]? a) print(lst[0::2]) b) print(lst[1::2]) c) print(lst[1:5:2]) d) print(lst[0:6:2]) 13 The return type of the input() function is a) string b) Integer c) list d) tuple 14 Which of the following operator cannot be used with string data type? a) + b) In c) * d) / 15 Consider a tuple tup1 = (10, 15, 25, and 30). Identify the statement that will result in an error. a) print(tup1) b) tup1 = 20 c) print(min(tup1)) d) print(len(tup1)) 16 Which one of the following is the default extension of a Python file? a).exe b).p++ 13 | P a g e c).py d).p 17 Which of the following symbol is used in Python for single line comment? a) / b) /* c) // d) # 18 Which of these about a dictionary is false? a) The values of a dictionary can be accessed using keys b) The keys of a dictionary can be accessed using values c) Dictionaries aren’t ordered d) Dictionaries are mutable 19 Which is the correct form of declaration of dictionary? a) Day={1:’monday’,2:’tuesday’,3:’wednesday’} b) Day=(1;’monday’,2;’tuesday’,3;’wednesday’) c) Day=[1:’monday’,2:’tuesday’,3:’wednesday’] d) Day={1’monday’,2’tuesday’,3’wednesday’] 20 What will be the output of the following statement: print(3-2**2**3+99/11) a) 244 b) 244.0 c) -244.0 d) Error 21 What is the output of following code: T=(100) print(T*2) a) Syntax error b) (200,) c) 200 d) (100,100) 22 Identify the output of the following Python statements: x = [[10.0, 11.0, 12.0],[13.0, 14.0, 15.0]] y = x print(y) a) 12.0 b) 13.0 c) 14.0 d) 15.0 23 Select the correct output of the code : S= "Amrit Mahotsav @ 75" A=S.partition (" ") print (a) a) ('Amrit Mahotsav', '@', '75') b) ['Amrit', 'Mahotsav', '@', '75'] c) ('Amrit', 'Mahotsav @ 75') d) ('Amrit', '', 'Mahotsav @ 75') 14 | P a g e 24 Identify the output of the following Python statements. x=2 while x < 9: print(x, end='') x=x+1 a) 12345678 b) 123456789 c) 2345678 d) 23456789 25 Identify the output of the following Python statements. b=1 for a in range(1, 10, 2): b += a + 2 print(b) a) 31 b) 33 c) 36 d) 39 26 A tuple is declared as T = (2,5,6,9,8). What will be the value of sum(T)? 27 Identify the output of the following Python statements. lst1 = [10, 15, 20, 25, 30] lst1.insert( 3, 4) lst1.insert( 2, 3) print (lst1[-5]) a) 2 b) 3 c) 4 d) 20 28 Evaluate the following expression and identify the correct answer. 16 - (4 + 2) * 5 + 2**3 * 4 a) 54 b) 46 c) 18 d) 32 29 Fill in the blank. ________________function is used to arrange the elements of a list in ascending order. a) sort() b) ascending() c) arrange() d) asort() 15 | P a g e 30 Which of the following will delete key-value pair for key = “Red” from a dictionary D1? a) delete D1("Red") b) del D1["Red"] c) del.D1["Red"] d) D1.del["Red"] 31 Identify the valid declaration of L: L = [‘Mon’, ‘23’, ‘hello’, ’60.5’] a) dictionary b) string c) tuple d) list 32 Given a Tuple tup1= (10, 20, 30, 40, 50, 60, 70, 80, 90). What will be the output of print (tup1 [3:7:2])? a) (40,50,60,70,80) b) (40,50,60,70) c) [40,60] d) (40,60) 33 If the following code is executed, what will be the output of the following code? name="ComputerSciencewithPython" print(name[3:10]) 34 Which of the following statement(s) would give an error during execution of the following code? a) Statement 1 b) Statement 2 c) Statement 3 d) Statement 4 35 Consider the statements given below and then choose the correct output from the given options: pride="#G20 Presidency" print(pride[-2:2:-2]) a) ndsr b) ceieP0 c) ceieP d) yndsr 36 Given is a Python list declaration : Listofnames=["Aman", "Ankit", "Ashish", "Rajan", "Rajat"] 16 | P a g e Write the output of: print (Listofnames [-1:-4:-1]) 37 What will be the output of the following code: Cities=[‘Delhi’,’Mumbai’] Cities,Cities=Cities,Cities print(Cities) 38 What will be the output of the following code? tup1 = (1,2,[1,2],3) tup1=3.14 print(tup1) a) (1,2,[3.14,2],3) b) (1,2,[1,3.14],3) c) (1,2,[1,2],3.14) d) Error Message 39 Select the correct output of the code: a) PYTHON-IS-Fun b) PYTHON-is-Fun c) Python-is-fun d) PYTHON-Is –Fun 40 What will be the result of following python code? 41 For a string S declared as S=”PYTHON”, Which of the following is incorrect: a) N=len(s) b) T=S c) “T” in S d) S=”M” 42 Which of the following statement(s) would give an error after executing the following code? Stud={"Murugan":100,"Mithu":95} # Statement 1 print (Stud ) # Statement 2 Stud ["Murugan"]=99 # Statement 3 print (Stud.pop()) # Statement 4 17 | P a g e print (Stud) # Statement 5 a) Statement 2 b) Statement 4 c) Statement 3 d) Statements 2 and 4 43 What will be the output of following Python code? a) False b) True c) Error d) None 44 Write a statement in Python to declare a dictionary whose keys are 1, 2, 3 and values are Monday, Tuesday and Wednesday respectively. 45 Assertion(A): List is an immutable data type Reasoning(R): When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable is created by the same name in memory a) Both A and R are true and R is the correct explanation for A b) Both A and R are true and R is not the correct explanation for A c) A is True but R is False d) A is false but R is True 46 Assertion (A): Python Standard Library consists of various modules. Reasoning(R): A function in a module is used to simplify the code and avoids repetition. a) Both A and R are true and R is the correct explanation for A b) Both A and R are true and R is not the correct explanation for A c) A is True but R is False d) A is false but R is True 47 Assertion(A): List is an immutable data type Reasoning(R): When an attempt is made to update the value of an immutable variable, the old variable is destroyed and a new variable is created by the same name in memory. a) Both A and R are true and R is the correct explanation for A b) Both A and R are true and R is not the correct explanation for A c) A is True but R is False d) A is false but R is True 48 Assertion (A) : List can not become key in a dictionary. Reasoning(R) : Only integers can be keys in a dictionary. 18 | P a g e a) Both A and R are true and R is correct explanation of A b) Both A and R are true but R is not correct explanation of A c) A is True but R is false d) R is true but A is false Weightage : 2 marks 1 Rewrite the following code in python after removing all syntax error(s). Underline each correction done in the code. 30=To for K in range(0,To) IF k%4==0: print (K*4) Else: print (K+3) 2 Rewrite the following code after removing all syntax error(s) and underline each correction done: Runs=(10,5,0,2,4,3) for I in Runs: if I=0: print(Maiden Over) else: print(Not Maiden) 3 Evaluate the following Python expression: a) 2*3+4**2-5//2 b) 615) or (10>5) 4 Predict the output of the following code: S="LOST" L=[10,21,33,4] D={} for I in range(len(S)): if I%2==0: D[L.pop()]=S[I] else: D[L.pop()]=I+3 for K,V in D.items(): print(K,V,sep="*") 5 Write the Python statement for each of the following tasks using BUILT-IN functions/methods only: (i) To insert an element 200 at the third position, in the list L1. (ii) To check whether a string named, message ends with a full stop / period or not. 6 A list named studentAge stores age of students of a class. Write the Python command to import the required module and (using built-in function) to display the most common age value from the given list. 19 | P a g e Weightage : 3 marks 1 Find the output of the following code: Name="PythoN3.1" R="" for x in range(len(Name)): if Name[x].isupper(): R=R+Name[x].lower() elif Name[x].islower(): R=R+Name[x].upper() elif Name[x].isdigit(): R=R+Name[x-1] else: R=R+"#" print(R) 2 Predict the output of the Python code given below: Programming Practice 1 Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string. For example, if the string is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3) 2 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an argument and displays the names (in uppercase)of the places whose names are longer than 5 characters. For example, Consider the following dictionary PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"} The output should be: LONDON NEW YORK 3 Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a numeric value by which all elements of the list are shifted to left. Sample Input 20 | P a g e Data of the list Arr= [ 10,20,30,40,12,11], n=2 Output: Arr = [30,40,12,11,10,20] 21 | P a g e Topics to be covered 1. Introduction 2. Types of Functions 3. Create User Defined Function 4. Arguments And Parameters 5. Default Parameters 6. Positional Parameters 7. Function Returning Values 8. Flow of Execution 9. Scope of Variable 22 | P a g e Function Reusable block of code that performs a specific task. For example: len(), print(), min(), max(), sorted () , type() etc. Types of Functions Defining a function in Python: Name the function and specifies what to do when the function is called. Python interpreter ignores the function definition until the function is called. Calling a function: Calling the function actually performs the specified actions with the indicated parameters Function Definition in Python In Python a function is defined using the def keyword  Arguments: Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. 23 | P a g e Actual Parameters (Arguments) are values supplied to the function when it is invoked/called Formal Parameters are variables declared by the function that get values when the function is called. Example 1: Observe the following code: Output: In the above example, a user defined function “function1” has been defined that receives one argument. Once the function is defined, it can be called any number of times with different arguments. Formal argument: x Actual argument: “first call to function “ passed in first call “second call to function” passed in second call Example 2: Write a function ADD(A,B) that receives two integer arguments and prints their sum. Output: return keyword: In Python, the `return` keyword is used in functions to specify the value that the function will return when it is called. When a function is executed, it may perform some computations or operations, and the result can be sent back to the caller using the `return` statement. 24 | P a g e The basic syntax for using the `return` statement is as follows: Here's what you need to know about the `return` statement: 1. Returning a Value: When you want to return a specific value from the function, you can use the `return` statement followed by the value you want to return. Note: The function will stop executing immediately after the `return` statement is encountered, and the value will be passed back to the caller. 2. Returning Multiple Values: Python allows you to return multiple values from a function as a tuple. You can simply separate the values with commas after the `return` statement. 3. Returning None: If a function doesn't have a `return` statement or has a `return` statement without any value, it implicitly returns `None`. `None` is a special constant in Python that represents the absence of a value. 25 | P a g e 4. Early Exit with Return: You can use the `return` statement to exit a function early if certain conditions are met. This is useful when you want to terminate the function before reaching the end. The `return` statement is a powerful tool that enables functions to produce results and pass data back to the calling code. Understanding how to use it correctly will help you design and implement effective functions in Python. Scope of a variable: In Python, the scope of a variable refers to the region of the program where the variable is accessible. The scope determines where a variable is created, modified, and used. Global Scope: Variables defined outside of any function or block have a global scope. They are accessible from anywhere in the code, including inside functions. To create a global variable, you define it at the top level of your Python script or module. Local Scope: Variables defined inside a function have a local scope. They are accessible only within the function where they are defined. Local variables are created when the function is called and destroyed when the function returns. 26 | P a g e Points to be noted: When local variable and global variable have different names: global variable can be accessed inside the function When local and global variable have same name : priority is given to local copy of variable Lifetime of a variable: The lifetime of a variable in Python depends on its scope. Global variables persist throughout the program's execution, local variables within functions exist only during the function's execution. Study the following programs: Example 1: 27 | P a g e Example 2: Passing list as argument to the function: Please note that when a list if passed as arguments , the original copy of list is passed to the function i.e if any change is made at any index in the list inside the function , it is reflected in original list. That is because list is a mutable datatype and in Python, when you pass a list as an argument to a function, you are actually passing a reference to the list rather than a copy of the list. This means that the function parameter will point to the same memory location as the original list. As a result, any changes made to the list within the function will be reflected in the original list outside the function. However, if you assign a different list to a variable inside a function in Python, it will create a new local variable that is separate from any variables outside the function. This local variable will only exist within the scope of the function, and changes made to it won't affect the original list outside the function. 28 | P a g e Output: global keyword In Python, the global keyword is used to indicate that a variable declared inside a function should be treated as a global variable, rather than a local variable. When you assign a value to a variable inside a function, Python, by default, creates a local variable within that function's scope. However, if you need to modify a global variable from within a function, you must use the global keyword to specify that you want to work with the global variable instead. Here's the basic syntax for using the global keyword: For example: Types of arguments passed to a function: Positional Arguments: These are the most common type of arguments and are matched to the function parameters based on their positions. The first argument corresponds to the first parameter, the second argument corresponds to the second parameter, and so on. The number and order of positional arguments must match the function's parameter list. 29 | P a g e Default Arguments: Default arguments are used when a function is called with fewer arguments than there are parameters. The default values are specified in the function definition. If a value is not provided for a parameter during the function call, the default value is used. Keyword Arguments: In this type, each argument is preceded by a keyword (parameter name) followed by an equal sign. The order of keyword arguments does not matter, as they are matched to the function parameters based on their names. These arguments provide flexibility to call a function with arguments passed in any order. Python modules: In Python, a module is a file containing Python code that defines variables, functions, and classes. Modules allow you to organize and reuse code by breaking it into separate files, making it easier to maintain and understand complex programs. Python's standard library comes with a vast collection of built-in modules that cover various functionalities If needed, you can also create your own custom modules. To use a module in your Python code, you need to import it using the import statement. math module: 30 | P a g e The math module in Python is a built-in module that provides various mathematical functions and constants. It is part of the Python Standard Library i.e. it does not require any additional installation to use. To use the math module, you need to import it at the beginning of your Python script. Once you've imported the module, you can access its functions and constants using the math prefix. Here are some commonly used functions and constants provided by the math module: Mathematical Constants: math.pi: Represents the mathematical constant π (pi). math.e: Represents the mathematical constant e (Euler's number). Basic Mathematical Functions: math.sqrt(x): Returns the square root of x. math.pow(x, y): Returns x raised to the power y. math.exp(x): Returns the exponential of x (e^x). math.log(x, base): Returns the logarithm of x to the specified base (default base is e). Trigonometric Functions (all angles are in radians): math.sin(x), math.cos(x), math.tan(x): Sine, cosine, and tangent of x, respectively. math.asin(x), math.acos(x), math.atan(x): Arcsine, arccosine, and arctangent of x, respectively. Hyperbolic Functions: math.sinh(x), math.cosh(x), math.tanh(x): Hyperbolic sine, cosine, and tangent of x, respectively. Angular Conversion: math.degrees(x): Converts x from radians to degrees. math.radians(x): Converts x from degrees to radians. Miscellaneous: math.ceil(x): Returns the smallest integer greater than or equal to x. math.floor(x): Returns the largest integer less than or equal to x. math.factorial(x): Returns the factorial of x. Study the following examples: Example 1: 31 | P a g e Example 2: Example 3: Statistics module: The statistics module in Python is another built-in module that provides functions for working with statistical data. It offers a variety of statistical functions to compute measures like mean, median, standard deviation, variance, etc. The statistics module is part of the Python Standard Library, so there's no need to install any additional packages to use it. Here are some commonly used functions provided by the statistics module: statistics.mean(data): Calculates the arithmetic mean (average) of the data. statistics.median(data): Computes the median value of the data. statistics.mode(data): Finds the mode (most common value) in the data. Example 1: 32 | P a g e Example 2: random module The random module in Python is another built-in module that provides functions for generating random numbers, sequences, and making random choices. It is commonly used for tasks such as random number generation, random shuffling, and random sampling. Here are some commonly used functions provided by the random module: random.random(): Generates a random float number in the range [0.0, 1.0). random.uniform(a, b): Generates a random float number in the range [a, b). random.randint(a, b): Generates a random integer in the range [a, b] (inclusive). random.choice(sequence): Picks a random element from a sequence (list, tuple, string, etc.). random.shuffle(sequence): Shuffles the elements of a sequence randomly (in- place). Example 1: What is the possible outcome/s of following code? Possible options: a) green b) yellow 33 | P a g e c) blue d) orange Solution: Here, the possible values for variable random-sample are 3, 4 and 5. Hence, the possible Outputs of above code are b) Yellow and d) orange. Example 2: What are the possible output/s for the following code? Output Options: i. 29: 26:25 :28 : ii. 24: 28:25:26: iii. 29: 26:24 :28 : iv. 29: 26:25:26: Solution: Option iv Example 3: What are the possible outcome/s for the following code: Output Options: i. 103#102#101#100# ii. 100#101#102#103# iii. 100#101#102#103#104# iv. 4#103#102#101#100# Solution: Option i and option iv 34 | P a g e 1. What will be the output of the following code? a) 10 b) 30 c) error d) 20 2. Name the Python Library modules which need to be imported to invoke the following functions: a) sin() b) randint() 3. What is the scope of a variable defined inside a function? a) Global scope b) Local scope c) Universal scope d) Function scope 4. In Python, can a function return multiple values simultaneously? a) Yes b) No 5. What is the purpose of the "return" statement in a function? a) It specifies the type of the function. b) It defines the input parameters of the function. c) It indicates the end of a function. d) It returns a value from the function to the caller. 6. Which of the following module functions generates an integer? a) randint() b) uniform() c) random() d) all of these 7. The return type of the input() function is a) string b) integer c) list d) tuple 35 | P a g e 8. The values being passed through a function call statements are called a) Actual parameter b) Formal parameter c) default parameter d) None of these 9. Which of the following components are part of a function header in Python? a) Function Name b) Return Statement c) Parameter List d) Both a and c 10. Which of the following function header is correct? a) def cal_si(p=100, r, t=2) b) def cal_si(p=100, r=8, t) c) def cal_si(p, r=8, t) d) def cal_si(p, r=8, t=2) 11. Which of the following is the correct way to call a function? a) my_func() b) def my_func() c) return my_func d) call my_func() 12. Consider the code given below: Which of the following statements should be given in the blank for #Missing Statement, if the output produced is 110? a) global a b) global b=100 c) global b d) global a=100 13. What will be the output? 36 | P a g e a) 5 b) 6 c) 4 d) This code will raise an error. 14. A function is defined as below, the function call parameters can be: a) Two tuples b) Two numbers c) One number d) All of the above 15. Statistics.mode([10,10,11,12,14,11,11,15,15,16,15]) will return (consider module is imported) a) 10 b) 15 c) 11 d) Error 16. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to each of the variables Lower and Upper. a) 10#40#70# b) 30#40#50# c) 50#60#70# d) 40#50#70# 17. What will be the output of the Python code? >>> def testify(a,b): return a-b >>> sum=testify(22,55) >>> sum+30 a) 33 b) -33 c) 3 37 | P a g e d) -3 18. What will be the output of the following code? >>> def a(b=11, c=21): b += 13 c -= 13 return b+c 0.77 >>> print(a(25), a(35)) a) 15 18 b) 46 56 c) 25 35 d) 13 12 19. What will be the output of the following code? num=100 def showval(X): global num num = 85 if(X%2==0): num += X else: num -= X print(num,end="#") showval(33) print(num) a) 100#52 b) 85#52 c) 85#33 d) 185#52 20. Find the impossible option from the following >>> import random >>> L=[i for i in range(random.randint(3,5))] a) [0, 1, 2, 3] b) [0, 1, 2, 3, 4] c) [0, 1, 2, 3, 4, 5] d) [0, 1, 2] 21. Look at the function definition and the function call and determine the correct output >>> def test(a): if(a>10): a += 10 if(a>20): a += 20 if(a>30): 38 | P a g e a +=30 print(a) >>> test(11) a) 21 b) 72 c) 61 d) 71 22. Predict output: a) [1, 2, 3, 4, 5, 6] b) [100, 2, 3, 4, 5, 6] c) [100, 2, 3, 4, 5] d) [1, 2, 3, 4, 5] 23. Predict output: a) [1, 2, 3, 4] b) [5, 6, 7] c) [1, 2, 3, 4, 5, 6, 7] d) This code will raise an error. 24. Assertion (A): To use a function from a particular module, we need to import the module. Reason (R): import statement can be written anywhere in the program, before using a function from that module. a) Both A and R are true and R is the correct explanation for A b) Both A and R are true and R is not the correct explanation for A c) A is True but R is False d) A is false but R is True 39 | P a g e 25. What will be the output of the following Python code? def add (num1, num2): sum = num1 + num2 sum = add(20,30) print(sum) 26. Find and write the output of following python code: def Alter(M,N=45): M = M+N N = M-N print(M,"@",) return M A=Alter(20,30) print(A,"#") B=Alter(30) print(B,"#") 27. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to each of the variables FROM and TO. a) 10#40#70# b) 30#40#50# c) 50#60#70# d) 40#50#70# 28. Predict output: 40 | P a g e 29. Predict output: 30. Rewrite the following code after removing the syntactical errors (if any). Underline each correction. 31. What will be the output of the following code? def my_func(var1=100, var2=200): var1+=10 var2 = var2 - 10 return var1+var2 print(my_func(50),my_func()) 32. What will be the output of the following code? 33. What will be the possible outcomes: a) Delhi#Mumbai#Chennai#Kolkata# b) Mumbai#Chennai#Kolkata#Mumbai# c) Mumbai# Mumbai #Mumbai # Delhi# d) Mumbai# Mumbai #Chennai # Mumbai 41 | P a g e 34. What will be the output of the following code? 35. What is the output of the following code snippet? i. ii. 36. What will be the output of the following code? 37. Find and write the output of the following Python code: def Display(str): m="" for i in range(0,len(str)): if(str[i].isupper()): m=m+str[i].lower() elif str[i].islower(): m=m+str[i].upper() else: if i%2==0: m=m+str[i-1] else: m=m+"#" print(m) 42 | P a g e Display('[email protected]') 38. Find and write the output of the following python code: I ii 39. What are the possible outcome/(s) for the following code.Also specify the maximum and minimum value of R when K is assigned value as 2: a) Stop # Wait # Go b) Wait # Stop # c) Go # Wait # d) Go # Stop # 40. Write the output of the following Python code: 43 | P a g e 41. Explain the positional parameters in Python function with the help of suitable example. 42. Predict the output of following: i. ii. iii. iv. v vi 43. Predict output : 44. What possible outputs(s) will be obtained when the following code is executed? Options: a) RED* b) WHITE* WHITE* BLACK* BLACK* c) WHITE* WHITE* d) YELLOW* BLACK* BLACK* WHITE*WHITE* BLACK* BLACK* BLACK* 44 | P a g e 45. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to each of the variables BEGIN and END. a) 60#35# b) 60#35#70#50# c) 35#70#50# d) 40#55#60# 46. What possible outputs(s) are expected to be displayed on screen at the time of execution of the program from the following code? Also specify the maximum values that can be assigned to each of the variables Lower and Upper. a) 10#40#70# b) 30#40#50# c) 50#60#70# d) 40#50#70# 47. What are the possible outcome/s for the following code: Options: a) 34:31:30:33: b) 29:33:30:31: c) 34:31:30:31: d) 34:31:29:33: 45 | P a g e 48. What are the possible outcome/s : 1 Guess=65 for I in range(1,5): New=Guess+random.randint(0,I) print(chr(New),end=' ') Output Options: a) A B B C b) A C B A c) B C D A d) C A B D 2 Score=[ 25,20,34,56, 72, 63] Myscore = Score[2 + random.randint(0,2)] print(Myscore) Output Options : a) 25 b) 34 c) 20 d) None of the above 3 Marks = [99, 92, 94, 96, 93, 95] MyMarks = Marks [1 + random.randint(0,2) ] print(MyMarks) Output Options : a) 99 b) 94 c) 96 d) None of the above 4 Disp=22 Rnd=random.randint(0,Disp)+15 N=1 for I in range(3,Rnd,4): print(N,end=" ") N+=1 print() Output Options: a) 1 b) 1 2 3 4 c) 1 2 d) 1 2 3 46 | P a g e 5 Area=["NORTH","SOUTH","EAST","WEST"] for I in range(3): ToGo=random.randint(0,1) + 1 print(Area[ToGo],end=":") print() Output Options: a) SOUTH : EAST : SOUTH : b) NORTH : SOUTH : EAST : c) SOUTH : EAST : WEST : d) SOUTH : EAST : EAST : 6 MIN = 25 SCORE = 10 for i in range (1,5): Num = MIN + random.randint(0,SCORE) print(Num,end=":") SCORE-=1; print() Output Options: a) 34:31:30:33: b) 29:33:30:31: c) 34:31:30:31: d) 34:31:29:33: 49. Ms. Sana wants to increase the value of variable x by 1 through function modify(). However this code raises error.Help sana to rectify the code: 50. Predict output : i. ii. 47 | P a g e iii. iv. 51. What will be the output of the following code fragments: i. ii. iii. iv. 52. What will be the output of the following Python Code? 53. Predict output: 48 | P a g e 54. Predict output: i. ii. iii. iv. Practical Exercise 1 Write a Python function named `calculate_gross_salary` that takes the basic salary (an integer) as an argument and returns the gross salary. The gross salary is calculated as follows: - If the basic salary is less than or equal to 10000, the gross salary is the basic salary plus 20% of the basic salary. - If the basic salary is more than 10000, the gross salary is the basic salary plus 25% of the basic salary. Write the function definition for `calculate_gross_salary` and use it to calculate the gross salary for a basic salary of 12000. 2 Write a Python function called calculate_average that takes a list of numbers as input and returns the average of those numbers. 3 Write a function update_list(L) that receives a list as arguments and increases the value of even elements by 2. For example: if the list is [2,4,6,7,9] after execution of function, the list should be : [4,6,8,7,9] 49 | P a g e Topics to be covered 1. Introduction 2. Types of errors 3. Handling Exceptions Using Try – Except – Finally Blocks 50 | P a g e EXCEPTION HANDLING While executing a Python program, it may happen that the program does not execute at all or it can generate unexpected output. This happens when there are syntax errors, run time errors, logical errors or any semantic errors in the code. S SYNTAX ERROR SEMANTIC ERROR LOGICAL ERROR RUN TIME ERROR It occurs when we put It occurs when the code It may occur when It occurs at the time of some incorrect is correct according to there may be some program execution. punctuation, incorrect syntax but it is not improper sequence of Such errors produce word sequence or there meaningful. The code statements or incorrect output for are some undefined will not behave as incorrect use of specific values of input. terms or missing expected. operator. It will not These errors are also parenthesis. For example: stop a program from called Exceptions, Syntax errors are also A = 10 executing but will which occur when called as Parsing errors. B = ”hello” produce incorrect something unexpected For example: Result = A + B output. It will happens leading to stop >>> p=2(num1+num2) Here, The code will generate incorrect the program execution. This statement is execute as it has correct output for every value For example: mathematically correct syntax but will not of input. 5. Division by zero but python interpreter generate expected For example: 6. Finding square will raise SYNTAX error output. If we want to find sum root of negative as there is no sign of two numbers and number. present between 2 and write the following 7. Insufficient parenthesis. The correct code: memory available statement will be: A, B = 10, 15 on computer. >>> p=2*(num1+num2) C=A*B 8. Trying to open a print (“Sum is: “, C) file that does not Here, the code will exist. generate A * B but we wanted to find Sum. Hence it is a logical error. EXCEPTIONS: 11. Run time errors are known as Exceptions. 12. When an Exception is generated, the program execution is stopped. 13. Removing errors from a code is referred to as EXCEPTION HANDLING. 14. Commonly occurring exceptions are usually defined in the Interpreter. These are known as Built-in Exceptions. 51 | P a g e Some Built-in Exceptions are listed as below: EXCEPTION DESCRIPTION ZeroDivisionError It is raised when an expression or a value is getting divided by zero (0). For example: If c = 0, then p = b/c will result in ‘ZeroDivisionError’. NameError It is raised when an identifier is not assigned any value earlier and is being used in some expression. For example: p = a*b/c then it will result in ‘NameError’ when one or more variables are not assigned values. TypeError It is raised when variables used in any expression have values of different data types. For example: p=(a+b)/c then it will result in ‘TypeError’ when the variables a, b and c are of different data types. Value Error It is raised when given value of a variable is of right data type but not appropriate according to the expression. IOError It is raised when the file specified in a program statement cannot be opened. IndexError It is raised when index of a sequence is out of the range. KeyError It is raised when a key doesn’t exist or not found in a dictionary. EXCEPTION HANDLING: Every exception has to be handled by the programmer for successful execution of the program. To ensure this we write some additional code to give some proper message to the user if such a condition occurs. This process is known as EXCEPTION HANDLING. Exception handlers separate the main logic of the program from the error detection and correction code. The segment of code where there is any possibility of error or exception, is placed inside one block. The code to be executed in case the exception has occurred, is placed inside another block. These statements for detection and reporting the execution do not affect the main logic of the program. 52 | P a g e STEPS FOR EXCEPTION HANDLING: An exception is said to be caught when a code designed for handling that particular exception is executed. In Python, exceptions, if any, are handled by using try-except-finally block. While writing a code, programmer might doubt a particular part of code to raise an exception. Such suspicious lines of code are considered inside a try block which will always be followed by an except block. The code to handle every possible exception, that may raise in try block, will be written inside the except block. If no exception occurred during execution of program, the program produces desired output successfully. But if an exception is encountered, further execution of the code inside the try block will be stopped and the control flow will be transferred to the except block. Example 1: 53 | P a g e The output will be: Example 2: In above example, the user entered a wrong value that raised ValueError. We can handle this exception by using ValueError exception. Result: Use of multiple “except” block: Sometimes, it may happen that a single piece of code in a program might have more than one type of error. If such an event happens, we can use multiple except blocks for a single try block. Example 1: 54 | P a g e The output will be: Example 2: We can also handle exceptions without naming them. The output will be: Default exception messages can also be displayed when we are not handling exceptions by name. 55 | P a g e The output will be: try…except…else Clause: Just like Conditional and Iterative statements we can use an optional else clause along with the try…except clause. An except block will be executed only when some exceptions will be raised in the try block. But if there is no error then except blocks will not be executed. In this case, else clause will be executed. The output will be: 56 | P a g e finally CLAUSE: The try…except…else block in python has an optional finally clause. The statements inside the finally block are always executed whether an exception has occurred in the try block or not. If we want to use finally block, it should always be placed at the end of the clause i.e. after all except blocks and the else block. The output will be: 57 | P a g e Exercise 1 In a try-except block, can there be multiple 'except' clauses? a) No, there can be only one 'except' clause. b) Yes, but only if the exceptions are of the same type. c) Yes, it allows handling different exceptions separately. d) No, 'except' clauses are not allowed in a try-except block. 2 When might you use the 'finally' block in exception handling? a) To handle exceptions that are expected to occur frequently. b) To provide a resolution for every possible error. c) To close resources that were opened in the 'try' block, regardless of whether an exception occurred or not. d) To avoid having to use 'except' blocks. 3 What will be the output of the following code snippet? a) Division by zero! b) Arithmetic error occurred! c) No error! d) This code will raise a syntax error. 4 Which of the following is NOT a standard built-in exception in Python? a) ValueError b) IndexError c) NullPointerException d) KeyError 5 What is an exception in programming? a) An error that occurs during runtime b) A warning message from the compiler c) A comment in the code d) A statement that terminates the program 6 What is the purpose of the "try" block in a try-except construct? a) To handle the exception by executing specific code b) To specify the type of exception to be thrown c) To define a custom exception class d) To ensure a specific block of code always executes 7 Which of the following exceptions in Python is not a built-in exception? a) ValueError 58 | P a g e b) KeyError c) CustomError d) IndexError 8 Assertion (A): In Python, the "try" block is used to enclose code that might raise an exception. Reasoning (R): The "try" block is where the program attempts to execute code that might result in an exception. If an exception occurs, it is handled in the corresponding "except" block. A. Both A and R are true and R is correct explanation of A B. Both A and R are true but R is not correct explanation of A C. A is True but R is False D. R is True but A is False 9 Assertion (A): The "finally" block in Python is always executed, regardless of whether an exception is raised or not. Reasoning (R): The "finally" block contains code that is guaranteed to execute, whether an exception occurs within the "try" block or not. A. Both A and R are true and R is correct explanation of A B. Both A and R are true but R is not correct explanation of A C. A is True but R is False D. R is True but A is False 10 Assertion (A): Python allows multiple "except" blocks to be used within a single "try" block to handle different exceptions. Reasoning (R): By using multiple "except" blocks with different exception types, Python provides the flexibility to handle various types of exceptions separately. A. Both A and R are true and R is correct explanation of A B. Both A and R are true but R is not correct explanation of A C. A is True but R is False D. R is True but A is False 11 Code snippet: Predict the output when: a) The user enters "0". b) The user enters "5". c) The user enters "abc". 12 State whether the following statement is True or False: An exception may be raised even if the program is syntactically correct. 13 What will be the output of the following code if the input is “e”: 59 | P a g e try: value = int("abc") result = 10 / 0 except ValueError: print("Error: Invalid value conversion") except ZeroDivisionError: print("Error: Division by zero") 14 What will be the output of the following code if the input is: i. 2 ii. 2.2 try: num = int(input("Enter a number: ")) except ValueError: print("Error: Invalid input") else: print("Entered number: ",num) 15 Rewrite the following code after handling all possible exceptions. num = int(input("Enter a number: ")) result = 10 / num print("Result:", result) 16 Consider the code given below: L = [‘s’, 45,23] Result = 0 for x in L: print (“The element is “, x) Result += x print(“The addition of all elements of L is: “, Result) Which of the following error will be raised by the given Python code? a) NameError b) ValueError c) TypeError d) IOError 17 Code snippet: Predict the output when: a) The user enters "10" for both numbers. 60 | P a g e b) The user enters "5" for the first number and "0" for the second number. c) The user enters "abc" for both numbers. 18 Which of the following statements is true? a). The standard exceptions are automatically imported in Python programs. b). All raised standard exceptions must be handled in Python. c). When there is deviation from the rules of a programming language, a semantic error is thrown. d). If any exception is thrown in try block, else block is executed. 19 Identify the statement(s) from the following options which will raise TypeError exception(s): a) print('5') b) print( 5 * 3) c) print('5' +3) d) print('5' + '3') Programming based question: 1 Create a simple calculator program that takes two numbers and an operator (+, -, *, /) as input. Implement exception handling to handle cases like division by zero and invalid operators. 2 Build a program that asks the user for an integer input. Use exception handling to ensure that the input is a valid integer. If the user provides invalid input, prompt them to retry until a valid integer is entered. 3 Create a program that connects to a database and performs database operations (e.g., insert, update, delete). Use exception handling to deal with database-related exceptions, such as connection errors or SQL syntax error. 4 Create a program that reads data from a file specified by the user. Implement exception handling to catch and handle the "FileNotFoundError" exception if the file does not exist. 5 Define a dictionary with some key-value pairs. Ask the user for a key and attempt to access the corresponding value from the dictionary. Handle the "KeyError" exception and display a message if the key is not found. 61 | P a g e Topics to be covered 1. Introduction 2. Types of files 3. Access specifiers in the file 4. File object methods seek() and tell() 5. Text files and its methods 6. Binary file and its methods 7. CSV files and its methods 8. Absolute and Relative path 62 | P a g e FILE HANDLING Files are used to store data permanently and can be retrieved later. Type of Files 1. Text Files 2. Binary Files 3. CSV Files Steps for File handling: 1. Open File 2. Read/Write 3. Close File Open Files: open( ) function is used to open files in python. There are two ways to open files in python: 1. file_object = open(“file name”, “ access specifier”) a. i.e. f=open(“test.txt”,”r”) #here our test file exists in the same directory of python. b. i.e. f=open(r”C:\Users\anujd\AppData\Local\Programs\Python\Python311\test.t xt”,”r”) Use ‘r’ before path indicates the data within quotes will be read as raw string and no special meaning attached with any character. Or f=open(”C:\\Users\\anujd\\AppData\\Local\\Programs\\Python\\Python311\ \test.txt”,”r”) The slash in the path has to be doubled. c. In this we need to close the file. d. In this mode if we are writing into a file then we have to close the file otherwise our data will not be written into the file till now the file is not closed. The data remains in the output buffer and when we close the file then data is shifted from the output buffer to the file. e. flush( ): It forces the data waiting in the buffer immediately written into the file without waiting for closing of file. 2. with open(“file name”,”access specifier”) as file_object: a. i.e. with open(“test.txt”,”r”) as f: 63 | P a g e b. i.e. with open(r”C:\Users\anujd\AppData\Local\Programs\Python\Python311\test.txt ”,”r”) as f: Or with open(”C:\\Users\\anujd\\AppData\\Local\\Programs\\Python\\Python311\\t est.txt”,”r”) as f: c. In this there is no need to close the file. It will automatically close the file. Close Files: close( ) function is used to close files in python. a. file_object.close( ) b. i.e. f.close( ) Access Specifiers in Files: Access Access Access Description File Pointer Mode Mode Mode for Position for Text for CSV Files Files Binary Files r Rb r Read mode. Opens a file for reading.If Beginning of the file does not exist, open() raises a File FileNotFoundError. r+ rb+ It opens the file for both reading and Beginning of writing. If the file does not exist, open() File raises a FileNotFoundError. w Wb w Write mode. It opens the file for writing Beginning of only. If the file exists, the content of the File file will be removed. If the file does not exist, it is created. w+ wb+ The w+ mode opens the file for both Beginning of writing and reading. Like w, if the file File exists, then the content of the file will be removed. If the file does not exist, it is created. 64 | P a g e a Ab a The a mode opens the file for End of File appending. In this the new content is added after the existing content. If the file does not exist, it creates the new file. a+ ab+ The a+ mode opens the file for both End of File appending and reading. In this the new content is added after the existing content. If the file does not exist, it is created. Default mode for file opening in “r” read mode. If we didn’t specify mode during the opening of the file then it will automatically open the file in read mode. File Object Methods (seek( ) & tell( )) Method Prototype Description seek( ) Syntax: seek() function is used to change the.seek(,) position of the File Handle to a given specific position. File handle is like a where: cursor, which defines from where offset: number of positions to be more forward the data has to be read or written in the file. from_where: it defines to reference point Then it returns the new absolute position. i.e. 0: sets the reference point at the f.seek(10,0) beginning of the file. (default) Here, f is the file handle, 10 is the offset (it 1: sets the reference point at the moves the cursor 10 bytes forward), 0 means current file position. reference point at the beginning of file. 2: sets the reference point at the end of the file Note: In the case of a text file we can use only ‘0’ as a reference point. tell( ) Syntax:.tell( ) tell() function returns the current position of the file object. This 65 | P a g e I.e. method takes no parameters and returns an integer value. Initially the position=f.tell( ) file pointer points to the beginning Here, position will hold the integer value of the of the file(if not opened in append file pointer returned by tell function. mode). So, the initial value of tell() is zero. f is the file handle. Text Files: It stores information in the form of ASCII or Unicode characters Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default. File extension will be.txt Working with Text Files: 1. Reading data from a file. 2. Writing data into a file. Reading data from files There are three ways to read data from text file: 1. read function i.e. read( ) 2. readline function i.e. readline( ) 3. readlines function i.e. readlines( ) read( ) : It is used in text files to read a specified number of data bytes from the file. It returns the result in the form of a string. Syntax: file_object.read( ) file_pointer.read(n): It will read the maximum n bytes/characters from the file. f.read(7) # it will read 7 bytes/characters from the position of file pointer. file_pointer.read( ): It will read the entire content of the file. f.read( ) # it will read all the data of the file from the position of file pointer. 66 | P a g e readline( ): It will read one complete line in one go from the file. It returns the data in the form of a string. Syntax: file_object.readline( ) file_pointer.readline( ): It will read the entire line. f.readline( ) #it will read one complete line in one go. file_pointer.readline(n): It will read the first ‘n’ bytes from the file. f.readline(5) #it will read the first 5 characters/bytes from the file. readlines( ): It will return all the lines of the file as the elements of the list. I.e. the 1st line of the file will be the first element of the list and so on. Syntax: file_object.readlines( ) file_pointer.readlines( ): It will read all the lines of the file as the elements of the list. f.readlines( ) #it will read all the lines of the file as the elements of the list. File Content Code Output 67 | P a g e Result is in the form of a list. 68 | P a g e Tips on writing text file code in exam: Let the file name be “abc.txt”. Read the question carefully and find out what has to be read from the file. Follow the below flow chart to write the code. 69 | P a g e Example 1: Write a function count_char() that reads a file named “char.txt” counts the number of times character “a” or “A” appears in it. Example 2: Write a function count_word() that reads a text file named “char.txt” and returns the number of times word “ the” exists. Example 3: Write a function count_line() that reads a text file named “char.txt” and returns the number of lines that start with a vowel. 70 | P a g e Writing data into Files If the file doesn’t exist then it will create the file. 1. write( ): It takes string as an input and writes it into the file. a. Syntax: file_object.write(string) b. i.e. f.write(“Hello World”) 2. writelines( ): It is used to write multiple lines as a list of strings into the file. In this each element of the list will be treated as a separate line in the file. a. Syntax: file_object.writelines(list of strings) b. I.e. data=[“I am a student of DOE”, “I studies in class 12th”] f.writelines(data) Code Output Content in “Topper.txt” file But, we want these names in separate lines. 71 | P a g e Output: Content of “Topper.txt” File: Question: Write a program in python with reference to above program, the content of the text files should be in different lines. I.e. Priya Disha Tanisha Krishna Aman Code 72 | P a g e Output Content of “Toppers.txt” file: Write a program in python to count vowels, consonants, digits, spaces, special characters, spaces, words and lines from a text file named “student.txt”. Content of File: 73 | P a g e Code: Output: 74 | P a g e Exercise 1. Define a function SGcounter() that counts and display number of S and G present in a text file ‘A.txt” e.g., SAGAR JOON IS GOING TO MARKET. It will display S:2 G:2 2. Write a function in Python that counts the number of “is”, “am” or “are” words present in a text file “HELLO.TXT”. If the “HELLO.TXT” contents are as follows: Here are two sentences that contain "is," "am," or "are": “She is studying for her final exams. We are planning a trip to the mountains next weekend.” The output of the function should be: Count of is/am/are in file: 2 3. Write a method in python to read lines from a text file HELLO.TXT to find and display the occurrence of the word “hello”. 4. Write a user-defined function named Count() that will read the contents of a text file named “India.txt” and count the number of lines which start with either “I” or “T”. E.g. In the following paragraph, there are 2 lines starting with “I” or “T”: “The Indian economy is one of the largest and fastest-growing in the world, characterized by a diverse range of industries including agriculture, manufacturing, services, and information technology. It boasts a sizable consumer base and a dynamic entrepreneurial spirit. However, it also faces challenges such as income inequality, poverty, and infrastructure gaps, which the government continually addresses through policy reforms and initiatives to foster sustainable growth and development.” 5. Write a method in python to read lines from a text file AZAD.TXT and display those lines, which are starting with an alphabet ‘T’. Binary Files: 1. Binary files are made up of non-human readable characters and symbols, which require specific programs to access its contents. 2. In this translation is not required because data is stored in bytes form. 3. Faster than text files. 75 | P a g e 4. pickle module is used for working with binary files a. import pickle 5. File extension will be.dat 6. There is no delimiter to end the file. Working in Binary files: Pickle module: pickle module is used in binary file for load( ) and dump( ) methods which are used for reading and writing into binary file respectively. Pickling: It is the process of converting python object into byte stream. Pickling is done at the time of writing into a binary file. Unpickling: It is the process of converting a byte stream into python object. Unpickling is done at the time reading from a binary file. dump( ): it is used to write data into binary file. Syntax: identifier = pickle.dump(data , file_pointer) Example: a= “My name is Anuj” pickle.dump(a,f) #here ‘a’ contains data and ‘f’ is a file pointer. Program Code Input Details 76 | P a g e File Content load( ): it is used to read data from binary file. Syntax: identifier = pickle.load(file_pointer) Example: data = pickle.load(f) #Here ‘data’ is an identifier and ‘f’ is a file pointer. 77 | P a g e Question: Write a menu based program in python which contain student details in binary file and should have following facilities: 1. Writing student details. 2. Display all students’ details 3. Search particular student details 4. Update any student details 5. Delete any student details 6. Exit 78 | P a g e 79 | P a g e Comma Separated Value (CSV) Files: 1. It is a plain text file which stores data in a tabular format, where each row represents a record and each column represents a field and fields are separated by comma in csv files. 2. csv module is used for working with csv files a. import csv 3. File extension for csv file will be.csv 4. CSV module provides two main classes for working with csv files are: 80 | P a g e a. reader b. writer 5. CSV reader object can be used to iterate through the rows of the CSV file. 6. CSV writer object that can be used to write row(s) to the CSV file. a. writerow(): This method is used to write a single row to the CSV file. b. writerows(): This method is used to write multiple rows to the CSV file. 7. We can read csv file data in excel file also. 1. Reader Function: a. For reading data from csv file we require csv. reader( ) function. 2. Writer Function: a. For writing data to the csv file we take a file object as input and write the data into the file. b. writerow( ): It writes a single row of data to the CSV file. c. writerows( ): It writes a list of rows of data to the CSV file. WRITING INTO CSV FILES Code: Output in IDLE: Result in Notepad: Result in Excel: 81 | P a g e Code: Output in IDLE: Result in Notepad: Result in Excel: Code: Output in IDLE: Result in Notepad: Result in Excel: 82 | P a g e READING FROM CSV FILES File Content: Code: To read all records of csv file Output: Code: To display all the records in which Output: name starts with ‘A’ ABSOLUTE AND RELATIVE PATH: 1. Absolute path is a path that starts from the root directory of the file system or we can say that it describes how to access a given file or directory, from the starting of the file system. 2. Relative path is a path that is relative to the current working directory or we can say that is interpreted from the perspective of the current working directory. 83 | P a g e 84 | P a g e Questions 1. Write a statement to send the file pointer position 10 bytes forward from current location of file ,consider fp as file object. a) fp.seek(10) b) fp.seek(10,1) c) fp.tell(10) d) fp.seek(1,10) 2. Which function is used to open a file in Python? a. open() b. read() c. write() d. close() 3. Which of the following mode in file opening statement results or generates an error if the file does not exist? a) a+ b) r+ c) w+ d) None of the above 4. If the csv file 'item.csv' has a header and 3 records in 3 rows and we want to display only the header after opening the file with open() function, we should write a). print(file.readlines()) b). print(file.read()) c) print(file.readline()) d). print(file.header()) 5. Identify the missing part in the code to write the list object in the file >>> import pickle >>> x=[1,3,5,7] >>> f=open('w.dat','wb') >>> pickle._____(x,f) >>> f.close() a). write() b). writeline() c). load() d). dump() 6. Which of the following statements are True (a) When you open a file for reading, if the file does not exist, an error occurs (b) When you open a file for writing, if the file does not exist, a new file is created (c) When you open a file for writing, if the file exists, the existing file is overwritten with the new file (d) All of the mentioned 7. Write a statement to send the file pointer position 10 bytes forward from current location of file , consider fp as file object. a) fp.seek(10) b) fp.seek(10,1) c) fp.tell(10) d) fp.seek(1,10) 8. myfile.txt is a file stored in the working directory. Total number of characters including spaces are 106 and there are 5 lines. What will be the output of len(file.readlines()) after the file was opened as file=open('myfile.txt') a). 4 b). 106 c). 5 d). 1 9. Which of the following option is not correct? a. if we try to read a text file that does not exist, an error occurs. b. if we try to read a text file that does not exist, the file gets created. 85 | P a g e c. if we try to write on a text file that does not exist, no error occurs. d. if we try to write on a text file that does not exist, the file gets Created. 10. A text file readme.txt is opened in Python. What type of data is stored in f? >>> file=open('readme.txt') >>> f=file.readlines() a). String b). Tuple c). List d). None of the above 11. Find P and Q from the options while performing object serialization >>> import pickle >>> spc=open("yoyo.dat","wb") >>> x=500 >>> pickle.dump(P,Q) a). x,spc b). spc, x c). 'yoyo.dat',500 d). 'yoyo.dat','500' 12. A text file myfile0.txt has two lines of text, what will be stored in the variable ctr when the following code is executed? >>> ctr=0 >>> spc=open("myfile0.txt") >>> while(spc.readline()): ctr += 1 a). 0 b). 1 c). 2 d). 3 13. How many lines does the file myfile00.txt has after the code is executed? >>> mylist=['India', '\nis', '\nmy', '\ncountry', '\nand', '\nI', '\nam', '\na', '\nproud', '\ncitizen'] >>> spc=open("myfile00.txt","w") >>> spc.writelines(mylist) a). 2 b). 10 c). 9 d). 1 14. Which of the following options can be used to read the first line of a text file Myfile.txt? a. myfile = open('Myfile.txt'); myfile.read() b. myfile = open('Myfile.txt','r'); myfile.read(n) c. myfile = open('Myfile.txt'); myfile.readline() d. myfile = open('Myfile.txt'); myfile.readlines() 15. Assume that the position of the file pointer is at the beginning of 3rd line in a text file. Which of the following option can be used to read all the remaining lin

Use Quizgecko on...
Browser
Browser