HomeInfo

Class 12 Computer Science Notes

Like Tweet Pin it Share Share Email

In Class 12 Computer Science, the focus shifts to more advanced programming concepts and practical applications. Building on the foundation laid in Class XI, you will explore topics like functions, exception handling, file handling, and data structures in greater depth. These concepts are essential for writing efficient and organized code, enabling you to solve more complex problems. Additionally, you will learn about databases, computer networks, and other essential topics that prepare you for higher-level studies in computer science or for real-world applications in technology. The comprehensive understanding of these topics will help you develop strong computational thinking and problem-solving skills, which are critical in today’s tech-driven world.

Advertisements
  • Data Types: Different types of data like integers (int), floating-point numbers (float), strings (str), and booleans (bool).

    Example:

    python
    age = 18 # int
    price = 19.99 # float
    name = "Alice" # str
    is_student = True # bool
  • Variables: Names assigned to data stored in memory.

    Example:

    python
    x = 5
  • Operators: Symbols used to perform operations on variables and values.
    • Arithmetic operators (+, -, *, /)
    • Comparison operators (==, !=, >, <)
    • Logical operators (and, or, not)

    Example:

    python
    result = 5 + 3 # Output:
    8
    is_equal = (5 == 3) # Output: False
  • Control Flow: You learned how to control the flow of execution in a Python program using:
    • if, elif, else statements for decision-making.

      Example:

      python
      age = 18
      if age >= 18:
               print("You can vote!")
      else:
              print("You cannot vote.")
    • Loops like for and while to repeat actions.

      Example:

      python
      for i in range(5):
               print(i) # Output: 0, 1, 2, 3, 4
  • Functions: Blocks of code that perform a specific task and can be reused.

    Example:

    python
    def greet(name):
             print(f"Hello, {name}!")
    greet("Alice") # Output: Hello, Alice!

Functions

A function in Python is a block of code that only runs when it is called. Functions are useful because they allow code reusability and better organization.

Types of Functions

  • Built-in Functions: These are functions that Python provides out of the box, such as print(), len(), max(), etc.

    Example:

    python
    print(len("Hello")) # Output: 5
  • Functions Defined in a Module: These functions are not part of the core Python language but come from external libraries or modules such as math, random, etc.

    Example:

    python
    import math
             print(math.sqrt(16)) # Output: 4.0
  • User-defined Functions: Functions created by users to perform specific tasks. These functions are written using the def keyword.

    Example:

    python
    def greet(name):
          return f"Hello, {name}!"

Creating User-defined Functions

See also  12th Bipartite Settlement Salary Calculator

A user-defined function is created using the def keyword, followed by the function name, parentheses (), and a colon :. Inside the function, you can write the logic that defines what the function does.

Arguments and Parameters

  • Positional Parameters: These are parameters passed in the correct positional order.
    python
    def add(a, b):
            return a + b
    print(add(2, 3)) # Output: 5
  • Default Parameters: These are parameters with default values.
    python
    def greet(name="Guest"):
            return f"Hello, {name}!"
    print(greet()) # Output: Hello, Guest!

Function Returning Value(s)

A function can return a result using the return statement. You can also return multiple values as a tuple.

Example:

python
def add_subtract(a, b):
           return a + b, a - b
            result = add_subtract(5, 3)
            print(result) # Output: (8, 2)

Flow of Execution

The flow of execution in a Python program starts at the top and moves downward. When a function is called, the control goes to the function, and once it completes, the control returns to the point where it was called.

Scope of a Variable

  • Local Scope: Variables defined inside a function. These variables are not accessible outside the function.
  • Global Scope: Variables defined outside all functions. These variables are accessible throughout the program.

Example:

python
x = 10 # Global variable
def test():
         y = 5 # Local variable
print(x, y)
test() # Output: 10 5

Exception Handling

Exception handling is used to manage errors and exceptions in Python so that the program doesn’t crash when encountering errors.

  • try-except-finally: Used to handle exceptions.
    • try: Block of code that may raise an exception.
    • except: Block of code to handle the exception.
    • finally: Code that will run no matter what (used for cleanup).

Example:

python
try:
     x = int(input("Enter a number: "))
except ValueError:
     print("That's not a valid number!")
finally:
          print("Execution finished")

Introduction to Files

See also  How to Earn Money on Instagram Easily

