💿 Computer Science TTR
Computer Science Things To Remember 🖥
Click the link below:
1. Python Things To Remember 🐍 : Python TTR
2. File Handling Things To Remember 📁 : File Handling TTR
3. My SQL Things To Remember 📊 : My SQL TTR
🐍 Python TTR
Python Things To Remember
Exception Handling
Syntax
raise Exception(“Text”) assert(10>100), “Not possible”
try: a = int(“abc”) print(10/0) except ZeroDivisionError: print(“Division by zero not possible”) except: print(“Some error”) else: print(“No exception has been raised if this prints”) finally:
print(“Always prints regardless of exception or not”)
Stack
Class 11 Python
Python Keywords
Python Data Types
Mutable (Changeable) and Immutable (Not Changeable) Data Types
Operators:
1. Arithmetic Operators: a. + b. - c. d. / e. % f. // g. *
2. Relational Operators: a. == b. != c. > d. < e. >= f. <=
3. Assignment Operators: a. = b. += c. -= d. /= e. %= f. //= g. **=
4. Logical Operators: a. and b. or c. not
5. Identity Operators: a. is b. is not
6. Membership Operators:
a. in b. not in
Order of Precedence
Explicit Conversion (Type Casting) When data type conversion takes place because the programmer forced it in the program.
Implicit Conversion (Coercion) When data type conversion is done automatically by Python.
Argument (Functions) An argument is a value passed to the function during the function call.
Parameter (Functions) Parameter is defined in the function header.
Scope of a Variable The part of the program where a variable is accessible can be defined as the scope of that variable.
1. Global Variable: A variable that is defined outside any function or any block is known as a global variable.
2. Local Variable: A variable that is defined inside any function or a block is known as a local variable.
Built in Python Functions
Built in Modules
1. Math Module
2. Random Module
3. Statistics Module
String Functions
List Functions
Tuple Functions
Dictionary Functions
📁 File Handling TTR
File Handling Things To Remember
Definitions:
File : A file is a collection of related data stored in a particular area on the disk. Stream : It refers to a sequence of bytes. File handling is an important part of any web application. Data Files : The data files that store data pertaining to specific applications, for later use. Data files can be stored in two ways: Text Files : Text files are structured as a sequence of lines, where each line includes a sequence of characters. Binary Files : A binary file is any type of file that is not a text file.
Text Files:
1. file.read(n): Reads n bytes, if no n is given reads the entire file.
2. file.readline(n): Reads n bytes till it reaches EOF character, if no n is given reads till end of newline char.
3. file.readlines(): Reads all lines and returns it as a list. Note: All the read function has ‘\n’ at the end so to access the last character we need to use [-2]
4. file.seek(offset, from_where): Moves cursor of the file. From_where: a. 0: sets the cursor at the beginning of the file. b. 1: sets the cursor at the current position (only binary). c. 2: sets the cursor at the end of the file (only binary). Note: when using seek in binary mode in “2” mode, there are two characters at the end of a line ‘\r\n’
5. file.tell(): Gives the cursor's current position as an integer.
6. file.write(text): Writes the text to the file.
7. file.writelines(list): Write each sentence in a list. Note: writelines does not add EOF character so each string in list must have EOF character at the end.
Binary Files: import pickle # Creating A Binary File def create_file(): file = open("stud.DAT", "wb") n = int(input("Enter number of entries: ")) for i in range(n): roll = int(input("Roll No: ")) name = int(input("Name: "))
mark = int(input("Marks: ")) rec = [roll, name, mark] pickle.dump(rec, file) file.close()
Loading A Binary File def show_file(): file = open("stud.DAT", "rb") try: while True: print(pickle.load(file)) except: print("End of File") file.close()
CSV Files: import csv # Note: We use text mode for csv files, also ensure to define newline as empty file = open('file.csv', 'w', newline='') writer = csv.writer(file, delimiter=',', quotechar='"') writer.writerow(['Abinav', 12, 'C']) data = [['John', 12, 'A'], ['Doe', 11, 'B']] writer.writerows(data) file.close()
file = open('file.csv', 'r', newline='') # Note: Rows doesn't give data as a list, for loop is must or you need to convert to list rows = csv.reader(file) for row in rows: print(row) file.close()
Note: Data given by csv is always string, so for numbers we need to use int() to convert to integer.
📊 My SQL TTR
My SQL Things To Remember
Definitions
Relational Database: A database that has a collection of tables of data items, which are well described and organised according to the relational model.
Degree: Number of columns / attributes in a table. Cardinality: Number of rows / tuples in a table.
Relation/Table: Data placed / organised in rows and columns.
Domain: All possible unique values of a particular column.
Row/Tuple : Horizontal subset / information in a table is called tuple. Column/Attribute: Set of data values of a particular simple type, one for each row of the table.
Primary Key: A column that uniquely identifies a row within a table. Candidate Key: Columns that are eligible to act as a primary key. Alternate Key: Candidate keys other than the primary key. Foreign Key: Columns that are used to establish a link between two tables.
MySQL Commands
1. Show: a. SHOW DATABASES; b. SHOW TABLES;
2. Create:
a. CREATE DATABASE CBSE2024; b. CREATE TABLE PLAYERS(GCODE INT, GNAME VARCHAR(20), PRIZE_MONEY INT, SDATE DATE); c. CREATE TABLE PLAYERS(GCODE INT PRIMARY KEY, GNAME VARCHAR(20), PRIZE_MONEY INT, SDATE DATE); Note: Constraints can be defined with each value
- Not Null
- Primary Key
- Unique
3. Use: a. USE CBSE2024;
4. Describe: a. DESC PLAYERS;
5. Insert: a. INSERT INTO PLAYERS VALUES(101, ‘CARROM BOARD’, 2, 5000, ‘2004-01-23’);
6. Select: a. SELECT * FROM PLAYERS; b. SELECT GCODE FROM PLAYERS; c. SELECT GCODE, GNAME FROM PLAYERS d. SELECT GCODE AS “GAME CODE” FROM PLAYERS; e. SELECT DISTINCT GNAME FROM PLAYERS;
7. Mathematical Operations (Aggregate Functions): a. Sum: SELECT SUM(PRIZE_MONEY) FROM PLAYERS; b. Count: i. SELECT COUNT(*) FROM PLAYERS; ii. SELECT COUNT(GCODE) FROM PLAYERS; c. Max: SELECT MAX(PRIZE_MONEY) FROM PLAYERS; d. Min: SELECT MIN(PRIZE_MONEY) FROM PLAYERS; e. Avg: SELECT AVG(PRIZE_MONEY) FROM PLAYERS;
Note: Always gives a float number.
8. Where: a. Comparison: i. SELECT FROM PLAYERS WHERE GCODE = 101; ii. SELECT FROM PLAYERS WHERE GCODE != 101; iii. SELECT FROM PLAYERS WHERE PRIZE_MONEY > 10000; iv. SELECT FROM PLAYERS WHERE PRIZE_MONEY < 10000; v. SELECT FROM PLAYERS WHERE PRIZE_MONEY <= 9000; vi. SELECT FROM PLAYERS WHERE PRIZE_MONEY >= 12000; vii. SELECT FROM PLAYERS WHERE SDATE > ‘2003-12-30’; viii. SELECT FROM PLAYERS WHERE SDATE BETWEEN ‘2003-12-30‘ AND ‘2004-12-30’; b. Like (Wildcard): Note: % sign is used to ignore all characters before or after. _ sign ignore the character before or after it i. SELECT FROM PLAYERS WHERE GNAME LIKE ‘%TENNIS’; ii. SELECT FROM PLAYERS WHERE GNAME LIKE ‘BALL%’; iii. SELECT * FROM PLAYERS WHERE GNAME LIKE ‘% %’; # Gives all elements with space in between. c. Mathematical Operations:
i. SELECT FROM PLAYERS WHERE PRIZE_MONEY%3 = 0; # Gives all elements that are divisible by 3 d. Miscellaneous Operations: i. SELECT FROM PLAYERS WHERE GCODE IN (101, 102, 103); ii. SELECT FROM PLAYERS WHERE GCODE NOT IN (104, 105, 106); iii. SELECT FROM PLAYER WHERE GCODE IS NOT NULL;
9. Order By: a. Ascending Order: SELECT FROM PLAYERS ORDER BY GNAME ASC; b. Descending Order: SELECT FROM PLAYERS ORDER BY SDATE DESC;
10. Delete: DELETE FROM PLAYERS WHERE GCODE = 101; Note: If where clause is not there, the whole table will be deleted
11. Group By: a. SELECT COUNT(GCODE) FROM PLAYERS GROUP BY NUM; b. SELECT GNAME FROM PLAYERS GROUP BY NUM HAVING COUNT(*) > 2; c. SELECT GNAME FROM PLAYERS GROUP BY GNAME ORDER BY ROLL;
12. Alter Table: a. ALTER TABLE PLAYERS ADD PRIMARY KEY(GCODE); b. ALTER TABLE PLAYERS ADD FOREIGN KEY(ROLL) REFERENCES SPORTS(ROLL); c. ALTER TABLE PLAYERS ADD UNIQUE(GNAME); d. ALTER TABLE PLAYERS ADD AGE INT;
e. ALTER TABLE PLAYERS MODIFY AGE VARCHAR(255); f. ALTER TABLE PLAYERS MODIFY GNAME VARCHAR(255) NOT NULL; g. ALTER TABLE PLAYERS MODIFY AGE INT DEFAULT 18 ; h. ALTER TABLE PLAYERS DROP COLUMN AGE; i. ALTER TABLE PLAYERS DROP PRIMARY KEY; j. ALTER TABLE PLAYERS RENAME COLUMN GNAME TO NAME;
13. Update: a. UPDATE PLAYERS SET PRIZE_MONEY = 10000 WHERE GCODE=104;
14. Drop: a. DROP TABLE PLAYERS; b. DROP DATABASE CBSE2024;
15. Joining: a. Equi-Join: SELECT FROM TABLE1, TABLE2 WHERE TABLE1.COL = TABLE2.COL; SELECT FROM TABLE1 JOIN TABLE2 ON TABLE1.COL = TABLE2.COL; b. Natural-Join: SELECT * FROM TABLE1 NATURAL JOIN TABLE2;
Connectivity: import mysql.connector as sql
mycon = mysql.connector.connect(host='localhost', user='root', password='tiger') mycursor = mycon.cursor() roll = input('Enter Roll Number: ') name = input('Enter Name: ') class_ = input('Enter Class: ') marks = input('Enter Marks: ') mycursor.execute('use cbse2024')
mycursor.execute(f"insert into student values({roll}, '{name}', '{class_}', {marks})")
mycursor.close() mycon.commit() mycon.close()
import mysql.connector as sql
con = sql.connect(host='localhost', user='root', password='tiger') cur = con.cursor() cur.execute('use cbse2024') cur.execute('select * from student') print(cur.fetchall()) print(cur.fetchone())
Result When using Fetchall: [(102, 'Badminton', 2, 12000, datetime.date(2003, 12, 12)), (103, 'Table Tennis', 4, 8000, datetime.date(2004, 2, 14)), (104, 'Chess', 2, 9000, datetime.date(2004, 1, 1)), (108, 'Lawn Tennis', 4, 25000, datetime.date(2004, 3, 19)), (101, 'Carrom Board', 2, 5000, datetime.date(2004, 1, 23))]
Result When using Fetchone: (1, 'Abinav', '12', 50)