




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A comprehensive guide to file handling and data structures in python. It covers various aspects of file handling, including text files, binary files, and csv files. The document also explores the implementation of stacks using lists in python. It includes code examples and exercises to enhance understanding.
Typology: Study notes
1 / 174
This page cannot be seen from the preview
Don't miss anything!
AC,RO BENGALURU AC,RO BENGALURU AC,RO BENGALURU
Revision of Python Covered in Class- XI 1 SH. ASHOK SENGUPTA
2 MS. DIVYA C.K.
Function and Exception Handling 3 MS. PREETI SARKAR
4 MS. UMA TIWARI
File Introduction and Text File 5 MS. ANSHU JAIN
Binary File 7 SH. AMIT KUMAR GUPTA
8 SH. SUNIL KUMAR T
CSV File 9 MS. SUMITHA
Data Structure 11 SH. RAMESHA K.S.
Computer Networks 13 MS. POOJA KHARE
Database Management and Mysql 15 MS. SONAM DUTTA
Interface of Python with Mysql 17 SH. AMIT KUMAR SINHA
18 SH. SUNIL KUMAR C. K.
03 Sets of Sample Question Papers with Marking Scheme
Unit 2: Computer Networks
● Evolution of networking: introduction to computer networks, evolution of networking (ARPANET, NSFNET, INTERNET) ● Data communication terminologies: concept of communication, components of data communication (sender,receiver, message, communication media,protocols), measuring capacity of communication media (bandwidth, data transfer rate), IP address, switching techniques (Circuit switching, Packetswitching) ● Transmission media: Wired communication media (Twisted pair cable, Co-axial cable, Fiber-optic cable), Wireless media (Radio waves, Micro waves, Infrared waves) ● Network devices (Modem, Ethernet card, RJ45, Repeater, Hub, Switch, Router, Gateway, WIFI card) ● Network topologies and Network types: types of networks (PAN, LAN, MAN,WAN), networking topologies (Bus, Star, Tree) ● Network protocol: HTTP, FTP, PPP, SMTP, TCP/IP, POP3, HTTPS, TELNET, VoIP ● Introduction to web services: WWW, Hyper Text Markup Language (HTML),Extensible Markup Language (XML), domain names, URL, website, web browser, web servers, web hosting
Unit 3: Database Management
● Database concepts: introduction to database concepts and its need
● Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate key, primary key, alternate key, foreign key)
● Structured Query Language: introduction, Data Definition Language and Data Manipulation Language, data type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), create database, use database, show databases, drop database, show tables, create table, describe table, alter table (add and remove an attribute, add and remove primary key), drop table, insert, delete, select, operators (mathematical, relational and logical), aliasing, distinct clause, where clause, in, between, order by, meaning of null, is null, is not null, like, update command, delete command, aggregate functions (max, min, avg, sum, count), group by, having clause, joins: cartesian product on two tables, equi-join and natural join
● Interface of python with an SQL database: connecting SQL with Python, performing insert, update, delete queries using cursor, display data by using connect(),cursor(), execute(), commit(), fetchone(), fetchall(), rowcount, creating database connectivity applications, use of %s format specifier or format() to perform queries
INDEX
1 Revision of Python Covered in Class- XI
(^2) Function and Exception Handling
3 File Introduction and Text File
(^4) Binary File
(^5) CSV File
6 Data Structure
(^7) Computer Networks
8 Database Management and Mysql
9 Interface of Python with Mysql
(^10) Sample Question Paper- 1
11 Sample Question Paper- 2
(^12) Sample Question Paper- 3
Python character set:
A character set is a set of valid characters acceptable by a programming language in scripting. Python supports all ASCII / Unicode characters that include: o Alphabets: All capital (A-Z) and small (a-z) alphabets. o Digits: All digits from 0-9. o Alphabets: All capital (A-Z) and small (a-z) alphabets. o Special Symbols: Python supports all kinds of special symbols - " ' l ; :! ~ @ # $ % ^ ` & * ( ) _ + – = { } [ ] . o White Spaces: White spaces like tab space, blank space, newline, and carriage return. o Other: All ASCII and UNICODE characters are supported by Python that constitutes the Python character set.
Python Tokens:
A token is the smallest individual unit in a python program. All statements and instructions in a program are built with tokens. Token Types: o Keywords : Keywords are reserved by python environment and cannot be used as identifier. There are 35 keywords in python. You may try to use the following code to get a list of keywords supported in your python version.
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] o Identifier : Identifiers are the names given to any variable, function, class, list, methods, etc. for their identification. Python is a case-sensitive language, and it has some rules and regulations to name an identifier. Here are the rules. An Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can have digits but cannot start with a digit. An identifier can’t be a keyword. My_name, init, Seven10 are valid examples. 20dollers, my.var, True are invalid examples. o Literals : Literals are the values stored in program memory and are often referred to by an identifier.
String Literals : The text written in single, double, or triple quotes represents the string literals in Python.
Escape characters : To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. Some of the escape characters are as under:
Escape Character Result ' Single Quote " Double Quote \ Backslash \n New Line \t Tab \b Back space Numeric Literals : A number represented in various forms is a Numeric Literal. o Integer Literal : It includes both positive and negative numbers along with 0. It doesn’t include fractional parts. It can also include binary, decimal, octal, hexadecimal literal. o Float Literal : It includes both positive and negative real numbers. It also includes fractional parts. 99.62, 0.35E-7 are valid float literals. o Complex Literal : It includes a+bi numeral, here a represents the real part and b represents the complex part. Boolean Literal : Boolean literals have only two values in Python. These are True and False. Special (None) Literal : Python has a special literal ‘None’. It is used to denote nothing, no values, or the absence of value. Collection Literal : Literals collections in python includes list, tuple, dictionary, and sets. o Operators : Operators are responsible for performing various operations in Python. The operators are of two types Unary (Operates on single operand) and Operators that operates on two operands (binary). o Arithmetic Operators : Arithmetic operators are used with numeric values to perform common mathematical operations: Operators Name Example
o There are other operators like the Bitwise operators and lambda operator (function) - These are not in syllabus. o Operator precedence : In a mathematical or logical expression the operator precedence plays an important role to decide which operator will be executed first. The following table elaborates their precedence. Operator Remarks () Even though () is not an operator but it plays an important roe in deciding which part of the expression should be evaluated first. ** The unique feature of ** is that it is the only operator that is evaluated from right to left *, /, //, % All the four have same precedence +, - They are next == != > >= < <= is is not in not in
All the relational, identity and membership operators Not Not being a unary operator has precedence over and/or And Have higher precedence over or Or Lowest precedence
Some Interesting operations using operators that are often asked in Examinations :
Expression Output Explanation 2 ** 3 ** 2 512 Since ** is evaluated from right to left, first 32 is evaluated to 9 and 2 evaluated 512 10 or 20 10 If the first operand of an “or” expression is true, return the first operand. Otherwise, evaluate and return the second operand. 0 or 10 10 0 is False and hence second operand is returned. 10 and 20 20 If the first operand of an “and” expression is false, return the first operand. Otherwise, evaluate and return the second operand. Note: Any value is interpreted as “false” for the above purposes if it is 0, 0.0, None, False, or an empty collection. Otherwise, it is interpreted as “true” for the above purposes. So, 10 and 20, being nonzero numbers, are “true.” 25 % - 4 - 3 Python evaluates the modulus with negative numbers using the formula: (a//b) * b + a%b == a 25 //- 4 gives - 7 with floor division.
Q. 1 Which one of the following is not a valid identifier? a) true b) init c) 20 Decades d) My_var Q. 2 Which of the following keywords is a python operator? a) for b) break c) is d) else Q. 3 What will be the output of the operation print("\\\")? a) \\\ b) \
c) \ d) Error Q. 4 What will be the output of the expression print(10+2010//2*3-5) a) 30 b) 40 c) 1005 d) 130 Q. 5 Evaluate the expression print(20%-3)? a) - 1 b) - 2 c) 2 d) Error
Q. 6 What will be the result of the expression True of False and not True or True a) True b) False c) None d) Error Q.7 What will be the output of the following program? a = {'A': 10 ,'B': 20 } b = {'B': 20 , 'A': 10 } print(a==b and a is b) a) True b) False c) None d) Error Q. 8 Which of the following statements is false for python programming language? a) Python is free and Open source. b) Python is statically typed. c) Python is portable. d) Python is interpreted.
Python for loop:
Python for loop is used to iterate a set of python statements till a counter reaches its limit.
Python for loop can also be used to iterate over a collection object (List, tuple)/ iterable (string, dictionary) using membership operators.
Python while loop is used in situations where we have no idea as when the loop is going to end since there are no counters.
range() function in python : The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.
range() example Output sequence range( 10 ) 0 1 2 3 4 5 6 7 8 9 range(1,11) 1 2 3 4 5 6 7 8 9 10 range(1,11,2) 1 3 5 7 9 range(10,0,-1) 10 9 8 7 6 5 4 3 2 1
range(start, stop, step)
Step can be +ve or - ve
Stop can be +ve or - ve but is never reached.
Start can be +ve or - ve
break statement in a loop : The break statement stops the loop iteration and exits from the loop.
continue statement : Whenever a continue statement is encountered in a loop the remaining statements after the continue statement are not executed and the loop enters next iteration.
else block in loop : The else block in a loop is executed when the break statement is not encountered inside the loop.
Students are advised to go through the above content since various operations involving the python data structures, user defined functions, data file handling and database interaction will require a thorough understanding of iteration. In CBSE examination you may not get a direct question from this topic except for a few MCQ or Assertion-Reasoning based question.
The following question is an ASSERTION AND REASONING based Questions. Mark the correct choice as: i) Both A and R are true, and R is the correct explanation for A ii) Both A and R are true, and R is not the correct explanation for A iii) A is True but R is False iv) A is false but R is True Q. ASSERTION: In python loop else block will be executed if the loop successfully terminates after complete iteration. REASON: A python loop else block will not execute if a break statement is encountered in a loop. Q. ASSERTION: A continue statement in a loop is mandatory. REASON: A continue statement will skip the remaining statements in the loop after it is encountered.
The loops exits if the number n is divisible by any number between to and half of the number
The continue statement will not print any number that is odd
The loop else will be encountered only for a prime number since break will not get executed during any iterations
Indexing : Each character of a string can be accessed using two types of indexing. o Forward indexing : First character of a string has an index 0 and next has 1 and so on. o Reverse indexing : Last character of the string is having an index of - 1 and last but one has - 2 and so on.
We can access any element of the string using indexing.
Slicing : A substring can be acquired from an existing string using the slicing operation.
Traversal : We can traverse a string using iteration and specifically using for loop. o Iterate using membership :
o Iterate using indexing :
Str[start:stop:step]
Stop is not reached.
String Methods : Python has a few built-in and string library methods (also built-in) to manipulate strings. Some of them as elaborated below with examples. o Global Methods : These methods accept string as a parameter – methodName(string)
o String Library Methods : These methods have the syntax string.methodName()
Methods that return True or False : isalnum() – Returns True is the string comprises of only alphabets and digits
isalpha() – Returns True if all the characters are Alphabets
isdigit() – Returns True if all the characters are digits.
isspace() – Returns True if all the characters are spaces
isupper() – Returns True if all the characters are upper-case alphabets
and stop are optional.
find(substr) – Returns the index of the first occurrence of a substring inside a given String. The general format of this method is index(substr, start, stop) where stop index is not included. Both start and stop are optional. This is same as index()
index(substr) find(substr) This function throws a ValueError if the substring is missing from the string.
This function returns - 1 if the substring is missing from the string.
Methods that modify an existing string and returns a new string: capitalize(): Converts the first character of a string to upper case and all other alphabets to lower case. Incase the first character is not an Alphabet, only the remaining alphabets will be converted to lower case.
title(): Converts all the first characters of each word of a string to upper case, in case they are alphabets. The remaining alphabets are converted to lower case.
replace(oldsubstr, newsubstr): Replaces all the first parameter with the second parameter and returns a new string.
The first M is not included since the start index is 2 and hence the index value of the next M is 6
The start is 7 hence first two M’s are not included.
upper(): Converts all the lowercase alphabets in a string to upper case and returns a new string.
lower(): Converts all the uppercase alphabets in a string to lowercase and returns a new string.
Methods that create a new object from an existing string: partition(substr): Returns a tuple with three elements from a string where the middle element is the substring.
split() – Returns a list with a sequence of substrings by eliminating all the spaces and newlines from the existing string.
split(substr): Returns a list with a sequence of substrings by eliminating all the occurrences of the substring from the existing string.