Python Supplement for Class XII 2020-21 PDF
Document Details
2021
CBSE
Preeti Arora
Tags
Summary
This document is a supplement for the 2020-21 CBSE computer science syllabus for class XII. It outlines changes to the old curriculum, providing a comparative analysis, and includes case-based/source-based integrated questions and additions to text and exercises.
Full Transcript
As per 2020-21 Syllabus PREETI ARORA DOEACC ‘A’ level, M.Sc–IT, M.Tech–IT Sr. Computer Science Teacher To download this Supplement Free of Cost, visit...
As per 2020-21 Syllabus PREETI ARORA DOEACC ‘A’ level, M.Sc–IT, M.Tech–IT Sr. Computer Science Teacher To download this Supplement Free of Cost, visit sultan-chand.com/ws/python12 Dear Reader The aim of this Supplement to Computer Science with Python for Class XII is to apprise you of the changes effected in the CBSE syllabus for 2020-21 and provide them in textbook format. In fact, the syllabus for 2020-21 has witnessed large-scale changes with two chapters completely refurbished, three chapters done away with, and new topics included in another two chapters, all of which have been duly taken care of in this Supplement. Besides, chapter-wise Case-based/Source-based Integrated Questions, which have been introduced for the first time in the Class XII curriculum, too have been given at the end of the Supplement. To ensure that your book is complete in all respects once this Supplement is in your hands, an elaborate Comparative Analysis of Class XII Old and New CBSE Curriculum has been given right in the beginning of the Supplement to give you a clear-cut idea about the chapters modified or new topics included in the 2020-21 syllabus vis-à-vis the old one. Since the Supplement is to be used in consonance with the textbook, additions to Chapters 3 and 4 text and exercises have been placed and numbered accordingly. A printed copy of this Supplement is also available at a nominal price. Happy learning! COMPARATIVE ANALYSIS OF CLASS XII OLD AND NEW CBSE CURRICULUM Computer Science (083) UNIT OLD CURRICULUM (2019-20) NEW CURRICULUM (2020-21) CHANGES Total weightage of this unit 30 Marks 40 Marks increased by 10 Marks Revision of the Basics of Python Revision of the Basics of Python No change Functions: scope, parameter Functions: scope, parameter passing, mutable/ passing, mutable/immutable immutable properties of data objects, passing properties of data objects, strings, lists, tuples, dictionaries to functions, math and string functions to pass arrays to functions, return default parameters, positional parameters, be added values, functions using libraries: return values, Functions using libraries: mathematical and string functions. mathematical and string functions. File handling: Need for a data file, Types of file: Text files, Binary files and CSV (Comma separated values) files. Text File: Basic operations on a text file: Open (filename – absolute or relative path, mode) / Close a text file, Reading and Manipulation of (1) CSV Files– open, read data from a text file, Appending data into a text I: Computational Thinking File handling: open and close a file, and write functions file, standard input/output and error streams, and Programming read, write, and append to a file, relative and absolute paths. Binary File: Basic standard input, output, and error (2) Read from a csv file operations on a binary file: Open(filename – streams, relative and absolute and Write into a csv file absolute or relative path, mode) / Close a binary paths. using csv.reader ( ) and file, pickle Module – methods load and dump; csv.writerow( ) Read, Write/Create, Search, Append and Update operations in a binary file. CSV File: import csv module, functions – Open / Close a csv file, Read from a csv file and Write into a csv file using csv.reader( ) and csv.writerow( ). Using Python libraries: create and Using Python libraries: create and import Python No change import Python libraries libraries. Recursion: simple algorithms with Recursion: simple algorithms with recursion: recursion: factorial, Fibonacci print a message forever, sum of first n natural No change numbers; recursion on arrays: numbers, factorial, Fibonacci numbers; recursion binary search on arrays: binary search Idea of efficiency: performance defined as inversely proportional to the wall clock time, count the number of operations a piece of code is performing, and measure Idea of efficiency: performance measurement in No change the time taken by a program. terms of the number of operations. Example: take two different programs for the same problem, and understand how the efficient one takes less time. Data visualization using Pyplot: line Entire Chapter removed chart, pie chart, and bar chart. Data-structures: Lists as covered in Class XI, Stacks – Data-structures: lists, stacks, Push, Pop using a list, Queues – Insert, Delete No change queues. using a list. Total weightage of this unit 15 Marks 10 Marks reduced by 5 marks Evolution of Networking: ARPANET, Internet, Interspace Different ways of sending data across the network with reference to switching (1) Evolution of Structure of a network: Types of techniques (Circuit and Packet switching). Networking networks: local area and wide Data Communication terminologies: Concept of area (web and internet), new Channel, Bandwidth (Hz, KHz, MHz) and Data (2) Switching Techniques II: Computer Networks technologies such as cloud and IoT, transfer rate (bps, Kbps, Mbps, Gbps, Tbps). (3) Data Communication (Entire Unit reframed) public vs. private cloud, wired and Terminologies wireless networks; concept of a Transmission media: Twisted pair cable, client and server. coaxial cable, optical fibre, infrared, radio link, microwave link and satellite link. Network Topologies and types: Bus, Star, Tree, (4) Topologies Types of Network: PAN, LAN, WAN, MAN. Network devices such as a NIC, Network devices: Modem, RJ45 connector, (1) Three more Network switch, hub, router, and access Ethernet Card, Router, Switch, Gateway, WiFi devices added point. card. Network stack: amplitude and frequency modulation, collision in wireless networks, error Topics removed: checking, and the notion of a MAC Network Protocol: TCP/IP, File Transfer Protocol (1) AM & FM address, main idea of routing. IP (FTP), PPP, HTTP,SMTP, POP3,Remote Login (2) CSMA/CA & CD addresses: (v4 and v6), routing (Telnet) and Internet, Wireless / Mobile table, router, DNS, and web URLs, Communication protocol such as GSM, GPRS (3) Error Checking TCP: basic idea of retransmission, and WLL. (4) Idea of Routing and rate modulation when there (5) Network Congestion is congestion (analogy to a road network), Protocols: 2G, 3G, 4G, Wi-Fi. What makes a protocol have a higher bandwidth? Mobile Telecommunication Technologies: 1G, Application layer: HTTP (basic 2G, 3G, 4G and 5G; Mobile processors; Electronic idea), working of email, secure mail protocols such as SMTP, POP3, Protocols No major changes communication: encryption and for Chat and Video Conferencing: VoIP, Wireless certificates (HTTPS), network technologies such as Wi-Fi and WiMax applications: remote desktop, remote login, HTTP, FTP, SCP, SSH, POP/IMAP, SMTP, VoIP, NFC. Basic network tools: traceroute, ping, ipconfig, nslookup, whois, Entire Topic removed speed-test. Network Security Concepts: Threats and Mentioned Topics have been prevention from Viruses, Worms, Trojan added to this unit; taken horse, Spams. Use of Cookies, Protection using from Unit-4 (Society Law Firewall, https; India IT Act, Cyber Law, Cyber and Ethics)—old curriculum Crimes, IPR issues, hacking. Introduction to Web services: WWW, Hyper Text Markup Language (HTML), Extensible Markup Language (XML); Hyper Text Transfer Newly-added topics Protocol (HTTP); Domain Names; URL; Website, Web browser, Web Servers; Web Hosting, Web Scripting E-commerce payment transactions using online banking, mobile banking, payment apps and Newly-added topics services. Total weightage of this unit 15 Marks 20 Marks increased by 5 marks Write a minimal Django-based web application that parses a GET and Complete Chapter removed POST request, and writes the fields to a file—flat file and CSV file. Interface of Python with an SQL database Connecting SQL with Python Creating Database Interface Python with an SQL connectivity Applications Performing Insert, No change database Update, Delete queries Display data by using fetchone(), fetchall(), rowcount() Database Concepts: Introduction to database concepts and its need. Relational data model: III: Data Management Concept of domain, relation, tuple, attribute, degree, cardinality, key, primary key, candidate key, alternate key and foreign key Structured Query Language: General Concepts: Advantages of using SQL, Data Definition Language and Data SQL commands: aggregation Manipulation Language; Data Types: number / The mentioned topics have functions – having, group by, order decimal, character / varchar / varchar2, date; been added from Class XI by. SQL commands: CREATE TABLE, DROP TABLE, previous curriculum ALTER TABLE, UPDATE....SET , INSERT, DELETE; SELECT, DISTINCT, FROM, WHERE, IN, BETWEEN, LIKE, NULL / IS NULL, ORDER BY, GROUP BY, HAVING; SQL Aggregate functions: SUM (), AVG (), COUNT (), MAX () and MIN (); Joins: equi-join and natural join 10 Marks 0 Marks No weightage Intellectual property rights, plagiarism, digital rights management, and licensing (Creative Commons, GPL and Apache), open source, open data, privacy. Privacy laws, fraud; cyber-crime— Major Topics of this Unit phishing, illegal downloads, have been added to child pornography, scams; cyber Computer Networks. IV: Society, Law and Ethics forensics, IT Act, 2000. This Unit has been Technology and society: completely removed. understanding of societal issues and cultural changes induced by technology. E-waste management: proper disposal of used electronic gadgets. Identity theft, unique ids, and biometrics. Gender and disability issues while teaching and using computers. RED - Removed Topics GREEN – Detailed added topics PURPLE – No Change BLUE - Added Topics CONTENTS CHAPTER 3 Using Python Libraries (Additions) 3.1 – 3.8 CHAPTER 4 Data File Handling (Additions) 4.1 – 4.24 CHAPTER 8 Computer Networks 8.1 – 8.74 CHAPTER 12 Relational Database and SQL 12.1 – 12.76 Case-based/Source-based Integrated Questions C.1 – C.22 3 Using Python Libraries (Additions) 3.11 USING PYTHON STANDARD LIBRARY’S FUNCTIONS AND MODULES Python’s standard library is very extensive, offering a wide range of modules and functions. The library contains built-in modules (written in C) that provide access to system functionality such as file I/O, that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming. Some of these important modules are explicitly designed to encourage and enhance the portability of Python programs, such as math module for mathematical functions; random module for pseudo-random number generation; and string module for string/text-related functions. We have already discussed important math and string modules and their functions. Let us talk about some more built-in mathematical functions. 3.11.1 Python’s built-in Mathematical Functions We have already discussed major functions using math module. Python provides many other mathematical built-in functions as well. These include trigonometric functions, representation functions, logarithmic functions, angle conversion functions, etc. In addition, two mathematical constants are also defined in this module. Pie (π): Pie (π) is a well-known mathematical constant, which is defined as the ratio of the circumference to the diameter of a circle and its value is 3.141592653589793. To import this single object (pie) from the math module: >>> import math >>> math.pi 3.141592653589793 Alternatively, it can be done without prefixing the module name and writing the name of the object directly after keyword import as shown below: >>> from math import pi >>> print(pi) >>> 3.141592653589793 Similarly, another well-known mathematical constant defined in the math module is e. It is called Euler’s number and it is a base of the natural logarithm. Its value is 2.718281828459045. Hence, these constants can be directly called and used from math module. We should remember not to use module name with imported object if imported through from import command because now the imported object is part of your program’s environment. The math module contains functions for calculating various trigonometric ratios for a given angle. The functions (sin, cos, tan, etc.), which we have already discussed, need the angle in radians as an argument. We, on the other hand, are used to express the angle in degrees. The math module presents two-angle conversion functions — degrees() and radians() — to convert the angle from degrees to radians and vice versa. For example, the following statements convert the angle of 30 degrees to radians and back. π degrees() converts a value in radians to degrees using the formula: degrees( x ) = x 180 180 On the contrary, radians() converts a value in degrees to radians: radians( x ) = x π POINT TO REMEMBER Π radian is equivalent to 180 degrees. For example, To convert an imputed angle of 50 degrees to radians and vice versa. Supplement – Computer Science with Python–XII Practical Implementation–5 Write a Python program to calculate the area of a regular polygon. For solving this problem, we have to understand the formula to be used first, which is given as: Area of a Regular Polygon n = number of sides s = length of a side s ns Area = π 4 tan n 3.2 Practical Implementation–6 Write a Python program to find the roots of a quadratic function. A quadratic equation is represented as: ax2 + bx + c = 0 Here, a, b and c are numbers, where a ≠ 0; and x is to be calculated. The roots of any quadratic equation are given by the formula: x = [–b +/– sqrt(b^2 – 4ac)]/2a. Using Python Libraries (Additions) 3.3 Practical Implementation–7 Write a Python program to calculate arc length of an angle. In a planar geometry, an angle is a figure formed by two rays called the sides of the angle, sharing a common endpoint known as the vertex of the angle. Angles formed by two rays lie in a plane, but this plane does not have to be a Euclidean plane. Ar c le ng th q r θ Arc length = 2pr 360 Supplement – Computer Science with Python–XII Practical Implementation–8 Write a Python program to convert a binary number to decimal number. A binary number is a number which is represented in the form of 0 and 1 (binary digits) only and decimal number system, the contemporary number system used mathematically, constitutes numbers from 0 to 9. 3.4 Also, a binary number system has 2 as its base while the decimal system has 10 as its base. The method of conversion of a binary number to its decimal equivalent is: 1 1 0 1 1 0 1 1 Binary to Decimal 1 × 20 = 1 × 1 = 1 1 × 21 = 1 × 2 = 2 0 × 22 = 0 × 4 = 0 1 × 23 = 1 × 8 = 8 1 × 24 = 1 × 16 = 16 0 × 25 = 0 × 32 = 0 1 × 26 = 1 × 64 = 64 1 × 27 = 1 × 128 = 128 1 + 2 + 8 + 16 + 64 + 128 = 219 (11011011)2=(219)10 In the above program, the input taken from the user is converted to a list using the function list() and gets stored inside variable b_num. The loop gets executed up to the length of the list, i.e., the number of list elements. With every iteration, each digit is extracted or popped from the list using Using Python Libraries (Additions) function pop(). This extracted digit is checked for character as 1 and is raised to the power of 2. Finally, the value gets printed which is in decimal format. In case the digit is 0, no execution takes place since the product of any value with 0 results in 0 itself. Hence, the output is obtained as 219. 3.11.2 Python’s built-in String Functions We have already discussed the built-in String functions in the previous chapters. Let us now see some more practical implementations of most commonly used inbuilt string functions. 3.5 Practical Implementation–9 Write a Python function that takes a list of words and returns the length of the longest one. “JSP”,”Computers”,”Python3” “JSP” , ”Computers” , ”Python3” Length 3 9 7 Word of the longest length “Computers” Supplement – Computer Science with Python–XII In the above program, two inbuilt string functions, append() and sort(), have been used for adding elements to an empty list, word_len, and the list elements are sorted in ascending order using sort() method. 3.6 Practical Implementation–10 Write a Python program to capitalize first and last letters of each word of a given string. Practical Implementation–11 Write a Python program to swap each character of a given string from lowercase to uppercase and vice versa. Using Python Libraries (Additions) 3.7 SOLVED QUESTIONS 40. Write a program that performs the following operations on a string: (a) Prompt the user to input a string. (b) Extract all the digits from the string. (c) If there are digits in the inputted string: Calculate and display the sum of the digits. Also display: ▪ The original string ▪ The digits ▪ The sum of the digits (d) If there are no digits: Display the original string along with the appropriate message: “No Digits are present” Ans. str1 = input("Enter the string: ") sum = 0 num = 0 if str1.isalpha() == False: for i in str1: if i.isdigit() == True: num =num*10 + int(i) sum += int(i) print("Original String: ",str1) print("Digits: ",num) print("Sum of digits is: ",sum) else: print("Original String: ", str1, "has no digit") 41. Write a program with a user-defined function with string as a parameter which replaces all vowels in the string with ‘*’. Ans. #Function to replace all vowels in the string with '*' def replaceVowel(st): #Create an empty string newstr = '' for character in st: #Check if next character is a vowel if character in 'aeiouAEIOU': #Replace vowel with * newstr += '*' else: Supplement – Computer Science with Python–XII newstr += character return newstr #End of function st = input("Enter a String: ") st1 = replaceVowel(st) print("The original String is:", st) print("The modified String is:", st1) UNSOLVED QUESTIONS 27. Write a user-defined function to calculate the area of a triangle. 28. Write a user-defined function to convert a string with more than one word into title case string where string is passed as parameter. (Title case means that the first letter of each word is capitalized.) 29. Write a function deleteChar() which takes two parameters—one is a string and the other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string. 30. Write a program to print the number of occurrences of a substring into a line using built-in string function find(). 3.8 4 Data File Handling (Additions) 4.11 BINARY FILE OPERATIONS Most of the files that we see in our computer system are called binary files. Example: Document files:.pdf,.doc,.xls, etc. Image files:.png,.jpg,.gif,.bmp, etc. Video files:.mp4,.3gp,.mkv,.avi, etc. Audio files:.mp3,.wav,.mka,.aac, etc. Database files:.mdb,.accde,.frm,.sqlite, etc. Archive files:.zip,.rar,.iso,.7z, etc. Executable files:.exe,.dll,.class, etc. All binary files follow a specific format. We can open some binary files in the normal text editor but we cannot read the content present inside the file. This is because all the binary files are encoded in the binary format, which can be understood only by a computer or a machine. In binary files, there is no delimiter to end a line. Since they are directly in the form of binary, hence there is no need to translate them. That is why these files are easy to work with and fast. We have already discussed about pickle module and handling (reading and writing) binary file operations using load() and dump() methods of this (pickle) module. We will now discuss the four major operations performed using a binary file such as— 1. Inserting/Appending a record in a binary file 2. Reading records from a binary file 3. Searching a record in a binary file 4. Updating a record in a binary file We will now discuss each of them. The file in consideration is “student” file with the fields Roll_no, name and marks. Inserting/Appending a record in a binary file Inserting or adding (appending) a record into a binary file requires importing pickle module into your program followed by dump() method to write onto the file. Practical Implementation–19 Program to insert/append a record in the binary file “student.dat”. Supplement – Computer Science with Python–XII As shown in the above program, inserting and adding a record in student file begins with importing pickle module. Then, iterating for the number of records to be added is done using while loop. Input is accepted from the user for roll number, name and marks. These fetched values are saved as a list to be appended. Once the record is created, it is appended to the binary file “student” using the dump() method, which writes the object onto the opened file. Finally the file is closed explicitly and the record is added into the student.dat file as shown in the output. Since binary file contains unreadable characters, it becomes difficult to read and understand, but it is directly used and understood by the computer. 4.2 Reading a record from a binary file The following practical implementation illustrates how a record is read from a binary file. Practical Implementation–20 Program to read a record from the binary file “student.dat” The above program deals with reading the contents from binary file student using load() method of pickle module. It is used to read the object from the opened file. The syntax for this is given by the statement— object = pickle.load(file) Once the contents are read, it gets stored inside the object, stud_rec. All the data of the respective fields from this object is held in the respective variables—roll_no, name and marks—and are finally displayed as the output. Searching a record in a binary file Searching the binary file "student" is carried out on the basis of the roll number entered by the user. The file is opened in the read-binary mode and gets stored in the file object, f. load() method is used to read the object from the opened file. A variable ‘found’ is used which will tell the status of the search operation being successful or unsuccessful. Each record from the file is read and the content of the field, roll no, is compared with the roll number to be searched. Upon the search being Data File Handling (Additions) successful, appropriate message is displayed to the user as shown in the practical implementation that follows. 4.3 Practical Implementation–21 Program to search a record from the binary file “student.dat” on the basis of roll number. Updating a record in a binary file Updating a record in the file requires roll number to be fetched from the user whose name is to be updated. Supplement – Computer Science with Python–XII Once the record is found, the file pointer is moved to the beginning of the file using seek(0) statement, and then the changed name is written to the file and the record is updated. seek() method is used for random access to the file. We will be learning more about it in the next section. 4.4 Practical Implementation–22 Write a menu-driven program to perform all the basic operations using dictionary on student binary file such as inserting, reading, updating, searching and deleting a record. Data File Handling (Additions) 4.5 Supplement – Computer Science with Python–XII 4.6 4.12 RANDOM ACCESS IN FILES USING TELL() AND SEEK() Till now, in all our programs we laid stress on the sequential processing of data in a text and binary file. But files in Python allow random access of the data as well using built-in methods seek() and tell(). seek()—seek() function is used to change the position of the file handle (file pointer) to a given specific position. File pointer is like a cursor, which defines from where the data has to be read or written in the file. Python file method seek() sets the file’s current position at the offset. This argument is optional and defaults to 0, which means absolute file positioning. Other values are: 1, which signifies seek is relative (may change) to the current position, and 2, which means seek is relative to the end of file. There is no return value. The reference point is defined by the “from_what” argument. It can have any of the three values: 0: sets the reference point at the beginning of the file, which is by default. 1: sets the reference point at the current file position. 2: sets the reference point at the end of the file. seek() can be done in two ways: Absolute Positioning Relative Positioning Absolute referencing using seek() gives the file number on which the file pointer has to position itself. The syntax for seek() is— f.seek(file_location) #where f is the file pointer For example, f.seek(20) will give the position or file number where the file pointer has been placed. This statement shall move the file pointer to 20th byte in the file no matter where you are. Relative referencing/positioning has two arguments, offset and the position from which it has to traverse. The syntax for relative referencing is: f.seek(offset, from_what) #where f is file pointer For example, f.seek(–10,1) from current position, move 10 bytes backward f.seek(10,1) from current position, move 10 bytes forward f.seek(–20,1) from current position, move 20 bytes backward f.seek(10,0) from beginning of file, move 10 bytes forward Data File Handling (Additions) POINT TO REMEMBER It must be remembered that Python 3.x only supports text file seeks from the beginning of the file. seek() with negative offset only works when the file is opened in binary mode. tell()—tell() returns the current position of the file read/write pointer within the file. Its syntax is: f.tell() #where f is file pointer 4.7 When you open a file in reading/writing mode, the file pointer rests at 0th byte. When you open a file in append mode, the file pointer rests at the last byte. This is illustrated in the practical implementation that follows: Practical Implementation–23 Program to read byte by byte from a file using seek() and tell(). Contents of “test.txt” Supplement – Computer Science with Python–XII 4.13 INTRODUCTION TO CSV In today’s organizational working environment, data sharing is one of the major tasks to be carried out, largely through spreadsheets or databases. A basic approach to share data is through the comma separated values (CSV) file. CSV is a simple flat file in a human readable format which is extensively used to store tabular data, in a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. 4.8 Files in the CSV format can be imported Spreadsheet to and exported from programs that store data in tables, such as Microsoft Excel or X OpenOffice Calc. Already defined, CSV stands for “comma CSV separated values”. Thus, we can say DATA that a comma separated file is a delimited Database text file that uses a comma to separate Fig. 4.9: CSV Storage Format values. CSV stands for Comma It is used for storing tabular Separated Values data in spreadsheet or database CSV Each record consists of fields Each line of the file is called a separated by commas (delimiter) record Fig. 4.10: Features of a CSV file Each line in a file is known as data/record. Each record consists of one or more fields, separated by commas (also known as delimiters), i.e., each of the records is also a part of this file. Tabular data is stored as text in a CSV file. The use of comma as a field separator is the source of the name for this file format. It stores our data into a spreadsheet or a database. CTM: The most commonly used delimiter in a CSV file is usually a comma. 4.14 WHY USE CSV The extensive use of social networking sites and their various associated applications requires the handling of huge data. But the problem arises as to how to handle and organize this large unstructured data, as shown in the Fig. 4.11(a) given below. consists o Data File Handling (Additions) Processing data having complex Bring huge amount of data to Storing huge and exponentially structure (structured, computation unit becomes a growing datasets un-structured, semi-structured) bottleneck Fig. 4.11(a): Problem of Huge Data 4.9 The solution to the above problem is CSV (Fig. 4.11(b)). Thus, CSV organizes data into a structured form and, hence, the proper and systematic organization of this large amount of data is done by CSV. Since CSV file formats are of plain text format, it makes it very easy for website developers to create applications that implement CSV. Fig. 4.11(b): CSV as a Solution CSV files are commonly used because they are easy to read and manage, small in size, and fast to process/transfer. Because of these salient features, they are frequently used in software applications, ranging anywhere from online e-commerce stores to mobile apps to desktop tools. For example, Magento, an e-commerce platform, is known for its support of CSV. Thus, in a nutshell, the several advantages that are offered by CSV files are as follows: CSV is faster to handle. CSV is smaller in size. CSV is easy to generate and import onto a spreadsheet or database. CSV is human readable and easy to edit manually. CSV is simple to implement and parse. CSV is processed by almost all existing applications. Supplement – Computer Science with Python–XII After understanding the concept and importance of using CSV files, we will now discuss the read and write operations on CSV files. 4.15 CSV FILE HANDLING IN PYTHON For working with CSV files in Python, there is an inbuilt module called CSV. It is used to read and write tabular data in CSV format. Therefore, to perform read and write operations with CSV file, we must import CSV module. CSV module can handle CSV files correctly regardless of the operating system on which the files were created. Along with this module, open() function is used to open a CSV file and return file object. We load the module in the usual way using import: >>> import csv 4.10 Like other files (text and binary) in Python, there are two basic operations that can be carried out on a CSV file: 1. Reading from a CSV file 2. Writing to a CSV file Let us discuss these CSV operations. 4.15.1 Reading from a CSV File Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python’s built-in open() function, which returns a file object. This creates a special type of object to access the CSV file (reader object), using the reader() function. The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. You can also use next() directly on it to read the next line of the CSV file, or you can treat it like a list in a for loop to read all the lines of the file (as lists of the file’s fields). This is shown in Practical Implementation–24. Before this, enter the student details in spreadsheet and save this file as shown. Next step is to open the Notepad and enter the data for student.csv, which will be the equivalent for student.xls. student.csv student.xls Data File Handling (Additions) In student.csv (notepad) file, the first line is the header and remaining lines are the data/ records. The fields are separated by comma, or we may say the separator character. In general, the separator character is called a delimiter, and the comma is not the only one used. Other popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters. 4.11 Practical Implementation–24 Write a program to read the contents of “student.csv” file. Explanation: As seen from the above output, every record is stored in reader object in the form of a List. In the above code, we first open the CSV file in READ mode. The file object is named f. The file object is converted to csv.reader object. We save the csv.reader object as csv_reader. The reader object is used to read records as lists from a csv file. Now, we iterate through all the rows using a for loop. When we try to print each row, one can find that row is nothing but a list containing all the field values. Thus, all the records are displayed as lists separated by comma. Supplement – Computer Science with Python–XII In the next implementation, we will count the number of records present inside the student.csv file. Practical Implementation–25 Write a program to read the contents of “student.csv” file using with open(). 4.12 The above modified code uses “with open()” function, the only difference being that the file being opened using with open() gets automatically closed after the program execution gets over, unlike open() where we need to give close() statement explicitly. Practical Implementation–26 Write a program to count the number of records present in “student.csv” file. Explanation: In the above program, a special type of object is created to access the CSV file (reader object), which is csv_reader using the reader() function. The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. The function next() is used to directly point to this list of fields to read the next line in the CSV file..next() method returns the current row and advances the iterator to the next row. The variable ‘c’ is used as a counter variable to count the number of rows/records present in this file, which is finally printed and thus the output is so obtained. One of the important observations from the output is the number of records which is being displayed as 11 instead of 10. This is so because the header (first line) in the student csv file is also Data File Handling (Additions) treated as a record only. This limitation is overcome in the next implementation. CTM:.next() method returns the current row and advances the iterator to the next row. 4.13 Practical Implementation–27 Program to count the exact number of records present in the csv file excluding the header. In the above program we have used line_num object of CSV file. Our csv_reader_object has a method called line_num that returns the number of lines in our CSV. Then, if statement checks if the line is the first line or not. If the condition is true, i.e., if it is the header line, then it is ignored using continue statement and the counting of records is resumed from the second line onwards. Also, line_num object always stores the current line in consideration and, hence, the correct output for 10 records is so obtained. CTM: line_num is nothing but a counter which returns the number of rows which have been iterated. Practical Implementation–28 Program to print the records in the form of comma separated values, instead of lists. Supplement – Computer Science with Python–XII 4.14 In the above program, we have used a new function join(). join() is a string method that joins all values of each row with comma separator. Thus, all the records are displayed as a string separated by a comma separator and not as a list and hence the output is so obtained. Practical Implementation–29 Program to search the record of a particular student from CSV file on the basis of inputted name. Till now we have covered the basics of how to use the CSV module to read the contents of a CSV file. Now, we will discuss how to write to a CSV file in Python. 4.15.2 Writing to a CSV File To write to a CSV file in Python, we can use the csv.writer() function. The csv.writer() function returns a writer object that converts the user’s data into a delimited string. This string can later be Data File Handling (Additions) used to write into CSV files using the writerow() function. In order to write to a CSV file, we create a special type of object to write to the CSV file “writer object”, which is defined in the CSV module, and which we create using the writer() function. The writerow() method allows us to write a list of fields to the file. The fields can be strings or numbers or both. Also, while using writerow(), you do not need to add a new line character (or other EOL indicator) to indicate the end of the line; writerow() does it for you as necessary. 4.15 Let us write data onto a CSV file using writerow() method. Practical Implementation–30 Program to write data onto “student” CSV file using writerow() method. Supplement – Computer Science with Python–XII 4.16 Contents of “marks.csv” created: Explanation: In the above program, the very first line is for importing csv file into your program. Next, whatever are the column headings for our data are mentioned as a list in the variable called fields. All the data stored inside these fields is placed inside the variable called rows. Now give the name of your file, let us say, student.csv. This will be created and stored inside your current working directory or the path that you mentioned (as we have given for D:/) for the attribute “filename”. ‘w’ stands for write mode and we are using the file by opening it using “with open”, since using with open does not require the file to be closed explicitly. The next statement comprises the most important function used for writing onto csv file, viz. csv.writer(), to obtain a writer object and store it in the variable csv_w as the name of the variable, and this is the CSV object. writer() takes the name of file object ‘f’ as the argument. By default, the delimiter is comma (,). writerow(fields) is going to write the fields which are the column headings into the file and have to be written only once. Using for loop, rows are traversed from the list of rows from the file. writerow(i) is writing the data row-wise in the for loop and in the end the file is automatically closed. Also, while giving csv.writer(), the delimiter taken is comma. We can change the delimiter whenever and wherever required by changing the argument passed to delimiter attribute. For example, delimiter = "|" (pipe symbol). You can put any character as delimiter and if nothing is Data File Handling (Additions) given, comma is placed by default. writerow() method is used to write each row. In this program, we have used for loop for writing data row-wise onto the file using writerow() method. We can avoid using for loop and can write all the rows/records in one go. This can be done by using writerows() method. writerows() writes all the rows in one go, so you need not use for loop and iterations. 4.17 Practical Implementation–31 Program to write data onto "student" csv file using writerows() method (modification of Practical Implementation–30). Supplement – Computer Science with Python–XII MEMORY BYTES Files in Python are interpreted as a sequence or stream of bytes stored on some storage media. The close() method of a file object flushes any unwritten information and closes the file object. The rename() method is used to rename the file or folder. OBJECTIVE TYPE QUESTIONS 1. Fill in the blanks. (p)..................... format is a text format accessible to all applications across several platforms. 4.18 (q)..................... method is used for random access of data in a CSV file. (r)..................... method of pickle module is used to write an object into binary file. (s)..................... method of pickle module is used to read data from a binary file. (t)..................... statement is given for importing csv module into your program. (u)..................... is a string method that joins all values of each row with comma separator in CSV. (v)..................... object contains the number of the current line in a CSV file. (w) To end all the file contents in the form of a list,..................... method is used. (x) To read all the file contents,..................... method may be used. (y) To force Python to write the contents of file buffer on to storage file,.............. method may be used. Answers: (p) CSV (q) seek() (r) dump() (s) load() (t) import csv (u) join() (v) line_num (w) readlines() (x) writelines() (y) flush() 2. State whether the following statements are True or False. (p) CSV module can handle CSV files correctly regardless of the operating system on which the files were created. (q) CSV module gets automatically imported into your program for reading a CSV file. (r) The type of operation that can be performed on a file depends upon the file mode in which it is opened. (s) Functions readline() and readlines() are essentially the same. (t) Every record in a CSV file is stored in reader object in the form of a list. (u) writerow() method allows us to write a list of fields to the CSV file. (v) Comma is the default delimiter for a CSV file. (w) tell() method of Python tells us the current position within the file. (x) The offset argument to seek() method indicates the number of bytes to be moved. (y) If the offset value is set to 2, beginning of the file would be taken as seek position. Answers: (p) True (q) False (r) True (s) False (t) True (u) True (v) True (w) True (x) True (y) False 3. Multiple Choice Questions (MCQs) (p) Which of the following is not a valid mode to open a file? (i) ab (ii) rw (iii) r+ (iv) w+ (q) Which statement is used to change the file position to an offset value from the start? (i) fp.seek(offset, 0) (ii) fp.seek(offset, 1) (iii) fp.seek(offset, 2) (iv) None of the above (r) The difference between r+ and w+ modes is expressed as? (i) No difference (ii) In r+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for w+ (iii) In w+ mode, the pointer is initially placed at the beginning of the file and the pointer is at the end for r+ (iv) Depends on the operating system (s) What does CSV stand for? Data File Handling (Additions) (i) Cursor Separated Variables (ii) Comma Separated Values (iii) Cursor Separated Values (iv) Cursor Separated Version (t) Which module is used for working with CSV files in Python? (i) random (ii) statistics (iii) csv (iv) math (u) Which of the following modes is used for both writing and reading from a binary file? (i) wb+ (ii) w (iii) wb (iv) w+ (v) Which statement is used to retrieve the current position within the file? (i) fp.seek() (ii) fp.tell() (iii) fp.loc (iv) fp.pos (w) What happens if no arguments are passed to the seek() method? (i) file position is set to the start of file (ii) file position is set to the end of file (iii) file position remains unchanged (iv) results in an error 4.19 (x) Which of the following modes will refer to binary data? (i) r (ii) w (iii) + (iv) b (y) Every record in a CSV file is stored in reader object in the form of a list using which method? (i) writer() (ii) append() (iii) reader() (iv) list() Answers: (p) (ii) (q) (i) (r) (ii) (s) (ii) (t) (iii) (u) (i) (v) (ii) (w) (iv) (x) (iv) (y) (iii) SOLVED QUESTIONS 35. Write a Python code to find out the size of the file in bytes, number of lines and number of words. Ans. # reading data from a file and find size, lines, words f = open('Lines.txt', 'r') str = f.read() size = len(str) print('size of file n bytes ', size) f.seek(0) L = f.readlines() word = L.split() print('Number of lines ', len(L)) print('Number of words ', len(word)) f.close() 36. Consider the following code: f = open("test", "w+") f.write("0123456789abcdef") f.seek(-3,2) //Statement 1 print(f.read(2)) //Statement 2 Explain statement 1 and give output of statement 2. Ans. Statement 1 uses seek() method that can be used to position the file object at a particular place in the file. Its syntax is: fileobject.seek(offset [, from_what]) So, f.seek(–3,2) positions the fileobject to 3 bytes before end of file. Output of Statement 2 is: de It reads 2 bytes from where the file object is placed. 37. Yogendra intends to position the file pointer to the beginning of a text file. Write Python statement for the same assuming “F” is the Fileobject. Ans. F.seek(0) Supplement – Computer Science with Python–XII 38. Differentiate between file modes r+ and rb+ with respect to Python. Ans. r+ opens a file for both reading and writing. The file pointer is placed at the beginning of the file. rb+ opens a file for both reading and writing in binary format. The file pointer is placed at the beginning of the file. 39. In which of the following file modes will the existing data of the file not be lost? rb, ab, w, w+b, a+b, wb, wb+, w+, r+ Ans. In file modes rb, ab, a+b and r+, data will not be lost. In file modes w, w+b, wb, wb+ and w+, data will be truncated, i.e., lost. 40. Write a statement in Python to perform the following operations: (a) To open a text file “Book.txt” in read mode (b) To open a binary file “Book.dat” in write mode Ans. (a) f = open("Book.txt", "r") (b) f = open("Book.dat", "wb") 41. What is a CSV file? Ans. CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. 4.20 42. What are the advantages of CSV file formats? Ans. Advantages: (a) A simple, compact and ubiquitous format for data storage. (b) A common format for data interchange. (c) It can be opened in popular spreadsheet packages like MS Excel, Cal, etc. (d) Nearly all spreadsheets and databases support import/export to CSV format. 43. Differentiate between a text file and a binary file. Ans. A text file stores data as ASCII/UNICODE characters whereas a binary file stores data in binary format (as it is stored in memory). Internal conversion is required in text file and, hence, it is slower but binary file does not need any translation and so is faster. 44. Write a program to add (append) Employee records onto a CSV file. Ans. import csv with open('myfile.csv',mode = 'a') as csvfile: mywriter = csv.writer(csvfile, delimiter = ',') ans = 'y' while ans.lower() == 'y': eno = int(input("Enter Employee Number:")) name = input("Enter Employee Name:") salary = int(input("Enter Employee Salary:")) mywriter.writerow([eno,name,salary]) print("## Data Saved… ##") ans = input("Add More?") 45. Write user-defined functions to perform read and write operations onto a student.csv file having fields roll number, name, stream and marks. Ans. import csv row = ['2','Akshat Chauhan','Commerce','98'] def readcsv(): with open("D:/student.dat", 'r') as f: data = csv.reader(f) # reader function to generate a reader object for row in data: print(row) def writecsv(): with open("D:/student.dat", 'w', newline='') as fobj: # write new record in file csv_w = csv.writer(fobj, delimiter=',') csv_w.writerow(row) print("Press-1 to Read Data and Press-2 to Write data: ") a = int(input()) if a == 1: readcsv() elif a == 2: writecsv() else: Data File Handling (Additions) print("Invalid value") 46. Write a Python program to read specific columns from a “department.csv” file and print the content of the columns, department id and department name. Ans. import csv with open('departments.csv', newline=") as csvfile: data = csv.reader(csvfile) print("ID Departmentalize") print("---------------------------------") for row in data: print(row, row) 4.21 47. Explain briefly the CSV format of storing files. Ans. The acronym CSV is short for Comma Separated Values, which refers to tabular data saved as plain text where data values are separated by commas. In CSV format: Each row of the table is stored in one row, i.e., the number of rows in a CSV file are equal to the number of rows in the table (or sheet or database table, etc.). The field values of a row are stored together with commas after every field value; but after the last field’s value, no comma is given, just the end of line. 48. Write a menu-driven program implementing user-defined functions to perform different functions on a csv file “student” such as: (a) Write a single record to csv. (b) Write all the records in one single go onto the csv. (c) Display the contents of the csv file. Ans. import csv # To create a CSV File by writing individual lines def CreateCSV1(): # Open CSV File Csvfile = open('student.csv', 'w', newline='') # CSV Object for writing Csvobj = csv.writer(Csvfile) while True: Rno = int(input("Rno:")) Name = input("Name:") Marks = float(input("Marks:")) Line = [Rno, Name, Marks] # Writing a line in CSV file Csvobj.writerow(Line) Ch = input("More(Y/N)?") if Ch == 'N': break Csvfile.close() # Closing a CSV File # To create a CSV File by writing all lines in one go def CreateCSV2(): # Open CSV File Csvfile = open('student.csv', 'w', newline='') # CSV Object for writing Csvobj =csv.writer(Csvfile) Lines = [] while True: Rno = int(input("Rno:")) Name = input("Name:") Marks = float(input("Marks:")) Supplement – Computer Science with Python–XII Lines.append([Rno, Name, Marks]) Ch = input("More(Y/N)?") if Ch == 'N': break # Writing all lines in CSV file Csvobj.writerows(Lines) Csvfile.close() # Closing a CSV File # To read and show the content of a CSV File def ShowAll(): # Opening CSV File for reading Csvfile = open('student.csv', 'r', newline='') # Reading the CSV content in object Csvobj = csv.reader(Csvfile) for Line in Csvobj: # Extracting line by line content print(Line) Csvfile.close() # Closing a CSV File print("CSV File Handling") while True: 4.22 Option = input("1:CreateCSV 2:CreateCSVAll 3:ShowCSV 4:Quit ") if Option == "1": CreateCSV1() elif Option == "2": CreateCSV2() elif Option == "3": ShowAll() else: break 49. (a) Create a binary file “employee” that stores the records of employees and display them one by one. (b) Display the records of all those employees who are getting salaries between 25000 to 30000. Ans. (a) import pickle f1 = open('emp.dat','rb') e = pickle.load(f1) for x in e: print(x) f1.close() (b) import pickle f1 = open('emp.dat','rb') e = pickle.load(f1) for x in e: if(e[x]>=25000 and e[x] 8.58 2. Server-Side Script Server-side scripting gets executed on the server before displaying the information requested. (a) ASP (Active Server Pages) It is a technology that is used to create dynamic web pages so that the user can see these pages without any specific web browser. The user does not require any specific web browser to view these pages. To create active server pages, a default scripting language is used, viz. VBScript and sometimes JSCRIPT. ASP pages are saved with the extension.ASP and not.html. Any web page that contains ASP code cannot be run simply by executing it through web browser; instead, the page must be requested through a web server that supports ASP. When a browser requests an ASP, the web server generates a page with HTML code and sends it back to the browser. ASP is also the short term used for Application Service Provider. Various services offered by ASP are: (i) It helps in creating interactive and dynamic web pages. (ii) It allows access to any data or databases and returns the result to web browser. (iii) It allows the user to dynamically edit, change or add any content of a web page. (iv) It provides security to a page as it is not executed by a web browser. (b) JSP (Java Server Pages) Java Server Pages (JSP) is a technology that helps software developers to create dynamic web pages based on HTML, XML or other document types. It was released in 1999 by Sun Microsystems. JSP is similar to PHP, but it uses the Java programming language. JSPs have dynamic scripting capability that is embedded in an HTML code. Java server pages can be run by a compatible web server with a servlet container, such as Apache Tomcat or Jetty. To process a JSP file, developers need a JSP engine, which is connected to a Web server. The JSP page is then compiled into a servlet, which is handled by the servlet engine. This phase is known as translation. The servlet engine then loads the servlet class and executes it to create dynamic HTML, which is then sent to the browser. A Java Server Pages compiler is a program that parses JSPs and converts them into executable Java Servlets. The various features of JSP are as follows: (i) Platform Independent: JSP can be deployed across many platforms. All these components can be run across web servers. (ii) Configured for reusability: JSP components can be reused across servlets, JavaBeans and Enterprise JavaBeans (EJB). (iii) Simple and easy to use: JSP is simple in the process of development and maintenance. CTM: Scripting languages are also often used by applications as control or configure languages. An example: Firefox is written in C/C++ and can be controlled with JavaScript. Computer Networks 8.59 Table: 8.1: Difference between Client-Side Scripting and Server-Side Scripting S.No. Client-Side Scripting Server-Side Scripting 1. Scripting runs through web browser. Scripting runs through web server. 2. The processing takes place on the end-user’s The processing takes place on the server side. computer. 3. The browser receives the page sent by the server Server executes server-side scripts to send out a and executes the client-side scripts. page but it does not execute client-side scripts. 4. Client-side scripting cannot be used to connect to Server-side scripting is used to connect to the the databases on the web server. databases that reside on the web server. 5. Client-side scripting can be blocked by the user. Server-side scripting cannot be blocked by the user. 6. Response from a client-side script is faster as Response from a server-side script is slower as compared to a server-side script because the compared to a client-side script because the scripts are processed on the local computer. scripts are processed on the remote computer. 7. Examples of client-side scripting languages are Examples of server-side scripting languages are Javascript, VBScript, etc. PHP, JSP, ASP, ASP.Net, Ruby, Perl, etc. 8.31 WEB 2.0 Web 2.0 is often known as World Wide Web for second generation where people collaborate with each other through social networking sites, blogs, wikis, folksonomies, video-sharing sites, hosted services, web applications and mashups. Web 2.0 offers more dynamic pages instead of static pages that allows users to create online applications. Web 2.0 also allows groups of people to work on multiple applications. For example, a user can work on a document or spreadsheet simultaneously, while in the background a computer keeps track of who made what changes, where and when. Web 2.0 tools are also less expensive than traditional software—many are even free. Because they are web-based, the need is only to update the browser. The various features of Web 2.0 are: Web-based applications can be accessed from anywhere. It provides multitasking. Supplement – Computer Science with Python–XII It is less expensive and provides dynamic pages. Specific problems can be solved by using simple applications. Value lies in content, not in the software used to display content. Transfer of data is readily shared. Employees and customers can create their own newsgroup. Social tools encourage people to create, collaborate, edit, categorize, exchange and promote information. Web 2.0 website uses a new programming language called AJAX (Asynchronous JavaScript and XML). 8.60 Applications supported by Web 2.0 are as follows: Blogging Social bookmarking RSS Wikis and other collaborative applications Interactive encyclopaedias and dictionaries Advanced Gaming CTM: Web 2.0 refers to added features and applications that make the web more interactive and easy to provide information using newsgroups, social networking sites, RSS, etc. 8.32 E-COMMERCE E-commerce (electronic commerce or EC) is the buying and selling of goods and services, or the transmitting of funds or data over an electronic network, primarily the internet. These business transactions occur either as business-to-business, business-to-consumer, consumer-to-consumer or consumer-to-business. The terms e-commerce and e-business are often used interchangeably. E-commerce is conducted using a variety of applications, such as email, online catalogues and shopping carts, EDI, File Transfer Protocol and web services. This includes business-to- business activities and outreach such as using email for unsolicited ads (usually viewed as spam) to consumers and other business prospects, as well as to send out e-newsletters to subscribers. More companies now try to entice consumers directly online, using tools such as digital coupons, social media marketing and targeted advertisements. SELF PRODUCTS E-COMMERCE BANK CUSTOMERS BANK PAYMENT SHIPPING WAREHOUSE The advantages of e-commerce include its round-the-clock availability, speed of access, wide availability of goods and services to the consumer, easy accessibility and international reach. 8.32.1 Payment Transactions through E-Commerce Computer Networks 1. Online Banking Online banking, also known as internet banking, e-banking or virtual banking, is an electronic payment system that enables customers of a bank or a financial institution to conduct a range of financial transactions through the financial institution’s website. 8.61 2. Mobile Banking Mobile banking is a service provided by a bank or a financial institution that allows its customers to conduct a range of financial transactions remotely using a mobile device such as a mobile phone or tablet, and using software, usually called an app, provided by the financial institution for the purpose. 8.32.2 Payment Apps and Services Payment apps are also referred to as Mobile Wallets. There are many payment apps available in the market which are very efficient to use and convenient to handle. The following are some of the wallets which are frequently used in the market. 1. Google Wallet 2. Apple Passbook 3. Paytm Wallet 4. Freecharge Wallet 5. MobiKwik Wallet 6. PayU 7. Square Wallet 8. PayPal 9. Dwolla 10. Venmo 11. Bharat Interface for Money (BHIM) App The online mode of payment has brought about a drastic change to marketing. There are many start-ups which are doing very well thanks to the online mode of payment. This revolution has taken the world by storm. 8.33 CLOUD COMPUTING Cloud computing provides computing and storage capacity services to the heterogeneous community of end-recipients. The name comes from the use of clouds as an abstraction for the complex infrastructure. Cloud Computing = Software as a Service + Platform as a Service + Infrastructure as a Service