Files are used for persistent storage. Python allows us to work with three types of files:

  • Text File: Stores data in human-readable text form.
  • Binary File: Stores data in binary (0s and 1s).
  • CSV File: Comma Separated Values, used for storing tabular data.
Advertisements

Working with Text Files

  • File Open Modes:
    • 'r': Read mode
    • 'w': Write mode
    • 'a': Append mode
    • 'r+': Read and write mode
    • 'a+': Append and read mode
  • Opening a File:
    python
    file = open('example.txt', 'r')
  • Reading from a File:
    python
    content = file.read() # Reads the entire file
  • Writing/Appending to a File:
    python
    file.write("Hello World!") # Write to the file
  • Closing a File:
    python
    file.close()
  • Using ‘with’ to open files:
    python
    with open('example.txt', 'r') as file:
          content = file.read()

Binary Files

Binary files contain data in a format that is not human-readable. You can use the pickle module for working with binary files.

  • Opening Binary Files:
    python
    with open('data.dat', 'wb') as file:
    # Writing binary data
  • Using pickle Module:
    python
    import pickle
    with open('data.dat', 'wb') as file:
          pickle.dump(data, file) # Write binary data

CSV Files

CSV files store tabular data in plain text. The csv module is used to work with CSV files in Python.

  • Reading and Writing CSV Files:
    python
    import csv
    with open('data.csv', 'w', newline='') as file:
         writer = csv.writer(file)
         writer.writerow(['Name', 'Age'])
         writer.writerows([['Alice', 23], ['Bob', 25]])

Data Structures: Stack

A stack is a data structure that follows the Last In, First Out (LIFO) principle. You can implement a stack using a list in Python.

  • Operations on Stack:
    • Push: Add an element to the stack.
    • Pop: Remove the top element from the stack.

Example:

python
stack = []
stack.append(10) # Push
stack.pop() # Pop

Unit II: Computer Networks

Evolution of Networking

  • ARPANET: The first network that led to the development of the Internet.
  • NSFNET: A network created by the National Science Foundation, which contributed to the growth of the Internet.

Data Communication Terminologies

  • Sender: The device that sends the message.
  • Receiver: The device that receives the message.
  • Message: The data being sent.
  • Communication Media: The path through which data travels (wired or wireless).
  • Bandwidth: The capacity of a communication medium to carry data.
See also  Collection of 2 Line Sad and Heart Touching Shayari

Transmission Media

  • Wired:
    • Twisted Pair Cable: Commonly used for telephone lines.
    • Coaxial Cable: Used for cable television.
    • Fiber Optic Cable: High-speed transmission using light signals.
  • Wireless:
    • Radio Waves: Used for mobile communication.
    • Microwaves: Used for satellite communication.
    • Infrared Waves: Used for short-range communication.

Network Devices

  • Modem: Converts digital signals to analog for transmission over telephone lines.
  • Router: Directs data between networks.
  • Switch: Connects devices within a network.
  • Gateway: Connects different types of networks.

Network Protocols

  • HTTP: Protocol used for transmitting web pages.
  • FTP: Protocol for file transfers.
  • TCP/IP: Protocols used for communication over the Internet.

Unit III: Database Management

Database Concepts

  • Database: An organized collection of data.
  • Relational Database: A database that organizes data into tables.

Keys in a Database

  • Primary Key: A unique identifier for each record.
  • Foreign Key: A field in one table that links to a primary key in another table.

Structured Query Language (SQL)

SQL is used to manage and manipulate relational databases.

  • Basic SQL Commands:
    • CREATE DATABASE to create a database.
    • CREATE TABLE to create a table.
    • INSERT to add records.
    • SELECT to retrieve records.
    • UPDATE to modify records.
    • DELETE to remove records.

Example:

CREATE TABLE Students (
ID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
INSERT INTO Students (ID, Name, Age) VALUES (1, 'Alice', 20);
Advertisements

Python-SQL Connectivity

You can connect Python to a SQL database using modules like mysql.connector.

  • Steps:
    1. Establish a connection using connect().
    2. Create a cursor using cursor().
    3. Execute SQL queries using execute().
    4. Fetch results using fetchall() or fetchone().

Example:

python

import mysql.connector

conn = mysql.connector.connect(host='localhost', user='root', password='password', database='school')
cursor = conn.cursor()

cursor.execute("SELECT * FROM Students")

rows = cursor.fetchall()

for row in rows:
print(row)

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *