CS1.1.1
CS1.1.1
Text Files A file whose contents can be viewed using a text editor is called a text file. A text file is simply a sequence of ASCII or Unicode
characters. Python programs, contents written in text editors are some of the example of text files.
Binary FilesA binary file stores the data in the same way as as stored in the memory. The .exe files, mp3 file, image files, word documents
are some of the examples of binary files. We can’t read a binary file using a text editor.
Opening and Closing Files : To perform file operation, it must be opened first then after reading, writing, editing operation can be
performed. To create any new file then too it must be opened. On opening of any file, a file relevant structure is created in memory as well
as memory space is created to store contents. Once we are done working with the file, we should close the file. Closing a file releases
valuable system resource. In case we forgot to close the file, Python automatically close the file when program ends or file object is no
longer referenced in the program. However, if our program is large and we are reading or writing multiple files that can take significant
amount of resource on the system. If we keep opening new files carelessly, we could run out of resources. So be a good programmer, close
the file as soon as all task are done with it.
Mode & Description 1. r - reading only. Sets file pointer at beginning of the file. This is the default mode. 2 rb – same as r mode but
with binary file., 3. r+ - both reading and writing. The file pointer placed at the beginning of the file., 4. rb+ - same as r+ mode but with
binary file., 5. w - writing only. Overwrites the file if the file exists. If not, creates a new file for writing., 6. wb – same as w mode but
with binary file., 7. w+ - both writing and reading. Overwrites. If no file exists, creates a new file for R & W., 8. wb+ - same as w+ mode
but with binary file., 9. a -for appending. Move file pointer at end of the file.Creates new file for writing,if not exist., 10. ab – same as a
but with binary file
open() Function: The key function for working with files in Python is the open() function. The open() function takes two parameters;
filename, and mode.
Python Delete File Delete a File To delete a file, you must import the OS module, and run its os.remove() function
CSV FILE (Comma separated value)is a file format for data storage which looks like a text file. The information is organized with one
record on each line and each field is separated by comma.
CSV File Characteristics : • One line for each record • Comma separated fields • Space-characters adjacent to commas are ignored •
Fields with in-built commas are separated by double quote characters.
When Use CSV? • When data has a strict tabular structure • To transfer large database between programs • To import and export data
to office applications, Qedoc modules • To store, manage and modify shopping cart catalogue
CSV Advantages • CSV is faster to handle • CSV is smaller in size • CSV is easy to generate • CSV is human readable and easy to edit
manually • CSV is simple to implement and parse • CSV is processed by almost all existing applications
CSV Disadvantages • No standard way to represent binary data • There is no distinction between text and numeric values • Poor support
of special characters and control characters • CSV allows to move most basic data only. Complex configurations cannot be imported and
exported this way • Problems with importing CSV into SQL (no distinction between NULL and quotes)
Write / Read CSV FILE Writing and reading operation from text file is very easy. First of all, we have to import csv module for file
operation/method call. For writing, we open file in ‘w’ writing mode using open () method which create newFile like object. Through
csv.writer() method ,we create writer object to call writerow() method to write objects. Similarly for reading, we open the file in ‘r’ mode
and create newFile like object,further we create newfilereader object using csv.reader() method to read each row of the file. Three file
opening modes are there ‘w’,’r’,’a’. ‘a’ for append After file operation close, opened file using close () method
Aggregate Functions and GroupingMAX, MIN, AVG, SUM, COUNT: Perform calculations on data….., GROUP BY: Groups data by one or
more columns….., HAVING: Filters grouped data.
Joins Cartesian Product: Combines every row from one table with every row from another….,Equi-Join: Combines rows based on a
specified equality condition…., Natural Join: Joins tables using columns with the same name.
Function Description
list.append() Add an Item at end of a list…….., list.extend() Add multiple Items at end of a list………, list.insert() insert an Item at a
defined index………….., list.remove() remove an Item from a list del…….., list[index] Delete an Item from a list………., list.clear()
empty all the list………, list.pop() Remove an Item at a defined index…………….., list.index() Return index of first matched item………..,
list.sort() Sort the items of a list in ascending or descending order………, list.reverse() Reverse the items of a list……….,len(list) Return
total length of the list…………,max(list) Return item with maximum value in the list………, min(list) Return item with min value in the
list……….., list(seq) Converts a tuple, string, set, dictionary into list.
Stack: A stack is a linear data structure in which all the insertion and deletion of data / values are done at one end only. It is type of
linear data structure. It follows LIFO(Last In First Out) property. Insertion / Deletion in stack can only be done from top. Insertion in
stack is also known as a PUSH operation. Deletion from stack is also known as POP operation in stack.
Applications of Stack: • Expression Evaluation:- It is used to evaluate prefix, postfix and infix expressions. • Expression Conversion:- It can
be used to convert one form of expression(prefix,postfix or infix) to one another. • Syntax Parsing:- Many compilers use a stack for parsing
the syntax of expressions. • Backtracking:- It can be used for back traversal of steps in a problem solution. • Parenthesis Checking:- Stack is
used to check the proper opening and closing of parenthesis. • String Reversal:- It can be used to reverse a string. • Function Call:- Stack is
used to keep information about the active functions or subroutines.
Using List as Stack in Python: The concept of Stack implementation is easy in Python , because it support inbuilt functions (append() and
pop()) for stack implementation.By Using these functions make the code short and simple forstack implementation. To add an item to the
top of the list, i.e., to push an item, we use append() function and to pop out an element we use pop() function. These functions work quiet
efficiently and fast in end operations.
Queue: Queue is a data structures that is based on First In First Out (FIFO) stretagy ,i.e. the first element that is added to the queue is the
first one to be removed. • Queue followsthe FIFO (First - In - First Out) structure. • According to its FIFO structure, element inserted first will
also be removed first. • In a queue, one end is always used to insert data (enqueue) and the other is used to delete data (dequeue),
because queue is open at both its ends.
Applications of Queue: Synchronization :- When data are transferred to asynch devices then it is used to synchronized. Scheduling :-
When a resource is shared among multiple consumers. Searching :- Like breadth first search in graph theory. Interrupt handling :- Handling
of multiple interrupt as the order they arrive.
Using List as Queue in Python: The concept of Queue implementation is easy in Python , because it support inbuilt functions (insert() and
pop()) for queue implementation.By Using these functions make the code short and simple for queue implementation. To add an item at
front of the queue, i.e., to enqueue an item, we use insert() function and to dequeue an element we use pop() function. These functions
work quiet efficiently and fast in end operations.
Using Module It is a file which contains python functions/global variables/clases etc. It is just .py file which has python executable code /
statement.
Using Package It is namespace that contains multiple package or modules. It is a directory which contains a special file_init_.py
Using Library It is a collection of various packages. Conceptually,There is no difference between package and python library.In Python, a
library is used loosely to describe a collection of the core modules. ‘standard library‘ of Python language comes bundled with the core
Python distribution are collection of exact syntax, token and semantics of the Python language . The python standard library lists down
approx more than 200 such core modules that form the core of Python. “Additional libraries” refer to those optional componentsthat are
commonly included in Python distributions. The Python installers automatically adds the standard library and some additional libraries.
The additional library is generally provided as a collection of packages. To use such additional library we have to use packaging tools like
easyinstall or pip to install such additional libraries
Using Framework Framework is like a collection of various libraries which architects some more component.
A database is a structured collection of data that is organized and stored in a way that allows for efficient retrieval, management, and
manipulation of information. It serves as a central repository for storing and managing data, making it a fundamental component of
modern information systems. Here, we will delve into the basics of database concepts and understand why they are essential.
Data Organization: Databases provide a structured way to organize data. Instead of storing information in isolated files or spreadsheets,
databases allow for the systematic arrangement of data into tables, rows, and columns. This organization simplifies data management and
retrieval.
Data Integrity: Maintaining data accuracy and consistency is crucial for any organization. Databases employ mechanisms such as
constraints, validation rules, and data relationships to ensure data integrity. This reduces the risk of errors and data inconsistencies.
Data Security:Databases offer security features to control access to data. User authentication, authorization, and encryption help protect
sensitive information from unauthorized access or tampering.
Efficient Data Retrieval: With databases, you can quickly retrieve specific pieces of information using structured query languages (SQL).
This efficient data retrieval is vital for applications like customer relationship management (CRM), e-commerce, and more.
Concurrency Control: In multi-user environments, where multiple users access and modify data simultaneously, databases employ
concurrency control mechanisms to prevent data conflicts and ensure data consistency.
Scalability: As an organization grows, so does its data. Databases provide scalability options, allowing organizations to handle increasing
amounts of data efficiently by adding more hardware resources or optimizing database design.
Data Analysis: Databases are crucial for data analysis and business intelligence. They enable the storage of historical data, which can be
analyzed to make informed decisions, track trends, and forecast future performance.
Data Backup and Recovery: Databases offer backup and recovery features to safeguard against data loss due to hardware failures,
accidents, or disasters. Regular backups ensure that data can be restored in case of emergencies.
Data Redundancy Reduction: Databases minimize data redundancy by storing data in normalized tables. This reduces storage
requirements and ensures consistency by updating data in one place.
Support for Complex Data Types: Modern databases can handle complex data types such as images, videos, and JSON documents,
making them versatile for various applications.
Components of the Relational Data Model
Relation:A relation is a table in the relational data model.It consists of rows and columns.Each row represents a record or tuple of an
individual, and each column represents an attribute or field holding the same property.
Attribute:An attribute is a characteristic or property of an entity represented as a column in a relation.For example, in a “Customers”
relation, attributes might include “CustomerID,” “Name,” “Email,” and “Phone.”
Tuple:A tuple is a row in a relation.It represents a single instance or record of data.Each tuple contains values for each attribute defined
in the relation.
Domain:A domain specifies the set of allowable values for a particular attribute.For instance, the domain of the “Age” attribute might be
defined as integers between 0 and 100.It can be termed as range.
Degree:The degree of a relation is the number of attributes it contains.It indicates the complexity and structure of the relation.
Cardinality:Cardinality refers to the number of tuples in a relation.It signifies the size of the data set represented by the relation.
Keys in the Relational Data Model
Candidate Key:A candidate key is a minimal set of attributes that can uniquely identify each record / tuple in a relation / table.There can
be multiple candidate keys in a relation.One of them will be chosen as the primary key.
.
Primary Key:The primary key is a specific candidate key chosen to uniquely identify each record / tuple.It must be unique and cannot
contain NULL values.It is used for data retrieval and integrity enforcement.
Alternate Key:Alternate keys are candidate keys that are not selected as the primary key.They can still be used for uniqueness constraints
or as reference keys in other relations.
Foreign Key:A foreign key is an attribute or set of attributes in one relation that refers to the primary key of another relation.It
establishes relationships between tables and enforces referential integrity.Foreign keys ensure that values in the referencing table exist in
the referenced table.
SQL (Structured Query Language) is a powerful and standardized language used for managing and manipulating relational databases. It
provides a structured and efficient way to interact with databases, enabling tasks such as data retrieval, insertion, deletion, and schema
definition. In this set of notes, we will explore various aspects of SQL.
Data Definition Language (DDL) and Data Manipulation Language (DML)
DDL deals with defining the database structure, including creating, altering, and deleting tables and databases.
DML focuses on manipulating data within the database, such as inserting, updating, and deleting records.
Data TypesSQL supports various data types to specify the kind of data that can be stored in each column of a table:CHAR(n): Fixed-
length character strings with a specified maximum length ‘n’.,., VARCHAR(n): Variable-length character strings with a maximum length of
‘n’. INT: Integer data type for whole numbers.,, FLOAT: Floating-point number data type for decimals.,,, DATE: Date data type for
storing dates.
ConstraintsSQL allows you to apply constraints to columns for data integrity:NOT NULL: Ensures that a column cannot contain NULL
values…, UNIQUE: Enforces unique values within a column
Database OperationsCREATE DATABASE: Creates a new database…, USE DATABASE: Specifies the database to be used….., SHOW
DATABASES: Lists all available databases….., DROP DATABASE: Deletes a database….., SHOW TABLES: Displays a list of tables in the
current database……, CREATE TABLE: Creates a new table with specified columns and data types……, DESCRIBE TABLE: Provides
information about the structure of a table….., ALTER TABLE: Modifies the structure of an existing table, including adding or removing
columns and altering primary keys………, DROP TABLE: Deletes a table and its data.
Data ManipulationINSERT: Adds new records into a table…, DELETE: Removes records from a table….., SELECT: Retrieves data from
one or more tables……,Operators: Mathematical (+, -, *, /), relational (=, <>, >, <, >=, <=), and logical (AND, OR, NOT)
operators……..,Aliasing: Renaming columns or tables for readability……,DISTINCT: Retrieves unique values from a
column……..,WHERE: Filters rows based on a specified condition……, IN: Checks for a value within a list….,BETWEEN: Filters rows
within a specified range……ORDER BY: Sorts query results……NULL: Represents missing or unknown data…….IS NULL: Tests for NULL
values……..,IS NOT NULL: Tests for non-NULL values…….,LIKE: Searches for a specified pattern…..,UPDATE: Modifies existing
data……,DELETE: Removes data from a table
Local Environment First check-in the local namespace or local function or local environment, found then use it, otherwise move to
Enclosing environment.
Enclosing Evironment If not found in Local, then it checks inside the enclosing namespace, if found then ok, otherwise moves to the
global namespace.
Global Environment If not found in Enclosing, it checks inside the global namespace, if found then ok, otherwise move to the Built-in
namespace.
Built-in Environment If not found in Global, it checks inside the Built-in namespace, if found then ok, otherwise raises an Error message –
NameError: name ‘varName’ is not defined.
Local ScopeA variable that is defined in the function called Local Variable and it has local scope.
LifetimeThe time for which a variable remains in memory is called Lifetime of Variable. It depends on the scope of the variable.
FunctionsPython provides the features to divide a large program into different smaller modules, called Functions. A Function is a group of
statements i.e. subprogram, that exists within a program for the purpose of performing specific tasks, and returns values/results whenever
it is required.Functions can take some data as input, process upon according to the instructions, and give some output at the end. Example
– max( ), min( ), sum( ), type(), etc.
Types of FunctionsIn Python, Functions can be categorized into three categoriesBuilt-in functions Functions defined in
Modules User-defined Functions
(a) Built-in FunctionsBuilt-in Functions are the predefined functions that are already available in Python. These functions are always
available in the standard library, no need to import any module for them.
Most frequently used Built-in Functions 1.int( ) – to convert into an integer. 2.float ( ) – to convert into float. 3.bool ( ) – to
convert into Boolean. 4.str ( ) – to convert into a string. 5.list ( ) – to convert a sequence into a list. 6.tuple( ) – to convert
a sequence into a tuple. 7.dict( ) – to convert sequences into the dictionary. 8.input( ) – to input value as a string. 9.eval(
) – to evaluate strings in the form of expression. 10.print( ) – to print/show output. 11.range( ) – to define a series of
numbers, useful for a loop. 12.max( ) – to find the maximum numbers. 13.min ( ) – to find the minimum numbers.
14.sum( ) – to sum two numbers or a list or tuple. 15.abs( ) – to find the absolute value (i.e. positive number) of numbers.
16.round (n, p ) – rounds a given floating point number to the specified number of digits and returns the result. 17.len( ) –
returns the length of the sequence. 18.chr( ) – returns the equivalent ASCII character of the given number. 19.ord( ) – returns
the ordinal value (ASCII number) of the given character. 20.type ( ) – returns the data type of data or variable. 20.id( ) – returns
the memory reference of value or variable.
(b) Functions defined in ModuleThese functions are pre-defined in particular modules and can only be used when the corresponding
module is imported.For example, 1.randint() function of the random module. 2.pow() function of the math module,
3.mean() module of the statistics module, 4.dump() function of the pickle module, 5.reader() function of csv module,
6.connect() function of mysql.connector module.
Calling / Invoking a FunctionA function definition defines user-defined functions. The function definition does not execute the function
body; this gets executed only when the function is called or invoked.Calling of function means, invoking or accessing or using the function.
To execute a function, invoke a function by its name and parameters inside the parenthesis (), if required. Syntax:
1.Function_Name( ) 2.Function_Name (arguments or parameters) 3.Res = Function_Name( ) 4.Res =
Function_Name( arguments / parameters)
Arguments: Values being passed by function call statement, are called arguments. Also called actual parameter or actual argument
Parameters: Values being received by function definition statement, are called parameters. Also called formal parameter and formal
argument.
Positional Arguments When the function call statement must match the number and order of arguments defined in the function
definition, such types of arguments are called Positional Arguments / Required Arguments / Mandatory Arguments.The process of
matching arguments is called Positional Argument Matching.
Default ArgumentsPython allows us to assign default values(s) to a function’s parameter(s) which becomes useful when matching
arguments is not passed in the function call statement.
Keyword (Named) ArgumentThe default arguments allow to specify the default value for the parameters, but it does not allow to pass
the value by changing order i.e. arguments always passed in the same order. Keyword arguments are the named arguments with assigned
values being passed in the function call statement. Keyword argument allows us to write any argument in any order with the help of an
argument name. Using keyword arguments, we can pass argument values by keyword i.e. by parameter name.
Variable length argumentsPython allows us to pass variable number of arguments to a function, this is called Variable length
argument.Variable length arguments are declared with * (asterisk) symbol.
Non – Void FunctionsThe Functions that return some value / values as a result, is called as Non-void Functions. Functions can return
value with the help of return statement. return is a Python keyword. Functions returning a value are also known as Fruitful Functions.
Void FunctionsThe Functions that does not return any value, as a result, is called as Void Functions. In this case no need to write return
statement or you many write return statement without value.
Function Returning Multiple ValuesThe Functions that return multiple values i.e. more than one value are called Multi–Value returning
Functions. These are some examples of functions returning a single value.
Scope of a Variable Scope means the accessibility of variables in other parts of the program. The scope rules of Python, decide in which
parts of the program a particular variable can be accessed or not.
Global Scope:A variable that is defined in the ‘main’ program, is called Global Variable and it has global scope.
Local ScopeA variable that is defined in the function called Local Variable and it has local scope.
LifetimeThe time for which a variable remains in memory is called Lifetime of Variable. It depends on the scope of the variable.
QPython program that reverses a string. QWrite recursive code to compute the greatest common divisor
def reverse_string(s): of two number.
return s[::-1] def gcd(a, b):
s = "Hello, World!" if b == 0:
print(reverse_string(s)) return a
else:
QWrite a Python function that accepts a string and return gcd(b, a % b)
calculates the number of uppercase and lowercase print(gcd(60, 48))
letters.
def count_upper_lower(s): QWrite a user-defined function to generate odd numbers
upper = 0 between a and b.
lower = 0 def odd_numbers(a, b):
for i in s: for i in range(a, b+1):
if i.isupper(): if i % 2 != 0:
upper += 1 print(i)
elif i.islower(): odd_numbers(1, 10)
lower += 1
return upper, lower QA user-defined function findname(name) where name is an
s = "Hello, World!" argument in python to delete phone no. from a dictionary
print(count_upper_lower(s)) phonebook on the basis of the name, where name is the key.
phonebook = {
QWrite a Python program to print the even numbers "John": "1234567890",
from a given list. "Jane": "0987654321",
def even_numbers(lst): "Bob": "9876543210"
for i in lst: }
if i % 2 == 0: def findname(name):
print(i) if name in phonebook:
lst = [1, 2, 3, 4, 5, 6] del phonebook[name]
even_numbers(lst) print(f"{name}'s phone number has been deleted from the
phonebook.")
QPython function to check whether a number is else:
perfect or not. print(f"{name} is not in the phonebook.")
def is_perfect(n): findname("John")
sum = 0 print(phonebook)
for i in range(1, n):
if n % i == 0: QWrite a method in Python to find and display the prime
sum += i numbers from 2 to N.
if sum == n: def is_prime(n):
return True if n <= 1:
else: return False
return False for i in range(2, n):
print(is_perfect(6)) if n % i == 0:
return False
QRecursive code to compute and print sum of return True
squares of n numbers. Value of n is passed as def prime_numbers(n):
parameter. for i in range(2, n+1):
def sum_squares(n): if is_prime(i):
sum = 0 print(i)
for i in range(1, n+1): prime_numbers(20)
sum += i**2
return sum
print(sum_squares(5))