0% found this document useful (0 votes)
26 views9 pages

Class 12 Python & SQL Revision Guide

This document provides key revision points for Class 12 Computer Science, covering Python basics, functions, exception handling, file types (text and binary), CSV files, data structures (stack), database concepts, SQL, and Python-SQL connectivity. It includes essential syntax, operations, and examples for each topic. The content is structured to aid students in their revision for examinations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views9 pages

Class 12 Python & SQL Revision Guide

This document provides key revision points for Class 12 Computer Science, covering Python basics, functions, exception handling, file types (text and binary), CSV files, data structures (stack), database concepts, SQL, and Python-SQL connectivity. It includes essential syntax, operations, and examples for each topic. The content is structured to aid students in their revision for examinations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Class 12 Computer Science

Keypoints for Revision

Python Revision (Class XI Basics)

 Python is an interpreted, high-level, general-purpose programming language.


 Indentation is mandatory in Python to define blocks of code.
 Identifiers are names given to variables, functions, classes, etc.
 Keywords are reserved words in Python (like if, else, while, for).
 Python supports mutable (list, dict, set) and immutable (int, str, tuple) data types.
 Operators: Arithmetic (+, -, *, /, %, //, **), Relational (>, <, >=, <=, ==, !=).
 Logical operators: and, or, not.
 Membership operators: in, not in.
 Identity operators: is, is not.
 Flow control: if, elif, else; loops - for, while.

Functions

 A function is a block of reusable code that performs a specific task.


 Built-in functions: Already available (len(), max(), min(), sum()).
 Functions defined in modules: Imported from libraries ([Link](), [Link]()).
 User-defined functions: Created by programmers using def keyword.
 Syntax: def function_name(parameters): body.
 Function arguments: values passed to a function.
 Parameters: variables that receive values in a function.
 Default parameters: Assigned if no value is provided.
 Positional parameters: Values passed in order.
 Keyword arguments: Values passed by parameter name.
 Function can return single or multiple values using return statement.
 Flow of execution: Top to bottom unless function is called.
 Local variables: Declared inside function, accessible only there.
 Global variables: Declared outside functions, accessible everywhere.
 Use global keyword to modify global variables inside a function.

Exception Handling

 Exception: Error that disrupts program execution.


 Examples: ZeroDivisionError, FileNotFoundError, ValueError.
 try block: Code that may cause error is placed here.
 except block: Handles the exception.
 finally block: Executes code whether exception occurs or not.
 Syntax: try: ... except ExceptionType: ... finally: ...
Text Files

 Two main file types: Text files and Binary files.


 Text files store data in human-readable form.
 Binary files store data in machine-readable form.
 CSV files store tabular data separated by commas.
 File path can be relative (current directory) or absolute (full path).
 Opening text files: open('[Link]', 'r').
 Modes: r (read), w (write), a (append), r+, w+, a+.
 Closing files: [Link]().
 Writing: write() for strings, writelines() for list of strings.
 Reading: read(), readline(), readlines().
 tell(): Returns current file position.
 seek(offset): Moves file pointer to given position.
 Manipulating data: read, modify, overwrite.

Binary Files

 Binary files are opened with modes: rb, wb, ab, rb+, wb+, ab+.
 Must import pickle module for binary file operations.
 [Link](object, file): Writes Python object into binary file.
 [Link](file): Reads Python object from binary file.
 Supports read, write, search, append, update.

CSV Files

 CSV: Comma Separated Values file format for tables.


 import csv module for CSV operations.
 Open CSV file: open('[Link]','r').
 Writing CSV: writer(), writerow(), writerows().
 Reading CSV: reader().
 Example: [Link](f).writerow(['Name','Age']).
 Example: for row in [Link](f): print(row).

Data Structures (Stack)

 Stack: Linear data structure, follows LIFO (Last In First Out).


 Push: Insert element at top.
 Pop: Remove element from top.
 Implement stack using Python list (append for push, pop() for pop).
 Example: [Link](10), [Link]().
Database Concepts

 Database: Organized collection of data.


 DBMS: Software for managing databases.
 Advantages: Data consistency, integrity, security.
 Relational database: Data stored in tables (relations).
 Table consists of rows (tuples) and columns (attributes).

Relational Model

 Relation: Table in relational model.


 Attribute: Column in a table.
 Tuple: Row in a table.
 Domain: Set of valid values for attribute.
 Degree: Number of attributes.
 Cardinality: Number of tuples.
 Candidate key: Attribute(s) uniquely identifying a row.
 Primary key: Chosen candidate key, unique and not null.
 Alternate key: Candidate keys other than primary key.
 Foreign key: Attribute referring to primary key of another table.

SQL

 SQL: Structured Query Language.


 Two types: DDL (Data Definition Language), DML (Data Manipulation Language).
 DDL: CREATE, ALTER, DROP.
 DML: INSERT, UPDATE, DELETE, SELECT.
 Data types: char(n), varchar(n), int, float, date.
 Constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY.
 CREATE DATABASE dbname;
 USE dbname;
 SHOW DATABASES;
 DROP DATABASE dbname;
 SHOW TABLES;
 CREATE TABLE student(id INT PRIMARY KEY, name VARCHAR(20));
 DESC student;
 ALTER TABLE student ADD age INT;
 ALTER TABLE student DROP age;
 ALTER TABLE student ADD PRIMARY KEY(id);
 ALTER TABLE student DROP PRIMARY KEY;
 DROP TABLE student;
 INSERT INTO student VALUES(1,'Rahul');
 DELETE FROM student WHERE id=1;
 UPDATE student SET name='Amit' WHERE id=2;
 SELECT * FROM student;
 Operators: +, -, *, / (Arithmetic); >,<,=,!= (Relational); AND, OR, NOT (Logical).
 Aliasing: SELECT name AS student_name FROM student;
 DISTINCT: SELECT DISTINCT city FROM student;
 WHERE clause filters rows.
 IN: SELECT * FROM student WHERE city IN('Delhi','Mumbai');
 BETWEEN: SELECT * FROM student WHERE age BETWEEN 18 AND 25;
 ORDER BY: SELECT * FROM student ORDER BY name ASC;
 NULL: Special marker for missing value.
 IS NULL: SELECT * FROM student WHERE age IS NULL;
 LIKE: SELECT * FROM student WHERE name LIKE 'A%';
 Aggregate functions: MAX(), MIN(), AVG(), SUM(), COUNT().
 GROUP BY groups rows for aggregation.
 HAVING filters groups.
 JOIN: Combines data from multiple tables.
 Cartesian product: SELECT * FROM A, B;
 Equi-join: SELECT * FROM A,B WHERE [Link]=[Link];
 Natural join: SELECT * FROM A NATURAL JOIN B;

Python-SQL Connectivity

 Python can connect to MySQL using [Link] module.


 connect(): Establishes connection to database.
 Syntax: con = [Link](host='localhost', user='root', password='pwd',
database='db'). In case of sqlite3, these parameters are not used.
 cursor(): Creates a cursor object to execute queries.
 execute(): Runs a SQL query.
 commit(): Saves changes permanently. Executed through connection object returned by
connect( ) method.
 fetchone(): Fetches one row from result set.
 fetchall(): Fetches all rows from result set.
 rowcount: It is a property that returns number of rows affected.
 Example: [Link]('INSERT INTO student VALUES(1,"Amit")').
 Placeholders: Use %s to safely pass parameters.
 Example: [Link]('INSERT INTO student VALUES(%s,%s)',(2,'Rahul')).
 Creating database applications requires proper exception handling.
 Always close connection using [Link]().
OUTPUT BASED QUESTIONS
ALL THE BEST

Common questions

Powered by AI

Python's 'try', 'except', and 'finally' blocks reinforce its error handling philosophy by encapsulating error-prone code segments in a protected environment where exceptions can be managed predictably and safely. The 'try' block allows testing of code that might throw an error, while the 'except' blocks handle specific exceptions, offering a clean, readable method to manage different error types gracefully. The 'finally' block ensures that cleanup actions—like releasing resources or closing open files—occur irrespective of whether an error is encountered, thereby maintaining program stability and reliability. This structured approach reflects Python's focus on simplicity and functionality, promoting robust error handling strategies that enhance software resilience and user experience .

Text and binary files in Python both serve as mediums for data storage, yet they differ significantly in format and specific operations. Text files store data in a human-readable format, typically manipulated with string-based functions like 'read()', 'write()', and 'writelines()'. Conversely, binary files store data in a machine-readable format, which requires different operations handled by the 'pickle' module, specifically 'pickle.dump()' and 'pickle.load()' for writing and reading Python objects. Text files focus on read and write operations with traditional strings and built-in data types, while binary files support broader, object-level persistence enabling complex data structures to be stored efficiently .

CSV files play a vital role in data management by storing tabular data in a simple, text-based format that is easily accessible and interpretable across various platforms. Python, with its 'csv' module, excels in facilitating interaction with CSV files through functions like 'reader()' and 'writer()'. These allow efficient reading of data into a list of records and writing of complex data structures formatted for CSV compatibility. Python's inherent capabilities, enhanced by this module, allow seamless data manipulation and facilitate comprehensive operations such as data parsing, transformation, and transfer across different systems, supporting a wide range of data-centric applications .

Indentation in Python programming is used to define blocks of code, which is crucial because it organizes the code into a readable and structured format. Unlike other languages that use braces or keywords to delimit blocks of code, Python relies on indentation to identify code groups and flow, such as within loops, functions, and conditionals. This design choice emphasizes Python's trademark readability and simplicity, enforcing consistency and reducing errors that may arise from misaligned braces or misplaced block delimiters .

Data structures such as stacks significantly enhance computational tasks in Python by providing an organized way to manage data according to Last In First Out (LIFO) principles. Stacks facilitate efficient storage and retrieval of data, simplifying tasks such as parsing expressions, backtracking algorithms, and memory management. Implemented using Python's list with 'append()' for 'push' and 'pop()' for retrieval, stacks support recursion optimization and algorithm design requiring temporary data preservation and orderly access. Their predictable operational model reduces complexity in coding structures like undo mechanisms, recursive function support, and navigational history tracking, crucial for many real-world applications .

Database Management Systems (DBMS) offer a structured approach to organizing, storing, and managing data through software designed to support consistent, secure, and efficient data handling. Relational databases, a type of DBMS, present marked improvements in data management due to their table-based structure, which embodies relationships between different data points through rows and columns. This structure facilitates data integrity, enforcing rules like primary and foreign keys, which uniquely identify records and define relationships. Moreover, the use of SQL (Structured Query Language) in relational databases streamlines data operations such as querying, updates, and schema modifications, further supporting robust data consistency and reducing redundancy .

Python being an interpreted language presents both philosophical and practical benefits. Philosophically, it embodies simplicity and ease of use, aligning with Python's design philosophy that values readability and minimalism. Practically, interpretation offers immediate execution of code, which aids rapid development and testing, as changes can be quickly run without the need for compilation. This facilitates exploratory programming styles, ideal for scripting, data analysis, and rapid prototyping. For developers, this means more immediate feedback and interaction with data, accelerating development cycles and innovation, while for users, it often results in faster deployment and iteration of software solutions .

Exception handling in Python is significant because it provides a systematic way to manage and respond to runtime errors, ensuring program stability and robustness. By enclosing code that may cause an error in a 'try' block, developers can intercept and handle potential exceptions using 'except' blocks. This prevents the program from crashing and allows specific errors to be managed appropriately, such as logging an error message or attempting an alternative action. The 'finally' block ensures that crucial bottom-line code, like resource deallocation or state-saving actions, are executed regardless of whether an error occurred, thereby preserving program continuity and integrity .

In Python, variable scope determines where in a program a variable may be accessed. Local variables are declared inside a function and are accessible only within it, while global variables are declared outside of any function, making them accessible throughout the code. Within a function, global variables can be accessed and modified using the 'global' keyword, allowing the function to alter global state. This keyword explicitly tells Python to use the variable from the global scope, avoiding the creation of a new local variable when assignment statements are executed within the function .

Python's SQL database connectivity, facilitated by libraries like 'mysql.connector', significantly streamlines database operations and enhances application efficiency by providing a seamless interface for executing SQL queries within Python scripts. This integration allows developers to establish database connections, perform data retrieval and updates, and manage transactions using Python code, benefiting from Python’s dynamic features alongside robust SQL database capabilities. With functions such as 'connect()', 'execute()', and 'commit()', complex database operations can be executed efficiently, and transaction safety is maintained. This combination supports efficient data handling, ease of maintenance, and scalability for Python-driven applications .

You might also like