ComputerScience(083)-XI
3. Unit wise Syllabus
Unit 1: Computer Systems and Organisation
● Basic computer organisation: Introduction to Computer System, hardware, software, input device, output device, CPU, memory (primary, cache and secondary), units of memory (bit, byte, KB, MB, GB, TB, PB)
● Types of software: System software (Operating systems, system utilities, device drivers), programming tools and language translators (assembler, compiler, and interpreter), application software
● Operating System(OS): functions of the operating system, OS user interface
● Boolean logic: NOT, AND, OR, NAND, NOR, XOR, NOT, truth tables and De Morgan’s laws, Logic circuits
● Number System: Binary, Octal, Decimal and Hexadecimal number system; conversion between number systems
● Encoding Schemes: ASCII, ISCII, and Unicode (UTF8, UTF32)
-----------------------------------------------------------------------------------------------------
Detailed Notes on Basic Computer Organisation
1. Introduction to Computer System
A computer system is composed of two essential components:
- Hardware: The physical, tangible elements of the computer system.
- Software: The intangible instructions and programs that tell the hardware how to function.
The computer system takes input, processes it using its hardware and software, and provides output. The system also involves memory for temporary and permanent data storage.
Example:
- Input: You type a message on your keyboard (input device).
- Processing: The CPU processes the input using the operating system and other software.
- Output: The message is displayed on the monitor (output device).
2. Hardware Components
The hardware refers to all the physical components of a computer. Key categories of hardware include:
Major Categories of Hardware:
Input Devices: Hardware that allows users to enter data into the system.
- Keyboard: Types text, numbers, and commands.
- Mouse: Allows interaction with the computer's graphical interface (clicking, dragging).
- Scanner: Converts physical images and text into digital data for processing.
- Microphone: Captures sound (e.g., voice) to input into the system.
Output Devices: Hardware that displays or presents data from the computer.
- Monitor: Displays visual information (text, images, videos).
- Printer: Converts digital information into printed format (physical).
- Speakers: Output sound, such as music or speech.
Central Processing Unit (CPU): The “brain” of the computer, which performs operations based on the instructions received.
- Control Unit (CU): Manages the flow of instructions and data within the CPU and between other components of the computer.
- Arithmetic Logic Unit (ALU): Performs mathematical calculations (e.g., addition, subtraction) and logic operations (e.g., AND, OR).
- Registers: Small, high-speed memory areas within the CPU used to store data temporarily during processing.
Storage Devices: Permanent storage for data.
- Hard Disk Drive (HDD): A traditional, magnetic storage device used to store data permanently.
- Solid-State Drive (SSD): A faster, more reliable storage device with no moving parts compared to an HDD.
- USB Flash Drive: A portable, external storage device often used for transferring data between computers.
3. Software
Software is a set of programs and instructions that direct the hardware on what actions to take. Software can be categorized into two main types:
Categories of Software:
System Software: These are essential programs that help the computer run. The operating system (OS) is a prime example.
- Operating System (OS): Manages the computer's hardware and software resources, such as memory, CPU, and input/output devices.
- Example: Windows, macOS, Linux.
- Device Drivers: Small programs that allow the OS to communicate with hardware components like printers, graphics cards, and network adapters.
- Operating System (OS): Manages the computer's hardware and software resources, such as memory, CPU, and input/output devices.
Application Software: Programs designed to perform specific tasks for users.
- Example: Microsoft Word for word processing, Google Chrome for web browsing, Adobe Photoshop for image editing.
4. Input Devices
Input devices are hardware components that allow the user to interact with the computer and provide data for processing.
Examples of Input Devices:
- Keyboard: Used to input text and commands into the computer.
- Example: Typing a document or entering commands into a terminal.
- Mouse: Used to point, click, and interact with on-screen elements.
- Example: Clicking an icon to open an application.
- Scanner: Digitizes physical documents and images into digital format for use by the computer.
- Example: Scanning a photo to send it via email.
- Microphone: Captures audio input, converting sound to digital form.
- Example: Recording a voice memo or a podcast.
5. Output Devices
Output devices display or provide the results of computer processing. They convert the processed data into forms understandable by the user.
Examples of Output Devices:
- Monitor: Displays visual output, including text, images, and videos.
- Example: Watching a movie on the screen or reviewing a document.
- Printer: Produces hard copies of digital documents or images on paper.
- Example: Printing a document to submit in class or at work.
- Speakers: Provide audio output.
- Example: Listening to music or hearing a notification sound.
6. Central Processing Unit (CPU)
The CPU is the main unit of the computer that performs all processing and manages the execution of instructions.
Components of the CPU:
- Control Unit (CU): Directs the flow of data and instructions between the CPU and other components of the system.
- Arithmetic Logic Unit (ALU): Performs mathematical and logical operations.
- Example: Calculating
5 + 3using the ALU’s arithmetic capabilities.
- Example: Calculating
- Registers: Small storage locations within the CPU to hold data during processing.
Example:
When you open a software program, the CPU is responsible for processing the instructions required to launch the program, loading it into memory, and managing its execution.
7. Memory
Memory is used to store data temporarily or permanently, and can be categorized based on its speed and volatility.
Types of Memory:
- Primary Memory (RAM): Temporary, volatile storage used to store data that the CPU is actively processing.
- Example: Opening a web browser loads the browser into RAM for quick access by the CPU.
- Cache Memory: A small, high-speed memory located close to the CPU that stores frequently accessed data and instructions for faster processing.
- Example: Storing recently accessed web pages for faster loading when revisited.
- Secondary Memory: Permanent storage for data, such as hard drives, SSDs, and USB drives.
- Example: Saving a document on your hard drive for future use.
8. Units of Memory
Memory and storage are measured in units that represent different quantities of data. These units help us understand the size and capacity of storage devices and memory.
Units of Memory:
- Bit (b): The smallest unit of data, either 0 or 1 (binary).
- Example: A bit could represent a binary choice (on/off, true/false).
- Byte (B): 8 bits, typically representing one character of data.
- Example: A single letter, such as "A," is stored in 1 byte.
- Kilobyte (KB): 1,024 bytes.
- Example: A small text file might be around 10 KB.
- Megabyte (MB): 1,024 KB (1,048,576 bytes).
- Example: A high-resolution image might take up about 3 MB.
- Gigabyte (GB): 1,024 MB (1,073,741,824 bytes).
- Example: A full-length HD movie can be around 2-5 GB.
- Terabyte (TB): 1,024 GB (1,099,511,627,776 bytes).
- Example: A modern hard drive might have a storage capacity of 1 TB.
- Petabyte (PB): 1,024 TB (1,125,899,906,842,624 bytes).
- Example: Large data centers may store information in the PB range.
Summary Example:
When you browse the web:
- Input: You use the mouse and keyboard to type a website URL.
- CPU: The CPU processes the URL and retrieves the website's data from storage.
- Primary Memory: The website is loaded into RAM for quick access.
- Cache: Frequently used data from the website may be stored in cache memory for faster future access.
- Output: The monitor displays the website content, and the speakers output any audio from the site.
___________________________________________________________________
Unit 2: Computational Thinking and Programming - I
● Introduction to Problem-solving: Steps for Problem-solving (Analyzing the problem, developing an algorithm, coding, testing, and debugging), representation of algorithms using flowchart and pseudocode, decomposition
● Familiarization with the basics of Python programming: Introduction to Python, Features of Python, executing a simple “hello world" program, execution modes: interactive mode and script mode, Python character set, Python tokens( keyword, identifier, literal, operator, punctuator), variables, concept of l-value and r-value, use of comments
● Knowledge of data types: Number(integer, floating point,complex), boolean, sequence(string, list, tuple), None, Mapping(dictionary), mutable and immutable data types.
● Operators: arithmetic operators, relational operators, logical operators, assignment operators, augmented assignment operators, identity operators (is, is not), membership operators (in not in)
● Expressions, statement, type conversion, and input/output: precedence of operators, expression, evaluation of an expression, type-conversion (explicit and implicit conversion), accepting data as input from the console and displaying output.
● Errors- syntax errors, logical errors, and run-time errors
● Flow of Control: introduction, use of indentation, sequential flow, conditional and iterative flow
● Conditional statements: if, if-else, if-elif-else, flowcharts, simple programs: e.g.: absolute value, sort 3 numbers and divisibility of a number.
● Iterative Statement: for loop, range(), while loop, flowcharts, break and continue statements, nested loops, suggested programs: generating pattern, summation of series, finding the factorial of a positive number, etc.
● Strings: introduction, string operations (concatenation, repetition, membership and slicing), traversing a string using loops, built-in functions/methods–len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(),lstrip(), rstrip(), strip(), replace(), join(), partition(), split()
● Lists: introduction, indexing, list operations (concatenation, repetition, membership and slicing), traversing a list using loops, built-in functions/methods–len(), list(), append(), extend(), insert(), count(), index(), remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum(); nested lists, suggested programs: finding the maximum, minimum, mean of numeric values stored in a list; linear search on list of numbers and counting the frequency of elements in a list.
● Tuples: introduction, indexing, tuple operations (concatenation, repetition, membership and slicing); built-in functions/methods – len(), tuple(), count(), index(), sorted(), min(), max(), sum(); tuple assignment, nested tuple; suggested programs: finding the minimum, maximum, mean of values stored in a tuple; linear search on a tuple of numbers, counting the frequency of elements in a tuple.
● Dictionary: introduction, accessing items in a dictionary using keys, mutability of a dictionary (adding a new term, modifying an existing item), traversing a dictionary, built-in functions/methods – len(), dict(), keys(), values(), items(), get(), update(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), sorted(); Suggested programs: count the number of times a character appears in a given string using a dictionary, create a dictionary with names of employees, their salary and access them.
● Introduction to Python modules: Importing module using ‘import ’ and using from statement, importing math module (pi, e, sqrt(), ceil(), floor(), pow(), fabs(), sin(), cos(), tan()); random module (random(), randint(), randrange()), statistics module (mean(), median(), mode()).
------------------------------------------------------------------------------------------------------
Unit 2: Computational Thinking and Programming - I
This unit focuses on the fundamentals of problem-solving and introduces Python programming, including basic concepts, data types, control flow, and essential Python operations.
Computational Thinking and Programming – I
Introduction to Problem-Solving
Easy English · Detailed explanations · Original examples · Exam-oriented notes
Syllabus Covered
Introduction to Problem-Solving
Steps for Problem-Solving
Analyzing the Problem
Developing an Algorithm
Coding
Testing and Debugging
Representation of Algorithms using Flowcharts and Pseudocode
Decomposition
1. Introduction to Problem-Solving
1.1 What is a Problem?
A problem is a situation in which we need to find an answer, solution, or way to achieve a particular goal.
Examples
Finding the sum of two numbers.
Calculating the average marks of a student.
Checking whether a number is even or odd.
Finding the largest number among three numbers.
Preparing a school timetable.
1.2 What is Problem-Solving?
Problem-solving is a systematic process of understanding a problem, planning a solution, implementing it, and checking whether the solution works correctly.
In computer science, problem-solving means developing a logical and step-by-step solution that can be implemented using a computer.
Example: Finding the Sum of Two Numbers
Suppose we want to calculate the sum of 15 and 25.
PROBLEM
15 + 25 = ?
SOLUTION
40
To solve this problem using a computer, we need to provide clear instructions for adding the two numbers and displaying the result.
2. Steps for Problem-Solving
Problem-solving in programming generally involves five important steps.
1. Analyzing the Problem
Understand the problem and its requirements.
2. Developing an Algorithm
Prepare a step-by-step solution.
3. Coding
Convert the solution into program code.
4. Testing
Check whether the program works correctly.
5. Debugging
Find and correct errors in the program.
If an error is found during testing, the programmer corrects it and tests the program again.
3. Analyzing the Problem
3.1 Definition
Problem analysis is the process of understanding what a problem requires, what information is available, and what result is expected.
Before writing a program, we should identify three important components:
Input
The data given to the computer.
Example: Two numbers, 15 and 25.
Process
The operation performed on the input.
Example: Adding the two numbers.
Output
The result produced by the computer.
Example: The sum, 40.
3.2 Example: Calculate the Average of Three Marks
Suppose a student scores 70, 80 and 90 marks in three subjects.
Component | Description |
|---|---|
Input | 70, 80, 90 |
Process | Add the marks and divide the total by 3 |
Output | 80 |
Formula:
3.3 Importance of Problem Analysis
Helps us understand the actual problem.
Identifies the required inputs and expected outputs.
Prevents unnecessary coding.
Helps us plan the correct solution.
Makes the program easier to develop and test.
4. Developing an Algorithm
4.1 What is an Algorithm?
An algorithm is a finite sequence of clear, ordered steps used to solve a problem or perform a task.
In simple words, an algorithm is a step-by-step plan for solving a problem.
4.2 Real-Life Example: Making a Cup of Tea
Algorithm:
Start.
Take water in a pan.
Heat the water.
Add tea leaves and sugar.
Add milk.
Boil the mixture.
Strain the tea into a cup.
Stop.
This is an example of an algorithm because it contains ordered steps to complete a task.
4.3 Algorithm to Add Two Numbers
Problem: Write an algorithm to input two numbers and display their sum.
Algorithm:
Start.
Input two numbers A and B.
Calculate
SUM = A + B.Display SUM.
Stop.
4.4 Characteristics of a Good Algorithm
Characteristic | Explanation |
|---|---|
Input | An algorithm may accept zero or more inputs. |
Output | It should produce at least one result. |
Definiteness | Every step should be clear and unambiguous. |
Finiteness | It must finish after a finite number of steps. |
Effectiveness | Every step should be practical and executable. |
Important Points
An algorithm is a plan, not necessarily a computer program.
It can be written in simple English or another understandable language.
The same algorithm can be implemented in different programming languages.
5. Coding
5.1 Definition
Coding is the process of converting an algorithm or solution into instructions written in a programming language that a computer can execute.
A programmer writes code using programming languages such as Python, C++, Java or JavaScript.
5.2 Example: Python Program to Add Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
total = a + b
print("Sum =", total)Explanation of the Program
Code | Meaning |
|---|---|
| Takes input from the user. |
| Converts the input into an integer. |
| Adds the two numbers. |
| Stores the calculated sum. |
| Displays the result. |
Sample Output
Enter first number: 15
Enter second number: 25
Sum = 405.3 Important Terms
Programming Language: A language used to write instructions for a computer.
Program: A set of instructions written in a programming language to perform a task.
Programmer: A person who writes, tests and maintains computer programs.
6. Testing
6.1 Definition
Testing is the process of running a program with different inputs to check whether it produces the expected results.
Testing helps us identify errors and check whether a program satisfies its requirements.
6.2 Example: Testing a Sum Program
Suppose a program calculates the sum of two numbers.
We should test it with different input values.
Input A | Input B | Expected Output |
|---|---|---|
10 | 20 | 30 |
5 | 7 | 12 |
0 | 8 | 8 |
-4 | 6 | 2 |
If the program gives the expected output for these test cases, it passes those particular tests.
However, passing a few tests does not guarantee that the program is completely error-free.
6.3 Types of Test Cases
1. Normal Test Case
Uses ordinary and expected input values.
Example: Adding 10 and 20.
2. Boundary Test Case
Checks values at the limits of the allowed input range.
Example: If marks must be between 0 and 100, test the values 0 and 100.
3. Invalid Input Test Case
Checks how a program handles input that is not allowed.
Example: Entering a negative number when only positive numbers are permitted.
6.4 Importance of Testing
Helps identify errors.
Checks whether the program meets its requirements.
Verifies the correctness of output.
Improves the reliability of software.
7. Debugging
7.1 Definition
Debugging is the process of identifying, locating and correcting errors in a computer program.
An error in a program is commonly called a bug.
7.2 Example 1: Syntax Error
Incorrect code:
print("Hello"The closing parenthesis is missing.
Correct code:
print("Hello")7.3 Example 2: Logical Error
Suppose we want to calculate the average of three numbers.
Incorrect code:
average = (a + b + c) / 2The program may run, but the result will be incorrect because the total is divided by 2 instead of 3.
Correct code:
average = (a + b + c) / 37.4 Types of Errors
1. Syntax Error
An error caused by breaking the grammar or rules of a programming language.
Example: Missing a bracket or colon.
2. Runtime Error
An error that occurs while a program is running.
Example: Dividing a number by zero.
3. Logical Error
An error in the program's logic that causes it to produce an incorrect result.
Example: Dividing the sum of three numbers by 2 instead of 3.
7.5 Testing vs Debugging
Testing | Debugging |
|---|---|
Checks whether the program works correctly. | Finds and corrects errors. |
May reveal a bug. | Investigates the cause of a bug. |
Focuses on checking program behaviour. | Focuses on correcting faulty code or logic. |
Remember: Testing detects failures; debugging investigates and fixes their causes.
8. Representation of Algorithms
An algorithm can be represented in different ways. Two common methods are:
Flowchart
Pseudocode
These methods help programmers understand and plan a solution before writing the actual program.
9. Flowchart
9.1 Definition
A flowchart is a graphical representation of an algorithm using standard symbols connected by arrows to show the sequence of steps.
It helps us understand the logic of a program visually.
9.2 Common Flowchart Symbols
Oval / Ellipse
Indicates the beginning or end of an algorithm.
Rectangle
Represents a calculation or processing step.
Parallelogram
Represents taking input or displaying output.
Diamond
Represents a condition with possible branches such as Yes/No.
Arrow / Flow Line
Shows the direction and sequence of execution.
9.3 Example: Flowchart to Add Two Numbers
Flowchart for adding two numbers
Explanation
Start the process.
Take two numbers as input.
Add the numbers and store the result in SUM.
Display the value of SUM.
Stop the process.
10. Pseudocode
10.1 Definition
Pseudocode is an informal, structured way of describing the steps of an algorithm using simple English-like statements and programming-style instructions.
Pseudocode is not a programming language. It does not follow the exact syntax rules of Python, C++ or Java.
10.2 Example: Pseudocode to Add Two Numbers
BEGIN
INPUT A, B
SUM ← A + B
PRINT SUM
ENDExplanation
Statement | Meaning |
|---|---|
| Starts the algorithm. |
| Takes two numbers as input. |
| Calculates and stores the sum. |
| Displays the result. |
| Finishes the algorithm. |
Note: The symbol ← means assignment, that is, storing a value in a variable.
10.3 Pseudocode to Calculate Average
BEGIN
INPUT A, B, C
TOTAL ← A + B + C
AVERAGE ← TOTAL / 3
PRINT AVERAGE
ENDIf the inputs are 70, 80 and 90, the output will be 80.
10.4 Pseudocode to Check Even or Odd
BEGIN
INPUT N
IF N MOD 2 = 0 THEN
PRINT "Even"
ELSE
PRINT "Odd"
END IF
ENDExplanation: MOD gives the remainder after division. If a number divided by 2 leaves remainder 0, it is even; otherwise, it is odd.
11. Flowchart vs Pseudocode
Flowchart | Pseudocode |
|---|---|
Graphical representation of an algorithm. | Text-based representation of an algorithm. |
Uses standard shapes and arrows. | Uses structured statements. |
Shows the flow visually. | Explains the steps in written form. |
Can become complex for large problems. | Usually easier to edit for large problems. |
Helps visualize the sequence and decisions. | Helps plan program logic before coding. |
12. Decomposition
12.1 Definition
Decomposition is the process of breaking a large or complex problem into smaller, manageable subproblems that are easier to understand, solve and test.
In simple words, instead of solving one big problem at once, we divide it into smaller tasks.
12.2 Real-Life Example: Organising a School Annual Function
Suppose a school wants to organise an annual function.
Instead of handling the entire event as one big task, we can divide it into smaller tasks.
Main Problem
Organise School Annual Function
1. Planning
Prepare the schedule.
2. Arrangements
Arrange the venue and equipment.
3. Performances
Prepare activities and performances.
4. Management
Manage participants and guests.
Completed Annual Function
Each smaller task can be divided further if needed.
12.3 Decomposition in Computer Programming
Suppose we need to create a student result program that calculates total marks, percentage and result status.
We can divide the problem into the following subproblems:
Input student details and marks.
Calculate total marks.
Calculate percentage.
Check whether the student has passed or failed.
Display the result.
Each part can be designed and tested separately.
Example: Student Result Program
MAIN PROBLEM
Create a Student Result Program
Subproblem 1: Input marks
Enter the student's marks.
Subproblem 2: Calculate total
Add the marks of all subjects.
Subproblem 3: Calculate percentage
Calculate the percentage obtained.
Subproblem 4: Determine result
Check the pass/fail condition.
Subproblem 5: Display result
Show the final result.
12.4 Advantages of Decomposition
Makes complex problems easier to understand.
Reduces the difficulty of problem-solving.
Allows programmers to work on separate parts.
Makes testing and debugging easier.
Makes programs easier to maintain and improve.
13. Complete Worked Example
Problem: Find the Greater of Two Different Numbers
Write an algorithm to input two different numbers and display the greater number.
Step 1: Analyze the Problem
Component | Details |
|---|---|
Input | Two numbers A and B |
Process | Compare A and B |
Output | The greater number |
Assumption: A and B are different numbers.
Step 2: Algorithm
Start.
Input A and B.
If A is greater than B, display A.
Otherwise, display B.
Stop.
Step 3: Pseudocode
BEGIN
INPUT A, B
IF A > B THEN
PRINT A
ELSE
PRINT B
END IF
ENDStep 4: Python Code
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
print("Greater number =", a)
else:
print("Greater number =", b)Step 5: Testing
A | B | Expected Output |
|---|---|---|
10 | 20 | 20 |
50 | 30 | 50 |
-5 | -2 | -2 |
Step 6: Debugging
If the program displays the smaller number, check the comparison condition and correct the logic.
14. Important Exam Questions
Very Short Answer Questions
What is problem-solving?
Define problem analysis.
What is an algorithm?
What is coding?
Define testing.
What is debugging?
What is a flowchart?
What is pseudocode?
What is decomposition?
What is a bug?
Short Answer Questions
Write the five steps of problem-solving in programming.
Explain input, process and output with an example.
Write any four characteristics of a good algorithm.
Differentiate between testing and debugging.
Explain the common symbols used in a flowchart.
Write pseudocode to calculate the average of three numbers.
Explain the three common types of programming errors.
What is decomposition? Give an example.
Differentiate between flowchart and pseudocode.
Long Answer Questions
Explain the steps involved in problem-solving with suitable examples.
Define an algorithm and explain its characteristics.
Explain flowcharts and their common symbols with examples.
Explain pseudocode and write pseudocode to find the greater of two numbers.
Explain decomposition and discuss its advantages in programming.
Explain testing and debugging, including syntax, runtime and logical errors.
15. Quick Revision Table
Term | Easy Meaning |
|---|---|
Problem-Solving | Solving a problem systematically |
Problem Analysis | Understanding the problem, inputs and outputs |
Algorithm | A step-by-step solution |
Coding | Writing instructions in a programming language |
Testing | Checking whether a program works correctly |
Debugging | Finding and correcting program errors |
Flowchart | Graphical representation of an algorithm |
Pseudocode | Text-based representation of an algorithm |
Decomposition | Dividing a complex problem into smaller parts |
Memory Trick
A → A → C → T → D
A – Analyze the problem.
A – Develop an algorithm.
C – Write the code.
T – Test the program.
D – Debug the errors.
------------------------------------------------------------------------------------------------------
CBSE Class 11 – Computer Science (083)
Unit 2: Computational Thinking and Programming – I
Topic: Familiarization with the Basics of Python Programming
Easy, student-friendly notes in English
1. Introduction to Python
Python is a high-level, general-purpose programming language used to develop software, websites, games, automation scripts, and many other applications.
It was created by Guido van Rossum and first released in 1991.
Python is popular because its syntax is simple and easy to understand. It allows programmers to write programs using fewer lines of code compared to many other programming languages.
Example
print("Hello, World!")Output:
Hello, World!The print() function displays information on the screen.
2. Features of Python
Python has several important features.
Feature | Description |
|---|---|
Simple and easy to learn | Python has a clear and readable syntax. |
High-level language | Programmers do not need to manage low-level computer operations directly. |
Interpreted language | Python programs are executed by the Python interpreter. |
General-purpose | Python can be used for many types of applications. |
Portable | Python programs can run on different operating systems with suitable Python support. |
Open-source | Python is freely available to use, modify, and distribute under its licence. |
Dynamically typed | The type of a variable is determined at runtime. |
Large standard library | Python provides many built-in modules for common tasks. |
Object-oriented | Python supports classes and objects. |
Case-sensitive | Uppercase and lowercase letters are treated differently. |
Example of case sensitivity
name = "Raj"
Name = "Amit"
print(name)
print(Name)Output:
Raj
AmitHere, name and Name are two different identifiers.
3. Executing a Simple “Hello, World!” Program
A Python program is a set of instructions written in Python language.
Program
print("Hello, World!")Output
Hello, World!Explanation
print()is a built-in Python function.Text written inside quotation marks is called a string literal.
The function displays the string on the screen.
The program does not require a semicolon at the end.
Another example
print("Welcome to Python")
print("Computer Science - Class 11")Output:
Welcome to Python
Computer Science - Class 11Each print() statement displays its output on a separate line.
4. Execution Modes in Python
Python programs can be executed in two main modes:
Interactive Mode
Script Mode
4.1 Interactive Mode
In interactive mode, Python executes one statement at a time as the user enters it.
It is useful for testing small instructions and performing quick calculations.
Example
>>> 5 + 3
8
>>> print("Hello")
HelloThe symbol >>> is the Python prompt. It indicates that Python is ready to accept a command.
Advantages
Immediate output.
Useful for learning and testing small statements.
No need to save a program file.
Limitation
A series of statements is not automatically saved as a program file.
4.2 Script Mode
In script mode, Python statements are written in a file and saved with the .py extension.
The file is then executed as a complete program.
Example
Create a file named hello.py.
print("Hello, World!")
print("Welcome to Python")Output:
Hello, World!
Welcome to PythonAdvantages
Programs can be saved and reused.
Suitable for writing long programs.
Programs can be edited and executed again.
Difference between Interactive Mode and Script Mode
Interactive Mode | Script Mode |
|---|---|
Executes statements one at a time. | Executes statements from a saved file. |
Output is usually displayed immediately. | Output appears when the script is run. |
Useful for quick testing. | Useful for complete programs. |
Usually does not save the entered commands automatically. | Program is saved in a |
5. Python Character Set
A character set is a collection of valid characters that can be used in a programming language.
Python supports Unicode, which allows it to work with characters from many languages and writing systems.
The Python character set includes:
Character Type | Examples |
|---|---|
Alphabets |
|
Digits |
|
White spaces | Space, tab, newline |
Special symbols |
|
Unicode characters | Characters from many world languages |
Examples
name = "Rajesh"
age = 16
print(name, age)Output:
Rajesh 16Python uses characters to form keywords, identifiers, literals, operators, and other program elements.
6. Python Tokens
A token is the smallest meaningful unit of a Python program.
The main types of Python tokens are:
Keywords
Identifiers
Literals
Operators
Punctuators
Consider this statement:
total = price + 10Its tokens include:
total– identifier=– operatorprice– identifier+– operator10– literal
6.1 Keywords
Keywords are reserved words in Python that have special meanings. They cannot be used as ordinary variable names.
Examples
if, else, elif, for, while, break, continue, def, return, class, True, False, None, and, or, not, import
Example
if age >= 18:
print("Eligible")Here, if is a keyword.
Invalid use of a keyword
if = 10This causes a syntax error because if is a reserved keyword.
6.2 Identifiers
An identifier is the name given to a variable, function, class, or other program element.
Examples
name = "Aman"
age = 17
total_marks = 450Here, name, age, and total_marks are identifiers.
Rules for naming identifiers
An identifier can contain letters, digits, and underscores.
It must not begin with a digit.
It cannot contain spaces.
It cannot be a Python keyword.
Identifiers are case-sensitive.
Special symbols such as
@,$, and%are not allowed in ordinary identifiers.
Valid and invalid identifiers
Identifier | Valid / Invalid | Reason |
|---|---|---|
| Valid | Contains letters. |
| Valid | Does not begin with a digit. |
| Valid | Underscore is allowed. |
| Valid | Can begin with an underscore. |
| Invalid | Begins with a digit. |
| Invalid | Contains a space. |
| Invalid | It is a keyword. |
| Invalid | Hyphen is not allowed in an identifier. |
6.3 Literals
A literal is a fixed value written directly in a program.
Types of literals
Type | Examples |
|---|---|
Integer |
|
Floating-point |
|
String |
|
Boolean |
|
Special value |
|
Example
age = 16
height = 5.6
name = "Ravi"
is_student = TrueHere:
16is an integer literal.5.6is a floating-point literal."Ravi"is a string literal.Trueis a Boolean literal.
String literals
Strings are sequences of characters enclosed in quotes.
city = "Lucknow"
message = 'Welcome'Both single and double quotation marks can be used for strings.
6.4 Operators
An operator is a symbol or word used to perform an operation on values or variables.
Common types of operators
Operator Type | Operators | Purpose |
|---|---|---|
Arithmetic |
| Mathematical operations |
Relational / Comparison |
| Compare values |
Logical |
| Combine or reverse conditions |
Assignment |
| Assign or update values |
Membership |
| Check membership |
Identity |
| Check object identity |
Example: Arithmetic operators
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)Output:
13
7
30
3.3333333333333335Example: Comparison operator
print(10 > 5)Output:
True6.5 Punctuators
Punctuators are symbols used to organise Python code and define its structure.
Common punctuators
Punctuator | Use |
|---|---|
| Function calls and grouping expressions |
| Lists and indexing |
| Dictionaries and sets |
| Starts an indented block |
| Separates items |
| Accesses attributes or methods |
| Can separate simple statements on the same line |
| Begins a comment |
Example
marks = [80, 90, 75]
print(marks)Here:
[and]enclose a list.,separates list elements.()are used in the function call.
Example of colon
if marks >= 33:
print("Pass")The colon : introduces the indented block following the if statement.
7. Variables in Python
A variable is a name that refers to a value stored in memory.
In Python, a variable is created when a value is assigned to it.
Example
age = 16
name = "Aman"
marks = 85.5Here:
agerefers to the integer16.namerefers to the string"Aman".marksrefers to the floating-point value85.5.
Displaying variable values
name = "Aman"
age = 16
print(name)
print(age)Output:
Aman
16Updating a variable
x = 10
x = 20
print(x)Output:
20The second assignment makes x refer to the value 20.
Dynamic typing
Python is dynamically typed. A variable can refer to values of different types at different times.
x = 10
print(x)
x = "Python"
print(x)Output:
10
Python8. Concept of L-value and R-value
In an assignment statement, the terms L-value and R-value help explain the roles of the left and right sides.
Example
x = 10xis the L-value: the variable name on the left side that receives the assignment.10is the R-value: the value or expression on the right side that is assigned.
Example with an expression
a = 5
b = 3
c = a + bIn the statement:
c = a + bcis the L-value.a + bis the R-value expression.The expression evaluates to
8, which is assigned toc.
Another example
x = 10
y = xIn y = x:
yis the L-value.xis the R-value expression, whose current value is10.
Important point
In ordinary Python assignment, the left side must be an assignable target, such as a variable name or an item in a mutable container. A literal or arithmetic expression cannot be used as the assignment target.
Valid:
x = 5Invalid:
5 = xThe second statement causes a syntax error.
9. Use of Comments in Python
A comment is text written in a program to explain the code. Comments are ignored by Python during normal program execution.
Comments help programmers understand, maintain, and debug programs.
9.1 Single-line comments
A single-line comment begins with the # symbol.
Example
# This program displays a message
print("Hello, World!")Output:
Hello, World!The comment is not displayed as output.
9.2 Inline comments
An inline comment appears on the same line as a statement, after the code.
age = 16 # Store the student's age
print(age)Output:
169.3 Multi-line explanations
Python does not have a special multi-line comment symbol. A common approach is to use # at the beginning of each line.
# This program calculates
# the sum of two numbers
a = 10
b = 20
print(a + b)Output:
30Triple-quoted strings ('''...''' or """...""") are sometimes used for multi-line explanations, but they are string literals, not true comment syntax. When placed as the first statement in a module, function, or class, they can serve as a docstring.
Example of a docstring
def greet():
"""Display a greeting message."""
print("Hello!")10. Complete Example Program
The following program demonstrates variables, literals, operators, comments, and output.
# Program to calculate total marks
name = "Ravi"
english = 80
computer = 95
total = english + computer
print("Student Name:", name)
print("Total Marks:", total)Output:
Student Name: Ravi
Total Marks: 175Concepts used
Concept | Example |
|---|---|
Comment |
|
Variable |
|
String literal |
|
Integer literal |
|
Operator |
|
Function |
|
11. Quick Revision
Python is a high-level, general-purpose programming language.
Python is case-sensitive.
Python programs can be executed in interactive mode or script mode.
A token is the smallest meaningful unit of a program.
Keywords are reserved words.
Identifiers are names used for variables and other program elements.
Literals are fixed values written directly in a program.
Operators perform operations on values.
Punctuators help organise code.
Variables are names that refer to values.
In an assignment, the L-value is the assignment target and the R-value is the value or expression being assigned.
Comments begin with
#and are ignored during normal execution.
12. Important Exam Questions
What is Python? Write any five features of Python.
Write a Python program to display
Hello, World!.Differentiate between interactive mode and script mode.
What is a character set?
Define Python tokens and list their types.
What are keywords? Give five examples.
Define identifiers and write the rules for naming them.
What is a literal? Give examples of different types of literals.
What are operators? Name any four types of operators.
What are punctuators? Give four examples.
What is a variable? Explain dynamic typing with an example.
Explain L-value and R-value with an assignment statement.
What is a comment? Explain single-line and inline comments.
Identify the tokens in the following statement:
total = marks + 10
____________________________________________________________________
1. Introduction to Data Types
A data type specifies the kind of value that a variable can refer to and the operations that can be performed on that value.
Python provides several built-in data types, such as:
Number:
int,float,complexBoolean:
boolSequence:
str,list,tupleNone type:
NoneTypeMapping:
dict
Example
age = 16
price = 99.5
name = "Ravi"Here:
agerefers to an integer.pricerefers to a floating-point number.namerefers to a string.
The type() function is used to identify the data type of a value or variable.
print(type(age))
print(type(price))
print(type(name))Output:
<class 'int'>
<class 'float'>
<class 'str'>2. Number Data Types
Python has three main numeric data types:
Integer (
int)Floating-point (
float)Complex (
complex)
2.1 Integer (int)
An integer is a whole number without a decimal point. It can be positive, negative, or zero.
Examples
a = 10
b = -25
c = 0
print(a)
print(b)
print(c)Output:
10
-25
0Important points
Integers do not contain a decimal point.
Python integers can represent very large whole numbers, limited by available memory.
Arithmetic operations such as addition, subtraction, and multiplication can be performed on integers.
Example
a = 15
b = 5
print(a + b)
print(a * b)Output:
20
752.2 Floating-point (float)
A floating-point number represents a number that contains a fractional part or is written using scientific notation.
Examples
x = 3.14
y = -2.5
z = 10.0
print(x)
print(y)
print(z)Output:
3.14
-2.5
10.0Scientific notation
Python supports scientific notation using e or E.
a = 2.5e3
b = 4.2e-2
print(a)
print(b)Output:
2500.0
0.042Important points
A floating-point number usually contains a decimal point or exponent.
10is an integer, while10.0is a floating-point number.Floating-point values are stored approximately, so some decimal calculations may have small precision differences.
Example
print(0.1 + 0.2)Output:
0.30000000000000004This happens because many decimal fractions cannot be represented exactly in binary floating-point format.
2.3 Complex (complex)
A complex number contains a real part and an imaginary part.
A complex number is written in Python using the form:
a + bjHere:
ais the real part.bis the imaginary part.jrepresents the imaginary unit.
Examples
x = 3 + 4j
y = 2 - 5j
print(x)
print(y)Output:
(3+4j)
(2-5j)Accessing real and imaginary parts
z = 3 + 4j
print(z.real)
print(z.imag)Output:
3.0
4.0Important points
Python uses
jorJfor the imaginary part.The real and imaginary parts are accessed using
.realand.imag.Complex numbers are useful in scientific and mathematical calculations.
3. Boolean Data Type (bool)
The Boolean data type represents one of two values:
TrueFalse
Boolean values are commonly used in conditions and decision-making statements.
Example
is_student = True
is_absent = False
print(is_student)
print(is_absent)Output:
True
FalseBoolean expressions
Comparison operations produce Boolean results.
print(10 > 5)
print(10 == 5)
print(7 != 3)Output:
True
False
TrueImportant points
TrueandFalseare Python keywords.Their first letters must be capitalised.
TrueandFalseare different from the strings"True"and"False".
print(type(True))
print(type("True"))Output:
<class 'bool'>
<class 'str'>4. Sequence Data Types
A sequence is an ordered collection of items. Each item has a position, called an index.
Python's commonly used sequence types include:
String (
str)List (
list)Tuple (
tuple)
Sequence indexing starts from 0.
4.1 String (str)
A string is an ordered sequence of characters enclosed in single, double, or triple quotation marks.
Examples
name = "Rajesh"
city = 'Lucknow'
message = """Welcome to Python"""Accessing characters
word = "PYTHON"
print(word[0])
print(word[1])
print(word[-1])Output:
P
Y
NPositive indexing starts from the left at 0. Negative indexing starts from the right at -1.
String slicing
Slicing is used to access a part of a sequence.
word = "PYTHON"
print(word[0:3])
print(word[2:5])Output:
PYT
THOThe ending index is excluded from the result.
Important points
Strings are ordered.
Strings can contain letters, digits, spaces, and special characters.
Strings are immutable, which means their characters cannot be changed directly after the string is created.
Example of immutability
word = "PYTHON"
word[0] = "J"This causes a TypeError because individual characters of a string cannot be reassigned.
4.2 List (list)
A list is an ordered collection of items enclosed in square brackets [].
A list can contain values of the same or different data types.
Examples
marks = [80, 90, 75, 85]
names = ["Aman", "Ravi", "Neha"]
mixed = [10, "Python", 3.5, True]Accessing list elements
marks = [80, 90, 75, 85]
print(marks[0])
print(marks[2])
print(marks[-1])Output:
80
75
85Updating a list
Lists are mutable, which means their elements can be changed after creation.
marks = [80, 90, 75]
marks[1] = 95
print(marks)Output:
[80, 95, 75]Adding an element
numbers = [10, 20, 30]
numbers.append(40)
print(numbers)Output:
[10, 20, 30, 40]Important points
Lists preserve order.
Lists allow duplicate values.
Lists can contain different data types.
Lists are mutable.
4.3 Tuple (tuple)
A tuple is an ordered collection of items enclosed in parentheses ().
Example
days = ("Monday", "Tuesday", "Wednesday")
numbers = (10, 20, 30)Accessing tuple elements
days = ("Monday", "Tuesday", "Wednesday")
print(days[0])
print(days[2])Output:
Monday
WednesdaySingle-element tuple
A single-element tuple must include a comma.
x = (10,)
print(type(x))Output:
<class 'tuple'>Without the comma, (10) is simply an integer expression inside parentheses.
Important points
Tuples preserve order.
Tuples allow duplicate values.
Tuples can contain different data types.
Tuples are immutable.
Example of immutability
numbers = (10, 20, 30)
numbers[0] = 100This causes a TypeError because tuple elements cannot be reassigned.
5. None Data Type (NoneType)
None is a special value in Python that represents the absence of a value.
Its data type is NoneType.
Example
result = None
print(result)
print(type(result))Output:
None
<class 'NoneType'>Common uses of None
To indicate that a variable has no value assigned yet.
To represent the absence of a result.
As the default return value of a function that does not explicitly return another value.
Example
def greet():
print("Hello")
result = greet()
print(result)Output:
Hello
NoneThe function displays Hello but does not explicitly return a value, so its return value is None.
Important point
None is not the same as 0, False, or an empty string "".
6. Mapping Data Type – Dictionary (dict)
A dictionary is a collection of key-value pairs.
It is written using curly braces {}. Each key is associated with a value.
Syntax
dictionary_name = {
key1: value1,
key2: value2
}Example
student = {
"name": "Ravi",
"age": 16,
"marks": 88
}
print(student)Output:
{'name': 'Ravi', 'age': 16, 'marks': 88}Accessing dictionary values
Values are accessed using their keys.
student = {
"name": "Ravi",
"age": 16,
"marks": 88
}
print(student["name"])
print(student["marks"])Output:
Ravi
88Updating a dictionary
Dictionaries are mutable, so their values can be changed.
student = {"name": "Ravi", "marks": 88}
student["marks"] = 95
print(student)Output:
{'name': 'Ravi', 'marks': 95}Adding a new key-value pair
student = {"name": "Ravi"}
student["age"] = 16
print(student)Output:
{'name': 'Ravi', 'age': 16}Important points
A dictionary stores data as key-value pairs.
Keys must be unique.
Keys must be hashable, such as strings, numbers, or tuples containing only hashable items.
Values can be of different data types.
Dictionaries are mutable.
Dictionaries preserve insertion order in modern Python.
7. Mutable and Immutable Data Types
Python data types can be classified as mutable or immutable.
7.1 Mutable Data Types
A mutable object can be changed after it has been created.
Examples:
listdictset
Example
numbers = [10, 20, 30]
numbers[0] = 100
print(numbers)Output:
[100, 20, 30]The original list is modified.
7.2 Immutable Data Types
An immutable object cannot be changed after it has been created.
Examples:
intfloatcomplexboolstrtupleNoneType
Example
x = 10
x = x + 5
print(x)Output:
15This does not change the integer object 10. Instead, the expression creates or refers to the value 15, and the variable x is reassigned to it.
String example
name = "Ravi"
name = name + " Kumar"
print(name)Output:
Ravi KumarA new string is created and assigned to name; the original string is not modified.
8. Difference Between Mutable and Immutable Data Types
Mutable | Immutable |
|---|---|
Can be changed after creation. | Cannot be changed after creation. |
Existing object can be modified. | Changes require creating or referring to another object. |
Examples: | Examples: |
Example: | Example: assigning to |
9. Summary Table of Python Data Types
Data Type | Python Type | Example | Mutable / Immutable |
|---|---|---|---|
Integer |
|
| Immutable |
Floating-point |
|
| Immutable |
Complex |
|
| Immutable |
Boolean |
|
| Immutable |
String |
|
| Immutable |
List |
|
| Mutable |
Tuple |
|
| Immutable |
None |
|
| Immutable |
Dictionary |
|
| Mutable |
10. Complete Example Program
# Demonstration of Python data types
age = 16
height = 5.7
number = 2 + 3j
is_student = True
name = "Ravi"
marks = [80, 90, 85]
subjects = ("English", "Maths", "Computer")
student = {"name": "Ravi", "age": 16}
result = None
print(type(age))
print(type(height))
print(type(number))
print(type(is_student))
print(type(name))
print(type(marks))
print(type(subjects))
print(type(student))
print(type(result))Output:
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'NoneType'>11. Quick Revision
A data type defines the kind of value represented by an object.
int,float, andcomplexare numeric data types.boolstoresTrueorFalse.str,list, andtupleare commonly used sequence types.Nonerepresents the absence of a value.dictstores key-value pairs.Lists and dictionaries are mutable.
Integers, floats, complex numbers, Booleans, strings, tuples, and
Noneare immutable.The
type()function identifies the type of an object.Sequence indexing starts from
0.
12. Important Exam Questions
What is a data type? Name the main built-in data types in Python.
Explain integer, floating-point, and complex data types with examples.
What is a Boolean data type? Give an example.
Define a sequence. Explain string, list, and tuple.
Differentiate between a list and a tuple.
What is
Nonein Python? Give an example.____________________________________________________________________
1. Operators in Python
An operator is a symbol or keyword used to perform an operation on values or variables.
The values on which an operator works are called operands.
Example:
a = 10 b = 5 print(a + b)Here,
+is the operator, whileaandbare operands.1.1 Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
Operator
Name
Example
Result
+Addition
10 + 313-Subtraction
10 - 37*Multiplication
10 * 330/Division
10 / 33.333...//Floor division
10 // 33%Modulus
10 % 31**Exponentiation
2 ** 38Important points
/performs division and returns a floating-point result.//performs floor division, rounding the quotient down to the nearest integer value.%returns the remainder.**calculates a power.
Example
a = 17 b = 5 print(a / b) print(a // b) print(a % b) print(a ** 2)Output:
3.4 3 2 2891.2 Relational (Comparison) Operators
Relational operators compare two values. The result is always a Boolean value:
TrueorFalse.Operator
Meaning
Example
Result
==Equal to
5 == 5True!=Not equal to
5 != 3True>Greater than
8 > 4True<Less than
2 < 7True>=Greater than or equal to
5 >= 5True<=Less than or equal to
3 <= 2FalseExample
a = 10 b = 20 print(a < b) print(a == b) print(a != b)Output:
True False TrueRemember:
=is an assignment operator, whereas==is a comparison operator.1.3 Logical Operators
Logical operators are used to combine or reverse conditions.
Operator
Meaning
andTrue only when both conditions are True
orTrue when at least one condition is True
notReverses the Boolean result
Truth table
A
B
A and BA or BTrue
True
True
True
True
False
False
True
False
True
False
True
False
False
False
False
A
not ATrue
False
False
True
Example
age = 20 print(age >= 18 and age <= 60) print(age < 18 or age > 60) print(not age >= 18)Output:
True False False1.4 Assignment Operators
The assignment operator
=assigns a value to a variable.x = 10Here, the value
10is assigned tox.Other assignment operators can also be used to assign values.
Operator
Example
Equivalent statement
=x = 10Assign 10 to
x+=x += 5x = x + 5-=x -= 5x = x - 5*=x *= 5x = x * 5/=x /= 5x = x / 5//=x //= 5x = x // 5%=x %= 5x = x % 5**=x **= 2x = x ** 2Example
x = 10 x += 5 print(x)Output:
151.5 Augmented Assignment Operators
An augmented assignment operator performs an operation and assigns the result back to the same variable.
For example:
x = 10 x += 3This is equivalent to:
x = 10 x = x + 3Output:
13Other examples include
-=,*=,/=,//=,%=, and**=.1.6 Identity Operators (
is,is not)Identity operators check whether two references point to the same object in memory.
Operator
Meaning
isTrue if both references point to the same object
is notTrue if they point to different objects
Example
a = None print(a is None) print(a is not None)Output:
True FalseImportant difference:
==andis==checks whether two values are equal.ischecks whether two references identify the same object.
a = [1, 2, 3] b = [1, 2, 3] print(a == b) print(a is b)Output:
True FalseThe lists contain equal values, but they are separate list objects.
1.7 Membership Operators (
in,not in)Membership operators check whether a value is present in a sequence or collection.
Operator
Meaning
inTrue if the value is present
not inTrue if the value is absent
Example
name = "Python" print("P" in name) print("z" in name) print("z" not in name)Output:
True False TrueExample with a list
numbers = [10, 20, 30] print(20 in numbers) print(50 not in numbers)Output:
True True2. Expressions, Statements, Type Conversion and Input/Output
2.1 Expression
An expression is a combination of values, variables, operators, and function calls that produces a result when evaluated.
Examples
5 + 3 a * b (10 + 5) / 3Example program
a = 10 b = 5 result = a + b * 2 print(result)Output:
20The expression
a + b * 2evaluates to20because multiplication is performed before addition.2.2 Statement
A statement is an instruction that Python executes.
Examples:
x = 10 print(x)x = 10is an assignment statement.print(x)is a function-call statement.
Difference between expression and statement
Expression
Statement
Produces a value when evaluated.
Performs an instruction or action.
Example:
5 + 3Example:
x = 5 + 3Can be part of a statement.
May contain one or more expressions.
2.3 Precedence of Operators
Operator precedence determines the order in which operators are evaluated in an expression.
Common precedence order
From higher precedence to lower precedence:
Priority
Operators
1
Parentheses:
()2
Exponentiation:
**3
Unary operators:
+x,-x,~x4
Multiplication, division, floor division, modulus:
*,/,//,%5
Addition and subtraction:
+,-6
Comparisons:
<,<=,>,>=,==,!=,in,is7
Logical
not8
Logical
and9
Logical
orNote: Operators at the same precedence level generally follow associativity rules. Exponentiation is evaluated from right to left.
Example 1
print(5 + 3 * 2)Output:
11Multiplication is performed first:
3 * 2 = 6, then5 + 6 = 11.Example 2
print((5 + 3) * 2)Output:
16Parentheses are evaluated first.
Example 3
print(2 ** 3 ** 2)Output:
512Exponentiation is evaluated from right to left:
2 ** (3 ** 2)2.4 Evaluation of an Expression
Evaluation means calculating the value of an expression by applying the operators according to their precedence and associativity.
Example
a = 8 b = 4 c = 2 result = a + b * c print(result)Evaluation:
b * c→4 * 2→8a + 8→8 + 8→16
Output:
163. Type Conversion
Type conversion means converting a value from one data type to another.
There are two main types:
Implicit type conversion
Explicit type conversion
3.1 Implicit Type Conversion
Implicit conversion is performed automatically by Python.
Example
a = 10 b = 2.5 result = a + b print(result) print(type(result))Output:
12.5 <class 'float'>Python converts the integer
10to a floating-point value during the calculation.3.2 Explicit Type Conversion
Explicit conversion is performed by the programmer using conversion functions.
Function
Converts to
Example
int()Integer
int("25")→25float()Float
float("3.5")→3.5str()String
str(100)→"100"bool()Boolean
bool(1)→Truelist()List
list("ABC")→['A', 'B', 'C']tuple()Tuple
tuple([1, 2])→(1, 2)Example
x = "25" y = int(x) print(y + 5)Output:
30Without
int(x),"25"is a string, and adding the integer5to it would cause aTypeError.Important points
int(3.9)produces3, not4.float(5)produces5.0.str(25)produces"25".int("hello")causes aValueErrorbecause"hello"cannot be converted to an integer.
4. Input and Output in Python
4.1 Accepting Input Using
input()The
input()function accepts data from the keyboard through the console.Syntax
variable = input("Message")Important:
input()returns the entered data as a string.Example
name = input("Enter your name: ") print("Welcome", name)If the user enters
Aman, the output is:Enter your name: Aman Welcome Aman4.2 Accepting Numeric Input
Convert the input string to the required numeric type.
Integer input
age = int(input("Enter your age: ")) print(age)Floating-point input
price = float(input("Enter price: ")) print(price)Example: Adding two numbers
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) total = a + b print("Sum =", total)If the user enters
10and20:Enter first number: 10 Enter second number: 20 Sum = 304.3 Displaying Output Using
print()The
print()function displays data on the screen.Example
print("Hello, Python!") print(10 + 5)Output:
Hello, Python! 15Using commas in
print()name = "Ravi" age = 16 print("Name:", name, "Age:", age)Output:
Name: Ravi Age: 16Using f-strings
An f-string allows variables and expressions to be included inside a string.
name = "Ravi" marks = 90 print(f"{name} scored {marks} marks.")Output:
Ravi scored 90 marks.5. Errors in Python
An error is a problem in a program that prevents it from working as intended.
The three common categories are:
Syntax errors
Runtime errors
Logical errors
5.1 Syntax Errors
A syntax error occurs when Python code does not follow the rules of Python grammar.
Example
if age >= 18 print("Eligible")Problem: The colon
:is missing after the condition.Correct code:
if age >= 18: print("Eligible")Other common causes include missing brackets, missing quotation marks, and incorrect indentation in places where indentation is required.
5.2 Runtime Errors
A runtime error occurs while a program is running.
Example: Division by zero
a = 10 b = 0 print(a / b)This causes a
ZeroDivisionError.Example: Invalid type operation
age = "16" print(age + 5)This causes a
TypeErrorbecause Python cannot add a string and an integer.5.3 Logical Errors
A logical error occurs when a program runs without crashing but produces an incorrect result because its logic is wrong.
Example
length = 10 width = 5 area = length + width print(area)Output:
15The program runs, but the area of a rectangle should be calculated using multiplication.
Correct code:
area = length * width print(area)Correct output:
50Difference between error types
Error Type
When it occurs
Example
Syntax error
Code is grammatically incorrect.
Missing
:Runtime error
While the program is executing.
Division by zero
Logical error
Program runs but gives a wrong answer.
Using
+instead of*for area6. Flow of Control
Flow of control refers to the order in which statements of a program are executed.
Python programs commonly use three types of flow:
Sequential flow
Conditional flow
Iterative flow
6.1 Sequential Flow
In sequential flow, statements are executed one after another in the order in which they appear.
Example
a = 10 b = 20 total = a + b print(total)Output:
30The statements execute in this order:
StartAssign
a = 10Assign
b = 20Calculate
total = a + bDisplay
totalEnd6.2 Conditional Flow
Conditional flow allows a program to make decisions and execute different statements depending on whether a condition is true or false.
Python uses conditional statements such as:
ifif-elseif-elif-else
6.3 Iterative Flow
Iterative flow means repeating a set of statements multiple times.
Python provides two main loops:
forloopwhileloop
Example:
forloopfor i in range(1, 4): print(i)Output:
1 2 3The loop executes three times.
Example:
whileloopi = 1 while i <= 3: print(i) i += 1Output:
1 2 3The loop continues while the condition
i <= 3is true.7. Use of Indentation in Python
Indentation means leaving spaces at the beginning of a line of code.
Python uses indentation to define blocks of code. Unlike some other programming languages, Python does not use braces
{}to define the body of anifstatement or loop.Correct indentation
age = 20 if age >= 18: print("You are an adult")Output:
You are an adultThe
print()statement is indented, so it belongs to theifblock.Incorrect indentation
age = 20 if age >= 18: print("You are an adult")This causes an
IndentationError.Important points
Use consistent indentation.
Four spaces are the standard indentation level in Python.
Statements belonging to the same block should have the same indentation.
Indentation is important in conditional statements, loops, functions, and classes.
8. Conditional Statements
Conditional statements are used to make decisions in a program.
8.1 The
ifStatementThe
ifstatement executes a block of code only when its condition is true.Syntax
if condition: statementExample
age = 20 if age >= 18: print("Eligible to vote")Output:
Eligible to voteIf the condition is false, the indented statement is skipped.
Flowchart of
ifStartCheck conditionTrue
Execute blockFalse
Skip blockEnd8.2 The
if-elseStatementThe
if-elsestatement selects one of two blocks.If the condition is true, the
ifblock executes.If the condition is false, the
elseblock executes.
Syntax
if condition: statement1 else: statement2Example: Even or odd number
num = int(input("Enter a number: ")) if num % 2 == 0: print("Even number") else: print("Odd number")If the user enters
8:Enter a number: 8 Even numberIf the user enters
7:Enter a number: 7 Odd numberFlowchart of
if-elseStartCheck conditionTrueExecute
ifblockFalseExecute
elseblockEnd8.3 The
if-elif-elseStatementThe
if-elif-elsestatement is used when there are multiple conditions to check.Python checks conditions from top to bottom. The first true condition's block is executed, and the remaining conditions are skipped.
Syntax
if condition1: statement1 elif condition2: statement2 elif condition3: statement3 else: statement4Example: Checking marks
marks = int(input("Enter marks: ")) if marks >= 90: print("Grade A") elif marks >= 75: print("Grade B") elif marks >= 50: print("Grade C") else: print("Needs improvement")If the user enters
82:Enter marks: 82 Grade BFlowchart of
if-elif-elseStartCheck condition 1TrueBlock 1FalseCheck condition 2True → Block 2
False →
elseblockEnd9. Simple Python Programs Using Conditional Statements
Program 1: Find the Absolute Value of a Number
The absolute value of a number is its distance from zero. It is never negative.
For example:
Absolute value of
5is5.Absolute value of
-5is5.Absolute value of
0is0.
LoadingProgram
num = int(input("Enter a number: ")) if num < 0: absolute = -num else: absolute = num print("Absolute value =", absolute)Sample output
Enter a number: -8 Absolute value = 8Program 2: Sort Three Numbers in Ascending Order
This program arranges three numbers from smallest to largest.
Program
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third number: ")) if a <= b and a <= c: if b <= c: print(a, b, c) else: print(a, c, b) elif b <= a and b <= c: if a <= c: print(b, a, c) else: print(b, c, a) else: if a <= b: print(c, a, b) else: print(c, b, a)Sample output
Enter first number: 30 Enter second number: 10 Enter third number: 20 10 20 30Explanation: The program compares the three numbers and uses nested
ifstatements to display them in ascending order. The<=operator also allows equal numbers.Program 3: Check Divisibility of a Number
A number is divisible by another number if the remainder is zero.
For example:
12is divisible by3because12 % 3is0.13is not divisible by3because13 % 3is1.
Program: Check divisibility by 5
num = int(input("Enter a number: ")) if num % 5 == 0: print("Divisible by 5") else: print("Not divisible by 5")Sample output
Enter a number: 25 Divisible by 5Program: Check divisibility by another number
num = int(input("Enter the number: ")) divisor = int(input("Enter the divisor: ")) if divisor == 0: print("Division by zero is not allowed") elif num % divisor == 0: print("The number is divisible") else: print("The number is not divisible")10. Quick Revision
Operators perform operations on values and variables.
Arithmetic operators perform mathematical calculations.
Relational operators compare values and return Boolean results.
Logical operators combine or reverse conditions.
Assignment operators assign values to variables.
Augmented assignment operators update a variable using an operation.
isandis notcheck object identity.inandnot incheck membership.An expression produces a value; a statement is an instruction.
Operator precedence determines the order of evaluation.
input()accepts console input as a string.print()displays output.Type conversion changes a value from one type to another.
Syntax errors involve invalid Python syntax.
Runtime errors occur during program execution.
Logical errors produce incorrect results despite successful execution.
Sequential flow executes statements in order.
Conditional flow selects blocks based on conditions.
Iterative flow repeats statements.
Indentation defines code blocks in Python.
if,if-else, andif-elif-elseare conditional statements.
11. Important Exam Questions
Define an operator. Explain arithmetic operators with examples.
Differentiate between
=and==.Explain logical operators with a truth table.
What are augmented assignment operators? Give examples.
Differentiate between
==andis.Explain membership operators with examples.
Define expression and statement with examples.
What is operator precedence? Evaluate
5 + 3 * 2.Differentiate between implicit and explicit type conversion.
Explain the use of
input()andprint().Differentiate between syntax, runtime, and logical errors.
What is flow of control? Explain sequential, conditional, and iterative flow.
Why is indentation important in Python?
Explain
if,if-else, andif-elif-elsewith examples.Write a Python program to find the absolute value of a number.
Write a Python program to arrange three numbers in ascending order.
Write a Python program to check whether a number is divisible by 5.
Write a Python program to check whether a number is even or odd.
_________________RUonTop________________
PART A: ITERATIVE STATEMENTS
1. Introduction to Iteration
Iteration means repeating a set of statements again and again until a particular condition is satisfied.
Python provides two main iterative statements:
-
forloop -
whileloop
Example
Suppose we want to print numbers from 1 to 5.
Instead of writing:
print(1) print(2) print(3) print(4) print(5)we can use a loop:
for i in range(1, 6): print(i)Output:
1 2 3 4 5Loops make programs shorter, easier to understand, and easier to maintain.
2.
forLoopThe
forloop is used to repeat a block of statements for each item in a sequence or iterable.Syntax
for variable in sequence: statement1 statement2Example
for i in range(1, 6): print(i)Output:
1 2 3 4 5Working
The loop works as follows:
-
igets the value1→ print1 -
igets the value2→ print2 -
igets the value3→ print3 -
igets the value4→ print4 -
igets the value5→ print5 - Loop ends.
3.
range()FunctionThe
range()function generates a sequence of numbers and is commonly used withforloops.There are three common forms.
3.1
range(stop)range(stop)It generates numbers from
0up to, but not including,stop.Example
for i in range(5): print(i)Output:
0 1 2 3 4
3.2
range(start, stop)range(start, stop)It starts from
startand stops beforestop.Example
for i in range(2, 7): print(i)Output:
2 3 4 5 6
3.3
range(start, stop, step)The third argument specifies the difference between consecutive values.
Example
for i in range(2, 11, 2): print(i)Output:
2 4 6 8 10Example: Reverse counting
A negative step can be used to count backwards.
for i in range(5, 0, -1): print(i)Output:
5 4 3 2 1Important rule
The
stopvalue is not included.For example:
range(1, 5)produces:
1 2 3 4
4. Flowchart of a
forLoopThe basic flow of a loop can be represented as:
START | Initialize / Get next value | Is another value available? / \ YES NO | | Execute loop END body | └───────────────
5.
whileLoopA
whileloop repeatedly executes a block of statements as long as its condition is true.Syntax
while condition: statementExample
i = 1 while i <= 5: print(i) i += 1Output:
1 2 3 4 5Working
Initially:
i = 1Python checks:
i <= 5If it is
True, the loop body executes.Then:
i += 1increases
i.This continues until the condition becomes
False.
6. Flowchart of a
whileLoopSTART | Initialize variable | Check condition / \ TRUE FALSE | | Execute body END | Update variable | └────────────── back to conditionImportant point
A
whileloop must normally change something that affects its condition. Otherwise, the loop may become an infinite loop.Example of an infinite loop
i = 1 while i <= 5: print(i)Here
inever changes, so the condition remains true.
7. Difference Between
forandwhileLoopforLoopwhileLoopCommonly used when iterating over a sequence or a known range of values. Commonly used when repetition depends on a condition. Usually uses range()or another iterable.Uses a Boolean condition. Loop variable is commonly updated automatically by iteration. Programmer usually updates the control variable. Suitable for definite iteration. Suitable for condition-controlled iteration.
8.
breakStatementThe
breakstatement immediately terminates the nearest enclosing loop.Example
for i in range(1, 10): if i == 5: break print(i)Output:
1 2 3 4When
ibecomes5,breakterminates the loop.Flow
1 → 2 → 3 → 4 → 5 | break | END
9.
continueStatementThe
continuestatement skips the remaining statements in the current iteration and moves to the next iteration of the loop.Example
for i in range(1, 6): if i == 3: continue print(i)Output:
1 2 4 5When
iis3,print(i)is skipped.Difference Between
breakandcontinuebreakcontinueTerminates the loop completely. Skips only the current iteration. Control moves outside the loop. Control moves to the next iteration.
10. Nested Loops
A nested loop is a loop placed inside another loop.
The inner loop executes completely for each iteration of the outer loop.
Example
for i in range(1, 4): for j in range(1, 4): print(i, j)Output:
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3Here:
-
iis controlled by the outer loop. -
jis controlled by the inner loop. - The inner loop runs three times for every one iteration of the outer loop.
11. Generating Patterns
Nested loops are commonly used to generate patterns.
Program 1: Square Pattern
for i in range(1, 5): for j in range(1, 5): print("*", end=" ") print()Output:
* * * * * * * * * * * * * * * *Explanation
- Outer loop controls the rows.
- Inner loop controls the columns.
-
end=" "keeps the stars on the same line. -
print()moves to the next line.
Program 2: Increasing Star Pattern
for i in range(1, 6): for j in range(i): print("*", end=" ") print()Output:
* * * * * * * * * * * * * * *
Program 3: Number Pattern
for i in range(1, 6): for j in range(1, i + 1): print(j, end=" ") print()Output:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
12. Summation of a Series
A loop can be used to calculate the sum of a series.
Program: Sum of Numbers from 1 to N
n = int(input("Enter a number: ")) total = 0 for i in range(1, n + 1): total += i print("Sum =", total)If the user enters
5:Enter a number: 5 Sum = 15Calculation
1 + 2 + 3 + 4 + 5 = 15
Program: Sum of Even Numbers
n = int(input("Enter a number: ")) total = 0 for i in range(2, n + 1, 2): total += i print("Sum of even numbers =", total)For
n = 10:Sum of even numbers = 30because:
2 + 4 + 6 + 8 + 10 = 30
13. Factorial of a Positive Number
The factorial of a positive integer
nis the product of all positive integers from1ton.It is represented by
n!.Examples
5! = 5 × 4 × 3 × 2 × 1 = 1203! = 3 × 2 × 1 = 6By definition:
0! = 1Program Using
forLoopn = int(input("Enter a positive number: ")) factorial = 1 if n < 0: print("Please enter a positive number.") else: for i in range(1, n + 1): factorial *= i print("Factorial =", factorial)Sample output
Enter a positive number: 5 Factorial = 120
PART B: STRINGS
14. Introduction to Strings
A string is a sequence of characters enclosed within quotation marks.
Python supports:
-
Single quotes:
'Python' -
Double quotes:
"Python" -
Triple single quotes:
'''Python''' -
Triple double quotes:
"""Python"""
Example
name = "Rajesh" message = 'Welcome to Python' print(name) print(message)Output:
Rajesh Welcome to PythonStrings can contain letters, numbers, spaces, and special characters.
text = "Computer Science 083!"
15. String Indexing
Each character in a string has an index.
Python uses zero-based indexing.
Consider:
word = "PYTHON"Character P Y T H O N Positive index 0 1 2 3 4 5 Negative index -6 -5 -4 -3 -2 -1 Example
word = "PYTHON" print(word[0]) print(word[3]) print(word[-1])Output:
P H N
16. String Operations
Important string operations include:
- Concatenation
- Repetition
- Membership
- Slicing
16.1 String Concatenation
Concatenation means joining two or more strings.
The
+operator is used for concatenation.first = "Hello" second = "Python" result = first + " " + second print(result)Output:
Hello PythonImportant
The
+operator joins strings; it does not automatically convert numbers to strings.age = 16 print("Age: " + str(age))
17. String Repetition
The
*operator can repeat a string multiple times.word = "Hi " print(word * 3)Output:
Hi Hi HiExample
print("*" * 5)Output:
*****
18. String Membership
The
inandnot inoperators check whether a substring or character exists in a string.Example
text = "Python Programming" print("Python" in text) print("Java" in text) print("Java" not in text)Output:
True False True
19. String Slicing
Slicing is used to extract a part of a string.
Syntax
string[start:stop:step]The
stopindex is excluded.Example
word = "COMPUTER" print(word[0:4])Output:
COMPMore examples
word = "PYTHON" print(word[1:4]) print(word[:3]) print(word[3:]) print(word[::-1])Output:
YTH PYT HON NOHTYP
20. Traversing a String Using a Loop
Traversing a string means accessing its characters one by one.
Using a
forloopword = "PYTHON" for ch in word: print(ch)Output:
P Y T H O NUsing indexing
word = "PYTHON" for i in range(len(word)): print(word[i])Output:
P Y T H O N
21.
len()Functionlen()returns the number of characters in a string.Example
name = "Python" print(len(name))Output:
6Spaces are also counted.
text = "Hello World" print(len(text))Output:
11
22. String Methods
Python provides many built-in string methods for processing text.
22.1
capitalize()Converts the first character to uppercase and the remaining characters to lowercase.
text = "python PROGRAMMING" print(text.capitalize())Output:
Python programming
22.2
title()Converts the first character of each word to uppercase.
text = "computer science" print(text.title())Output:
Computer Science
22.3
lower()Converts letters to lowercase.
text = "PYTHON" print(text.lower())Output:
python
22.4
upper()Converts letters to uppercase.
text = "python" print(text.upper())Output:
PYTHON
22.5
count()Counts the number of occurrences of a substring.
text = "banana" print(text.count("a"))Output:
3Example
text = "Python is easy. Python is popular." print(text.count("Python"))Output:
2
23.
find()find()returns the index of the first occurrence of a substring.If the substring is not found, it returns
-1.text = "Computer Science" print(text.find("Science")) print(text.find("Python"))Output:
9 -1
24.
index()index()returns the index of the first occurrence of a substring.text = "Computer Science" print(text.index("Science"))Output:
9Difference between
find()andindex()find()index()Returns the position if found. Returns the position if found. Returns -1if not found.Raises ValueErrorif not found.Example:
print("Python".find("Java"))Output:
-1But:
print("Python".index("Java"))causes a
ValueError.
25.
endswith()Checks whether a string ends with a specified substring.
filename = "notes.txt" print(filename.endswith(".txt"))Output:
True
26.
startswith()Checks whether a string starts with a specified substring.
website = "https://example.com" print(website.startswith("https"))Output:
True
27.
isalnum()Returns
Trueif all characters are alphanumeric — letters or digits — and the string is not empty.text = "Python123" print(text.isalnum())Output:
TrueExample:
print("Python 123".isalnum())Output:
FalseThe space is not alphanumeric.
28.
isalpha()Returns
Trueif all characters are alphabetic and the string is not empty.text = "Python" print(text.isalpha())Output:
Trueprint("Python123".isalpha())Output:
False
29.
isdigit()Returns
Trueif all characters in the string are digits and the string is not empty.number = "12345" print(number.isdigit())Output:
Trueprint("123A".isdigit())Output:
False
30.
islower()Returns
Trueif the string has at least one cased character and all cased characters are lowercase.text = "python" print(text.islower())Output:
True
31.
isupper()Returns
Trueif the string has at least one cased character and all cased characters are uppercase.text = "PYTHON" print(text.isupper())Output:
True
32.
isspace()Returns
Trueif all characters in the string are whitespace characters and the string is not empty.text = " " print(text.isspace())Output:
TrueExample
text = "Hello" print(text.isspace())Output:
False
33.
lstrip()Removes leading whitespace from the left side of a string.
text = " Python" print(text.lstrip())Output:
PythonIt can also remove specified characters from the left.
text = "###Python" print(text.lstrip("#"))Output:
Python
34.
rstrip()Removes trailing whitespace from the right side.
text = "Python " print(text.rstrip())Output:
PythonIt can also remove specified characters from the right.
text = "Python###" print(text.rstrip("#"))Output:
Python
35.
strip()Removes leading and trailing whitespace.
text = " Python " print(text.strip())Output:
PythonIt can also remove specified characters from both ends.
text = "###Python###" print(text.strip("#"))Output:
PythonDifference
Method Removes from lstrip()Left side rstrip()Right side strip()Both sides
36.
replace()replace()replaces occurrences of one substring with another.Syntax
string.replace(old, new)Example
text = "I like Java" new_text = text.replace("Java", "Python") print(new_text)Output:
I like PythonExample
text = "banana" print(text.replace("a", "o"))Output:
bonono
37.
join()join()joins the elements of an iterable using a specified separator.Example
words = ["Python", "is", "easy"] sentence = " ".join(words) print(sentence)Output:
Python is easyAnother example
words = ["2026", "09", "20"] date = "-".join(words) print(date)Output:
2026-09-20
38.
partition()partition()divides a string into three parts based on the first occurrence of a specified separator:- Part before the separator
- Separator itself
- Part after the separator
Example
text = "name:Rajesh" result = text.partition(":") print(result)Output:
('name', ':', 'Rajesh')If the separator is not found, the original string is returned as the first element, followed by two empty strings.
39.
split()split()divides a string into a list of substrings.Example
text = "Python is easy" words = text.split() print(words)Output:
['Python', 'is', 'easy']By default, whitespace is used as the separator.
Example with a separator
data = "A,B,C,D" items = data.split(",") print(items)Output:
['A', 'B', 'C', 'D']
40. Important String Functions and Methods – Quick Table
Function / Method Purpose Example len()Returns length len("Python")capitalize()Capitalises first character "python".capitalize()title()Capitalises each word "hello world".title()lower()Converts to lowercase "PYTHON".lower()upper()Converts to uppercase "python".upper()count()Counts occurrences "banana".count("a")find()Finds position; returns -1if absent"Python".find("th")index()Finds position; raises error if absent "Python".index("th")endswith()Checks ending "file.txt".endswith(".txt")startswith()Checks beginning "Python".startswith("Py")isalnum()Checks letters/digits only "abc123".isalnum()isalpha()Checks alphabetic characters "Python".isalpha()isdigit()Checks digits "123".isdigit()islower()Checks lowercase "python".islower()isupper()Checks uppercase "PYTHON".isupper()isspace()Checks whitespace only " ".isspace()lstrip()Removes leading whitespace/characters " Python".lstrip()rstrip()Removes trailing whitespace/characters "Python ".rstrip()strip()Removes both leading/trailing whitespace " Python ".strip()replace()Replaces substring "Java".replace("Java","Python")join()Joins strings "-".join(["A","B"])partition()Splits into 3 parts around first separator "A:B".partition(":")split()Splits into a list "A,B".split(",")
41. Complete String Example
text = " Python Programming " print("Original:", text) print("Length:", len(text)) print("Upper:", text.upper()) print("Lower:", text.lower()) print("Title:", text.title()) print("Stripped:", text.strip()) print("Starts with Python:", text.strip().startswith("Python")) print("Ends with ing:", text.strip().endswith("ing")) print("Count of m:", text.count("m")) print("Find Python:", text.find("Python"))Output:
Original: Python Programming Length: 21 Upper: PYTHON PROGRAMMING Lower: python programming Title: Python Programming Stripped: Python Programming Starts with Python: True Ends with ing: True Count of m: 2 Find Python: 2
42. Important Points About Strings
- A string is a sequence of characters.
-
String indexing starts from
0. -
Negative indexing starts from
-1. -
Strings support concatenation using
+. -
Strings support repetition using
*. -
inandnot inare used for membership testing. - Slicing is used to extract a part of a string.
- Strings are immutable.
- String methods generally return a new string rather than modifying the original string.
-
len()returns the number of characters. -
find()returns-1when the substring is not found. -
index()raisesValueErrorwhen the substring is not found. -
split()returns a list. -
join()combines elements of an iterable into a string.
43. Important Exam Programs
Program 1: Count Vowels in a String
text = input("Enter a string: ") count = 0 for ch in text: if ch.lower() in "aeiou": count += 1 print("Number of vowels =", count)Sample Output
Enter a string: Computer Science Number of vowels = 6
Program 2: Reverse a String Using a Loop
text = input("Enter a string: ") reverse = "" for ch in text: reverse = ch + reverse print("Reverse =", reverse)Sample Output
Enter a string: Python Reverse = nohtyP
Program 3: Check Palindrome
A palindrome is a word or string that reads the same forwards and backwards.
Examples:
MADAM LEVEL RADARProgram
text = input("Enter a string: ") if text == text[::-1]: print("Palindrome") else: print("Not a palindrome")Sample Output
Enter a string: MADAM Palindrome
Program 4: Count Digits in a String
text = input("Enter a string: ") count = 0 for ch in text: if ch.isdigit(): count += 1 print("Number of digits =", count)
Program 5: Print Multiplication Table
n = int(input("Enter a number: ")) for i in range(1, 11): print(n, "x", i, "=", n * i)For input
5:5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25 5 x 6 = 30 5 x 7 = 35 5 x 8 = 40 5 x 9 = 45 5 x 10 = 50
44. Quick Revision
Iterative Statements
- Iteration means repeating statements.
-
Python provides
forandwhileloops. -
range()generates a sequence of numbers. -
breakterminates the nearest enclosing loop. -
continueskips the current iteration. - A loop inside another loop is called a nested loop.
- Nested loops are useful for generating patterns.
- Loops can be used to calculate sums and factorials.
Strings
- A string is a sequence of characters.
- Strings are immutable.
-
Indexing starts from
0. -
Negative indexing starts from
-1. -
+performs concatenation. -
*performs repetition. -
inandnot inperform membership testing. - Slicing extracts a part of a string.
-
len()returns string length. - String methods provide useful text-processing operations.
-
split()converts a string into a list. -
join()combines strings. -
replace()replaces specified text. -
partition()divides a string into three parts. -
find()returns-1if text is not found. -
index()raises an error if text is not found.
45. Important CBSE Exam Questions
Short Answer Questions
- What is iteration?
- Name the two iterative statements in Python.
-
What is the purpose of the
range()function? -
Differentiate between
breakandcontinue. - What is a nested loop?
- What is an infinite loop?
- What is a string?
- What is string indexing?
- What is string slicing?
- Why are strings called immutable?
-
What is the purpose of
len()? -
Differentiate between
find()andindex(). -
What is the use of
split()? -
What is the use of
join()? -
Differentiate between
strip(),lstrip()andrstrip().
Programming Questions
-
Write a Python program to print numbers from 1 to 10 using a
forloop. - Write a Python program to print even numbers from 1 to 50.
-
Write a Python program to calculate the sum of numbers from 1 to
n. - Write a Python program to calculate the factorial of a positive number.
- Write a Python program to generate a triangular star pattern.
- Write a Python program to generate a multiplication table.
- Write a Python program to count vowels in a string.
- Write a Python program to reverse a string.
- Write a Python program to check whether a string is a palindrome.
- Write a Python program to count the number of digits in a string.
- Write a Python program to count occurrences of a particular character in a string.
- Write a Python program to check whether a string contains only alphabets.
- Write a Python program to replace one word with another in a string.
- Write a Python program to split a sentence into words.
- Write a Python program to join a list of words into a sentence.
______________________RUonTop________________________
1. LISTS
1.1 Introduction to Lists
A list is an ordered collection of items in Python.
A list can contain:
- Numbers
- Strings
- Characters
- Boolean values
- Other lists
- Mixed data types
Lists are written using square brackets
[ ].Example
marks = [75, 82, 91, 68, 88] names = ["Amit", "Riya", "Neha"] mixed = [10, "Python", 3.5, True]Important Features of Lists
- Lists are ordered.
- Lists are mutable, which means their elements can be changed.
- Lists allow duplicate values.
- Lists support indexing and slicing.
- Lists can contain different data types.
- A list can contain another list.
2. List Indexing
Each item in a list has a position called an index.
Python uses zero-based indexing.
List: [10, 20, 30, 40, 50] Index: 0 1 2 3 4 Negative: -5 -4 -3 -2 -1Example
numbers = [10, 20, 30, 40, 50] print(numbers[0]) print(numbers[2]) print(numbers[-1])Output
10 30 50Changing an Item
Because lists are mutable:
numbers = [10, 20, 30] numbers[1] = 99 print(numbers)Output:
[10, 99, 30]3. List Operations
3.1 Concatenation
The
+operator joins two lists.a = [1, 2, 3] b = [4, 5, 6] c = a + b print(c)Output:
[1, 2, 3, 4, 5, 6]3.2 Repetition
The
*operator repeats a list.a = [1, 2] print(a * 3)Output:
[1, 2, 1, 2, 1, 2]3.3 Membership
The operators
inandnot incheck whether an item exists in a list.numbers = [10, 20, 30, 40] print(20 in numbers) print(50 in numbers) print(50 not in numbers)Output:
True False True3.4 Slicing
Slicing is used to extract a portion of a list.
Syntax
list[start:stop]The
stopindex is not included.numbers = [10, 20, 30, 40, 50] print(numbers[1:4])Output:
[20, 30, 40]Other Examples
numbers[:3] # First three elements numbers[2:] # From index 2 to end numbers[:] # Complete list numbers[::2] # Every second element numbers[::-1] # Reverse order4. Traversing a List Using Loops
Traversing means visiting each element of a list one by one.
Using
forLoopnumbers = [10, 20, 30, 40, 50] for x in numbers: print(x)Output:
10 20 30 40 50Traversing Using Index
numbers = [10, 20, 30, 40] for i in range(len(numbers)): print(numbers[i])5. List Built-in Functions and Methods
5.1
len()Returns the number of elements.
numbers = [10, 20, 30, 40] print(len(numbers))Output:
45.2
list()Converts an iterable into a list.
text = "PYTHON" x = list(text) print(x)Output:
['P', 'Y', 'T', 'H', 'O', 'N']5.3
append()Adds one item at the end of a list.
numbers = [10, 20, 30] numbers.append(40) print(numbers)Output:
[10, 20, 30, 40]Important
append()adds its argument as a single element.a = [1, 2] a.append([3, 4]) print(a)Output:
[1, 2, [3, 4]]5.4
extend()Adds multiple elements from another iterable.
a = [1, 2] a.extend([3, 4, 5]) print(a)Output:
[1, 2, 3, 4, 5]Difference
append([3,4]) → [1,2,[3,4]] extend([3,4]) → [1,2,3,4]5.5
insert()Adds an element at a specified position.
Syntax
list.insert(index, value)Example:
numbers = [10, 20, 40] numbers.insert(2, 30) print(numbers)Output:
[10, 20, 30, 40]5.6
count()Returns the number of times an element occurs.
numbers = [10, 20, 10, 30, 10] print(numbers.count(10))Output:
35.7
index()Returns the index of the first occurrence of an item.
numbers = [10, 20, 30, 20] print(numbers.index(20))Output:
1If the value is not present,
index()raises aValueError.5.8
remove()Removes the first occurrence of a specified value.
numbers = [10, 20, 30, 20] numbers.remove(20) print(numbers)Output:
[10, 30, 20]5.9
pop()Removes and returns an element.
numbers = [10, 20, 30, 40] x = numbers.pop() print(x) print(numbers)Output:
40 [10, 20, 30]With Index
numbers.pop(1)This removes the element at index
1.5.10
reverse()Reverses the list in place.
numbers = [10, 20, 30, 40] numbers.reverse() print(numbers)Output:
[40, 30, 20, 10]5.11
sort()Sorts the list in ascending order by default.
numbers = [50, 10, 40, 20, 30] numbers.sort() print(numbers)Output:
[10, 20, 30, 40, 50]Descending Order
numbers.sort(reverse=True)5.12
sorted()sorted()returns a new sorted list and does not change the original list.numbers = [40, 10, 30, 20] new_list = sorted(numbers) print(new_list) print(numbers)Output:
[10, 20, 30, 40] [40, 10, 30, 20]sort()vssorted()sort()sorted()List method Built-in function Changes original list Returns a new sorted list Used with lists Can work with many iterables 6.
min(),max()andsum()min()Finds the smallest value.
numbers = [10, 30, 5, 20] print(min(numbers))Output:
5max()Finds the largest value.
print(max(numbers))Output:
30sum()Calculates the total of numeric elements.
print(sum(numbers))Output:
657. Nested Lists
A list containing another list is called a nested list.
data = [[10, 20], [30, 40], [50, 60]]It can be visualised as:
data ├── [10, 20] ├── [30, 40] └── [50, 60]Accessing Elements
print(data[0]) print(data[1][0])Output:
[10, 20] 30Nested Loop
data = [[1, 2], [3, 4], [5, 6]] for row in data: for value in row: print(value)8. Suggested List Programs
Program 1: Find Maximum and Minimum
numbers = [25, 10, 45, 5, 30] print("Maximum =", max(numbers)) print("Minimum =", min(numbers))Output:
Maximum = 45 Minimum = 5Program 2: Find Mean of Values in a List
Mean is:
Mean = Sum of values / Number of valuesProgram:
numbers = [10, 20, 30, 40, 50] mean = sum(numbers) / len(numbers) print("Mean =", mean)Output:
Mean = 30.0Program 3: Linear Search in a List
Linear search checks elements one by one until the required element is found.
numbers = [10, 25, 30, 45, 50] key = int(input("Enter number to search: ")) found = False for x in numbers: if x == key: found = True break if found: print("Element found") else: print("Element not found")Program 4: Linear Search Using Index
numbers = [10, 20, 30, 40, 50] key = int(input("Enter number: ")) found = False for i in range(len(numbers)): if numbers[i] == key: print("Element found at index", i) found = True break if not found: print("Element not found")Program 5: Count Frequency of an Element
numbers = [10, 20, 10, 30, 10, 40] key = int(input("Enter number: ")) count = 0 for x in numbers: if x == key: count += 1 print("Frequency =", count)9. TUPLES
9.1 Introduction to Tuples
A tuple is an ordered collection of elements.
Tuples are generally written using parentheses
( ).numbers = (10, 20, 30, 40) names = ("Amit", "Riya", "Neha")A tuple can also contain mixed data types:
data = (10, "Python", 3.5, True)Important Features
- Tuples are ordered.
- Tuples support indexing.
- Tuples support slicing.
- Tuples allow duplicate values.
- Tuples can contain different data types.
- Tuples are immutable.
- Tuples can be nested.
10. Tuple Indexing
Tuple indexing is similar to list indexing.
t = (10, 20, 30, 40, 50) print(t[0]) print(t[2]) print(t[-1])Output:
10 30 50Because tuples are immutable, this is not allowed:
t[1] = 100It produces a
TypeError.11. Tuple Operations
11.1 Concatenation
a = (1, 2, 3) b = (4, 5) print(a + b)Output:
(1, 2, 3, 4, 5)11.2 Repetition
a = (1, 2) print(a * 3)Output:
(1, 2, 1, 2, 1, 2)11.3 Membership
t = (10, 20, 30) print(20 in t) print(50 not in t)Output:
True True11.4 Slicing
t = (10, 20, 30, 40, 50) print(t[1:4])Output:
(20, 30, 40)Other examples:
t[:3] t[2:] t[::-1]12. Tuple Built-in Functions and Methods
12.1
len()t = (10, 20, 30, 40) print(len(t))Output:
412.2
tuple()Converts an iterable into a tuple.
x = tuple([10, 20, 30]) print(x)Output:
(10, 20, 30)12.3
count()Counts occurrences of an element.
t = (10, 20, 10, 30, 10) print(t.count(10))Output:
312.4
index()Returns the index of the first occurrence.
t = (10, 20, 30, 20) print(t.index(20))Output:
112.5
sorted()Returns a new list containing the sorted elements.
t = (30, 10, 20) print(sorted(t))Output:
[10, 20, 30]Important
Although the original object is a tuple,
sorted()returns a list.12.6
min(),max()andsum()t = (10, 20, 30, 40) print(min(t)) print(max(t)) print(sum(t))Output:
10 40 10013. Tuple Assignment
Python allows multiple variables to be assigned values at the same time.
a, b, c = 10, 20, 30 print(a) print(b) print(c)This is called multiple assignment or tuple assignment.
Example: Swapping Values
a = 10 b = 20 a, b = b, a print(a) print(b)Output:
20 1014. Nested Tuples
A tuple can contain another tuple.
t = ((10, 20), (30, 40), (50, 60))Accessing elements:
print(t[0]) print(t[1][1])Output:
(10, 20) 4015. Suggested Tuple Programs
Program 1: Maximum, Minimum and Mean
numbers = (10, 20, 30, 40, 50) print("Maximum =", max(numbers)) print("Minimum =", min(numbers)) mean = sum(numbers) / len(numbers) print("Mean =", mean)Output:
Maximum = 50 Minimum = 10 Mean = 30.0Program 2: Linear Search in Tuple
numbers = (10, 20, 30, 40, 50) key = int(input("Enter number: ")) found = False for x in numbers: if x == key: found = True break if found: print("Element found") else: print("Element not found")Program 3: Frequency of an Element
numbers = (10, 20, 10, 30, 10, 40) key = int(input("Enter number: ")) count = 0 for x in numbers: if x == key: count += 1 print("Frequency =", count)16. LIST vs TUPLE
Feature List Tuple Brackets [ ]( )Ordered Yes Yes Mutable Yes No Indexing Yes Yes Slicing Yes Yes Duplicates Allowed Allowed append()Available Not available remove()Available Not available sort()Available Not available count()Available Available index()Available Available Easy Memory Trick
LIST → Mutable TUPLE → Immutable17. DICTIONARY
17.1 Introduction
A dictionary is a collection of key-value pairs.
It is written using curly brackets
{ }.Example
student = { "name": "Amit", "age": 16, "marks": 85 }Here:
"name" → key "Amit" → value "age" → key 16 → value "marks" → key 85 → valueA dictionary is useful when data needs to be stored with meaningful keys.
18. Accessing Items Using Keys
Dictionary values are accessed using their keys.
student = { "name": "Amit", "age": 16, "marks": 85 } print(student["name"]) print(student["marks"])Output:
Amit 85Important
If a key does not exist, using:
student["city"]causes a
KeyError.The
get()method can be used when you want to avoid this behaviour.19. Mutability of Dictionary
Dictionaries are mutable.
This means we can:
- Add a new item
- Modify an existing item
- Delete an item
19.1 Adding a New Item
student = { "name": "Amit", "marks": 85 } student["age"] = 16 print(student)19.2 Modifying an Existing Item
student["marks"] = 90 print(student)The value associated with the key
"marks"is changed.20. Traversing a Dictionary
Traversing Keys
student = { "name": "Amit", "age": 16, "marks": 85 } for key in student: print(key)Traversing Values
for value in student.values(): print(value)Traversing Keys and Values
for key, value in student.items(): print(key, value)Output:
name Amit age 16 marks 8521. Dictionary Functions and Methods
21.1
len()Returns the number of key-value pairs.
student = {"name": "Amit", "age": 16, "marks": 85} print(len(student))Output:
321.2
dict()Creates a dictionary.
student = dict(name="Amit", age=16) print(student)Output:
{'name': 'Amit', 'age': 16}21.3
keys()Returns a view containing dictionary keys.
student = {"name": "Amit", "age": 16} print(student.keys())To traverse:
for key in student.keys(): print(key)21.4
values()Returns the dictionary values.
for value in student.values(): print(value)21.5
items()Returns key-value pairs.
for key, value in student.items(): print(key, value)21.6
get()Returns the value associated with a key.
student = {"name": "Amit", "marks": 85} print(student.get("name"))Output:
AmitIf the key is absent:
print(student.get("city"))returns:
NoneA default value can also be supplied:
print(student.get("city", "Not Available"))Output:
Not Available21.7
update()Adds or modifies multiple key-value pairs.
student = {"name": "Amit", "marks": 80} student.update({"marks": 90, "age": 16}) print(student)21.8
deldelis a Python statement used to delete a dictionary item.student = { "name": "Amit", "age": 16, "marks": 85 } del student["age"] print(student)21.9
clear()Removes all items.
student.clear() print(student)Output:
{}21.10
fromkeys()Creates a dictionary from a sequence of keys.
keys = ["Name", "Age", "City"] student = dict.fromkeys(keys) print(student)Output:
{'Name': None, 'Age': None, 'City': None}A common value can also be provided:
student = dict.fromkeys(keys, "Unknown")21.11
copy()Creates a shallow copy of a dictionary.
student = {"name": "Amit", "marks": 85} new_student = student.copy() print(new_student)21.12
pop()Removes the specified key and returns its value.
student = { "name": "Amit", "age": 16, "marks": 85 } x = student.pop("age") print(x) print(student)Output:
16 {'name': 'Amit', 'marks': 85}21.13
popitem()Removes and returns the last inserted key-value pair.
student = { "name": "Amit", "age": 16, "marks": 85 } x = student.popitem() print(x) print(student)21.14
setdefault()Returns the value of a key.
If the key does not exist, it inserts the key with the specified default value.
student = {"name": "Amit"} student.setdefault("age", 16) print(student)Output:
{'name': 'Amit', 'age': 16}If
"name"already exists:student.setdefault("name", "Riya")the existing value is not replaced.
22.
max(),min()andsorted()with Dictionarymax()By default,
max()operates on dictionary keys.d = {"b": 20, "a": 10, "c": 30} print(max(d))Output:
cmin()print(min(d))Output:
asorted()sorted()returns a list of sorted keys by default.d = {"b": 20, "a": 10, "c": 30} print(sorted(d))Output:
['a', 'b', 'c']Important
For dictionaries,
max(),min()andsorted()normally work with keys, unless another iterable such asvalues()oritems()is explicitly supplied.23. Suggested Dictionary Program: Character Frequency
Problem
Write a program to count how many times each character appears in a string using a dictionary.
Program
text = input("Enter a string: ") frequency = {} for ch in text: if ch in frequency: frequency[ch] += 1 else: frequency[ch] = 1 print(frequency)Example Input
bananaOutput
{'b': 1, 'a': 3, 'n': 2}Explanation
For every character:
- If it already exists as a key, increase its value.
- Otherwise, create the key with value
1.
24. Character Frequency Using
get()The same program can be written more compactly:
text = input("Enter a string: ") frequency = {} for ch in text: frequency[ch] = frequency.get(ch, 0) + 1 print(frequency)For:
appleOutput:
{'a': 1, 'p': 2, 'l': 1, 'e': 1}25. Employee Dictionary Program
Problem
Create a dictionary containing employee names and their salaries and access the information.
Program
employees = { "Amit": 35000, "Riya": 42000, "Neha": 38000 } for name, salary in employees.items(): print("Employee:", name) print("Salary:", salary)Output:
Employee: Amit Salary: 35000 Employee: Riya Salary: 42000 Employee: Neha Salary: 3800026. Employee Details Using Nested Dictionary
For storing multiple details for each employee:
employees = { "E101": { "name": "Amit", "salary": 35000 }, "E102": { "name": "Riya", "salary": 42000 } } print(employees["E101"]["name"]) print(employees["E101"]["salary"])Output:
Amit 35000This is an example of a nested dictionary.
27. LIST, TUPLE AND DICTIONARY – Quick Comparison
Feature List Tuple Dictionary Syntax [ ]( ){key:value}Ordered Yes Yes Yes* Mutable Yes No Yes Access Index Index Key Duplicate elements Yes Yes Keys must be unique Slicing Yes Yes No Main purpose Collection of items Fixed collection Key-value data *Modern Python dictionaries preserve insertion order.28. INTRODUCTION TO PYTHON MODULES
28.1 What is a Module?
A module is a Python file containing functions, variables, classes or other Python code that can be reused in another program.
Python provides many built-in modules.
Examples:
math random statisticsModules help programmers:
- Reuse code
- Organise programs
- Avoid writing common functions again
- Access ready-made functionality
29. Importing a Module Using
importSyntax
import module_nameExample:
import math print(math.sqrt(25))Output:
5.0Here:
math → module sqrt → functionThe dot
.is used to access members of the module.30. Importing Using
fromA particular function can be imported from a module.
Syntax
from module_name import function_nameExample:
from math import sqrt print(sqrt(25))Now we can use
sqrt()directly.Importing Multiple Functions
from math import sqrt, ceil, floor31.
importvsfrom ... importimportfrom ... importImports the module Imports selected members Use module name with dot Can use imported member directly math.sqrt(25)sqrt(25)32. MATH MODULE
The
mathmodule provides mathematical functions and constants.First import it:
import math32.1
math.piRepresents the mathematical constant π.
import math print(math.pi)32.2
math.eRepresents Euler's number.
print(math.e)32.3
math.sqrt()Returns the square root.
print(math.sqrt(49))Output:
7.032.4
math.ceil()Returns the smallest integer greater than or equal to a number.
print(math.ceil(4.2))Output:
532.5
math.floor()Returns the largest integer less than or equal to a number.
print(math.floor(4.8))Output:
4ceil()vsfloor()ceil(4.2) → 5 floor(4.8) → 432.6
math.pow()Returns a number raised to a power.
print(math.pow(2, 3))Output:
8.032.7
math.fabs()Returns the absolute value of a number as a floating-point value.
print(math.fabs(-15))Output:
15.033. Trigonometric Functions
The
mathmodule provides:sin() cos() tan()Example
import math print(math.sin(0)) print(math.cos(0)) print(math.tan(0))Output:
0.0 1.0 0.0Important
The trigonometric functions in Python's
mathmodule use radians, not degrees.For example:
print(math.sin(math.pi / 2))Output:
1.034. MATH MODULE QUICK TABLE
Function/Constant Purpose Example math.piValue of π math.pimath.eEuler's number math.emath.sqrt(x)Square root math.sqrt(25)math.ceil(x)Round upward math.ceil(4.2)math.floor(x)Round downward math.floor(4.8)math.pow(x,y)x raised to y math.pow(2,3)math.fabs(x)Absolute float value math.fabs(-5)math.sin(x)Sine math.sin(x)math.cos(x)Cosine math.cos(x)math.tan(x)Tangent math.tan(x)35. RANDOM MODULE
The
randommodule is used to generate pseudo-random values.Import it using:
import random35.1
random.random()Returns a random floating-point number from:
0.0 ≤ number < 1.0Example:
import random print(random.random())A possible output could be:
0.638421The output can be different each time.
35.2
random.randint()Returns a random integer between two specified values, including both endpoints.
import random print(random.randint(1, 10))Possible output:
7It can produce any integer from
1through10.35.3
random.randrange()Returns a randomly selected value from a range.
print(random.randrange(1, 10))Possible values:
1, 2, 3, ..., 9The stop value
10is excluded.It can also use start and step:
random.randrange(2, 20, 2)Possible values:
2, 4, 6, 8, ..., 1836.
randint()vsrandrange()randint(a,b)randrange(a,b)Includes bExcludes brandint(1,10)→ 1 to 10randrange(1,10)→ 1 to 9Returns integer Returns integer 37. STATISTICS MODULE
The
statisticsmodule provides functions for basic statistical calculations.Import:
import statistics37.1
mean()The mean is the arithmetic average.
import statistics numbers = [10, 20, 30, 40, 50] print(statistics.mean(numbers))Output:
3037.2
median()The median is the middle value when the data is arranged in sorted order.
numbers = [10, 20, 30, 40, 50] print(statistics.median(numbers))Output:
30For an even number of values:
numbers = [10, 20, 30, 40] print(statistics.median(numbers))Output:
25.037.3
mode()The mode is the most frequently occurring value.
numbers = [10, 20, 20, 30, 20, 40] print(statistics.mode(numbers))Output:
2038. Importing Statistics Functions Directly
Instead of:
import statistics print(statistics.mean([10, 20, 30]))we can write:
from statistics import mean print(mean([10, 20, 30]))Multiple functions:
from statistics import mean, median, modeThen:
numbers = [10, 20, 20, 30] print(mean(numbers)) print(median(numbers)) print(mode(numbers))39. Complete Module Example
import math import random import statistics numbers = [10, 20, 20, 30, 40] print("Square Root:", math.sqrt(25)) print("Random Number:", random.randint(1, 10)) print("Mean:", statistics.mean(numbers)) print("Median:", statistics.median(numbers)) print("Mode:", statistics.mode(numbers))Possible output:
Square Root: 5.0 Random Number: 7 Mean: 24 Median: 20 Mode: 20The random number may be different each time.
40. IMPORTANT DIFFERENCES
append()vsextend()a = [1, 2] a.append([3, 4])Result:
[1, 2, [3, 4]]Whereas:
a = [1, 2] a.extend([3, 4])Result:
[1, 2, 3, 4]remove()vspop()remove()pop()Removes by value Removes by index Does not return removed item Returns removed item a.remove(20)a.pop(1)sort()vssorted()sort() → changes original list sorted() → returns a new sorted listList vs Tuple
List → [10, 20, 30] Tuple → (10, 20, 30)List → Mutable Tuple → ImmutableDictionary Access
student["name"]accesses a value directly using its key.
Whereas:
student.get("name")also accesses the value but provides a safer way to handle a missing key.
41. QUICK REVISION
Lists
- List is an ordered and mutable collection.
- Uses
[ ]. - Supports indexing and slicing.
- Important methods:
append(),extend(),insert(),remove(),pop(),reverse(),sort(). - Important functions:
len(),list(),min(),max(),sum(),sorted().
Tuples
- Tuple is ordered and immutable.
- Usually uses
( ). - Supports indexing, slicing and membership.
- Important methods:
count(),index(). - Important functions:
len(),tuple(),sorted(),min(),max(),sum().
Dictionary
- Stores data as key-value pairs.
- Uses
{ }. - Accessed using keys.
- Mutable.
- Important methods:
keys(),values(),items(),get(),update(),clear(),copy(),pop(),popitem(),setdefault().
Modules
- A module is reusable Python code.
importimports a module.from ... importimports selected members.mathprovides mathematical functions.randomprovides random-number functions.statisticsprovides statistical functions.
42. IMPORTANT EXAM QUESTIONS
Very Short Answer Questions
- What is a list?
- What is the difference between a list and a tuple?
- What is indexing?
- What is slicing?
- What is the purpose of
append()? - What is the difference between
append()andextend()? - What is the use of
pop()? - What does
sort()do? - What is the difference between
sort()andsorted()? - What is a nested list?
- What is a tuple?
- Why is a tuple called immutable?
- What is tuple assignment?
- What is a dictionary?
- What is a key-value pair?
- How can an item be accessed from a dictionary?
- What is the purpose of
keys()? - What is the purpose of
items()? - What is the difference between
get()and direct key access? - What is a module?
- How do you import the
mathmodule? - What is the use of
math.sqrt()? - What is the difference between
randint()andrandrange()? - What is the use of
statistics.mean()?
43. Important Programming Questions
Students should practise the following programs:
Lists
- Create a list and display all its elements.
- Find the maximum value in a list.
- Find the minimum value in a list.
- Calculate the mean of numbers stored in a list.
- Search for an element using linear search.
- Count the frequency of a given element.
- Sort a list in ascending order.
- Sort a list in descending order.
- Reverse a list.
- Count even and odd numbers in a list.
Tuples
- Create a tuple and display its elements.
- Find maximum and minimum values.
- Find the mean of tuple elements.
- Perform linear search.
- Count the frequency of an element.
- Demonstrate tuple assignment.
- Demonstrate nested tuples.
Dictionaries
- Create a student dictionary.
- Add a new key-value pair.
- Modify an existing value.
- Display all keys.
- Display all values.
- Display all key-value pairs.
- Create a character-frequency dictionary.
- Create an employee-salary dictionary.
- Search for an employee's salary.
- Delete an item from a dictionary.
Modules
- Find the square root using
math. - Find ceiling and floor values.
- Generate a random integer.
- Generate a random number using
randrange(). - Find mean, median and mode using
statistics.
44. CBSE EXAM TIPS
Remember these points carefully:
List → Mutable Tuple → Immutable Dictionary → Key-Value pairsappend() → Adds one item extend() → Adds multiple items insert() → Adds at a particular index remove() → Removes by value pop() → Removes by index and returns itemsort() → Changes the list sorted() → Returns a new sorted listrandint(a,b) → b is included randrange(a,b) → b is excludedfind() is associated with strings. index() is available for lists, tuples and strings.For dictionaries:
d.keys() → Keys d.values() → Values d.items() → Key-value pairs d.get() → Safely access a value d.update() → Add/modify items d.pop() → Remove specified key d.popitem() → Remove last inserted pair d.clear() → Remove all itemsFor modules:
import math math.sqrt(25)or:
from math import sqrt sqrt(25)_______U3__________________RUonTop_____________U3__________Unit 3: Society, Law and Ethics
Introduction
Computers, the Internet and digital technologies have become an important part of modern society. We use technology for:
- Education
- Communication
- Banking
- Shopping
- Entertainment
- Healthcare
- Government services
- Business and employment
Technology provides many benefits, but its improper use can create problems such as cyber crime, privacy violations, plagiarism, cyber bullying and electronic waste.
Therefore, every computer user should understand digital responsibility, cyber safety, law and ethics.
1. DIGITAL FOOTPRINTS
1.1 What is a Digital Footprint?
A digital footprint is the trail or record of information that a person leaves behind while using the Internet and digital devices.
Whenever we use websites, social media, apps or online services, we may leave information behind.
Examples
A digital footprint may include:
- Websites we visit
- Online searches
- Social media posts
- Comments and likes
- Photos and videos uploaded
- Emails sent
- Online purchases
- Online registrations
- Reviews posted on websites
- Location information shared by apps
- Online accounts created
Example
Suppose a student:
- Creates an Instagram account.
- Posts a photograph.
- Comments on a friend's post.
- Searches for a product.
- Buys the product online.
These activities can create a digital footprint.
1.2 Types of Digital Footprints
Digital footprints are commonly divided into two types:
A. Active Digital Footprint
An active digital footprint is information that a user deliberately provides or shares online.
Examples
- Posting a photograph
- Writing a comment
- Sending an email
- Filling an online form
- Creating a social media post
- Uploading a video
B. Passive Digital Footprint
A passive digital footprint is information collected about a user without the user actively posting it.
Examples
- Websites recording IP addresses
- Cookies storing browsing information
- Location information collected by an application
- Websites recording visit statistics
1.3 Why Digital Footprints Matter
Digital footprints can affect:
- Privacy
- Reputation
- Security
- Education
- Employment
- Personal relationships
Important Rule
Think before you post.
Information shared online can be copied, saved, forwarded or redistributed.
1.4 How to Manage Your Digital Footprint
- Think carefully before posting.
- Avoid sharing unnecessary personal information.
- Use strong passwords.
- Review privacy settings.
- Delete unused accounts.
- Avoid suspicious websites.
- Do not accept unknown friend/follow requests blindly.
- Check information before sharing it.
- Avoid posting sensitive documents.
- Remember that deleting a post does not guarantee that all copies have disappeared.
2. DIGITAL SOCIETY AND NETIZEN
2.1 What is a Digital Society?
A digital society is a society in which digital technologies are widely used for communication, education, business, government services and everyday activities.
Examples
- Online classes
- Digital payments
- Online banking
- E-commerce
- Video conferencing
- Online government services
- Social networking
3. NETIZEN
3.1 Meaning of Netizen
The word Netizen is formed from:
Internet + Citizen = NetizenA netizen is a person who actively uses the Internet and participates in the online community.
A responsible netizen should:
- Respect other users.
- Follow laws.
- Protect personal information.
- Communicate politely.
- Avoid spreading false information.
- Respect intellectual property.
- Report harmful or illegal activities.
4. NET ETIQUETTES
4.1 What is Netiquette?
Netiquette means Internet etiquette.
It refers to the rules and good manners that should be followed while communicating and behaving online.
Important Netiquette Rules
- Be polite and respectful.
- Do not use offensive language.
- Do not intentionally hurt others.
- Do not type everything in CAPITAL LETTERS unnecessarily.
- Do not spread rumours.
- Respect other people's privacy.
- Do not share someone else's photograph without permission.
- Do not send spam.
- Give credit to original creators.
- Verify information before forwarding it.
- Do not participate in cyber bullying.
- Use appropriate language in online discussions.
5. COMMUNICATION ETIQUETTES
Communication etiquette means following appropriate manners while communicating using digital technologies.
Examples include:
- Chat
- Video calls
- Online meetings
- Discussion forums
- Messaging applications
Good Communication Practices
1. Use a meaningful subject in an email
Bad:
Subject: HiBetter:
Subject: Class 11 Computer Science Assignment2. Be clear and brief
Write information in a clear manner.
3. Avoid unnecessary messages
Do not send repeated messages or spam.
4. Respect others
Do not use abusive or insulting language.
5. Check before sending
Check:
- Recipient
- Message
- Attachments
- Links
before sending.
6. Do not forward private messages
Private communication should not be shared publicly without appropriate permission.
6. SOCIAL MEDIA ETIQUETTES
Social media etiquette means using social networking platforms responsibly.
Important Rules
- Think before posting.
- Do not post private information publicly.
- Respect other people's opinions.
- Do not upload someone else's photograph without permission.
- Do not spread fake news.
- Do not post offensive content.
- Do not share passwords or OTPs.
- Avoid arguments and abusive comments.
- Report inappropriate or harmful content.
- Use privacy settings carefully.
Remember
POST → THINK → CHECK → SHARE7. DATA PROTECTION
7.1 What is Data Protection?
Data protection means protecting data from:
- Unauthorised access
- Unauthorised modification
- Loss
- Theft
- Misuse
- Unauthorised disclosure
Examples of Sensitive Data
- Passwords
- Bank details
- Credit/debit card information
- Aadhaar-related information
- Personal photographs
- Medical records
- Educational records
- Personal identification information
8. INTELLECTUAL PROPERTY RIGHTS (IPR)
8.1 What is Intellectual Property?
Intellectual Property (IP) refers to creations of the human mind, such as:
- Inventions
- Literary works
- Software
- Music
- Artistic works
- Designs
- Brand names
- Logos
Intellectual Property Rights (IPR) are legal rights that protect such creations.
9. COPYRIGHT
9.1 Meaning of Copyright
Copyright is a legal protection given to the creators of original works.
It can apply to:
- Books
- Articles
- Music
- Films
- Photographs
- Videos
- Computer programs
- Artwork
- Educational content
Example
If a person creates an original educational video, another person should not simply copy and publish it as their own work.
10. PATENT
10.1 Meaning of Patent
A patent is a legal right granted for an invention that satisfies applicable legal requirements.
It can protect inventions such as:
- New machines
- New technical processes
- New products
- Certain technological innovations
Example
A company develops a new technological device. It may seek patent protection for the invention if it meets the applicable requirements.
11. TRADEMARK
11.1 Meaning of Trademark
A trademark is a sign that identifies and distinguishes the goods or services of one business from those of others.
It may include:
- Brand names
- Logos
- Symbols
- Certain words or phrases
Example
A company's distinctive brand name or logo may be protected as a trademark.
12. COPYRIGHT vs PATENT vs TRADEMARK
Copyright Patent Trademark Protects original creative works Protects qualifying inventions Identifies/distinguishes goods or services Books, music, software, videos Machines, processes, technical inventions Brand names, logos, marks Concerned mainly with creative expression Concerned with inventions Concerned with commercial identity 13. VIOLATION OF IPR
Violation of Intellectual Property Rights means using protected intellectual property in a way that infringes the owner's legal rights.
Important examples include:
- Plagiarism
- Copyright infringement
- Trademark infringement
14. PLAGIARISM
Meaning
Plagiarism means presenting someone else's work, ideas or words as your own without appropriate acknowledgement.
Examples
- Copying an assignment from the Internet.
- Submitting another student's project as your own.
- Copying an article without credit.
- Using another person's ideas without acknowledgement.
How to Avoid Plagiarism
- Write in your own words.
- Give credit to sources.
- Use quotation marks for direct quotations.
- Mention references where required.
- Do not submit copied work as your own.
15. COPYRIGHT INFRINGEMENT
Copyright infringement occurs when someone uses copyrighted material in a way that violates the copyright owner's rights.
Examples
- Copying and distributing a copyrighted book without permission.
- Re-uploading copyrighted videos without appropriate rights.
- Using copyrighted software illegally.
- Copying copyrighted images and claiming them as your own.
Important
Not every use of copyrighted material is automatically infringement; applicable copyright law may provide exceptions or limitations in particular situations.
16. TRADEMARK INFRINGEMENT
Trademark infringement generally involves unauthorised use of a trademark in a way that may cause confusion or otherwise violates the rights associated with the mark.
Example
A business uses another company's brand name or logo in a misleading manner to make customers believe that the products or services are associated with the original company.
17. OPEN SOURCE SOFTWARE
17.1 Meaning
Open source software is software whose source code is made available under a licence that permits users to use, inspect, modify and redistribute it, subject to the licence terms.
Examples
- Linux
- Mozilla Firefox
- LibreOffice
- Python
Important
Open source does not simply mean "software that is free of cost."
It refers primarily to the availability of source code and the rights granted by the applicable licence.
18. SOFTWARE LICENSING
A software licence is a legal agreement that specifies how software can be used, modified and distributed.
Different licences provide different permissions and conditions.
Examples:
- Creative Commons licences
- GNU General Public License (GPL)
- Apache License
19. CREATIVE COMMONS
Creative Commons (CC) provides a set of standard licences that creators can use to specify how others may use their creative works.
Different Creative Commons licences impose different conditions.
Common conditions include:
- BY – Attribution required
- SA – ShareAlike
- NC – NonCommercial
- ND – NoDerivatives
Important
Always check the exact Creative Commons licence attached to a work before using it.
20. GNU GENERAL PUBLIC LICENSE (GPL)
The GNU General Public License (GPL) is a widely used free and open-source software licence.
It allows users to use, study, modify and redistribute covered software subject to its licence conditions.
A key feature of the GPL is its copyleft approach: under the applicable terms, modified/distributed versions must preserve the required freedoms and licensing conditions.
21. APACHE LICENSE
The Apache License is a permissive open-source software licence.
It allows users to:
- Use the software
- Modify the software
- Distribute the software
- Use it in many types of projects
subject to the licence conditions.
The Apache License also contains provisions relating to copyright and patents.
22. CYBER CRIME
22.1 Definition
Cyber crime refers to illegal activities involving computers, computer networks, digital devices or the Internet.
Examples include:
- Hacking
- Phishing
- Online fraud
- Identity theft
- Malware attacks
- Ransomware
- Cyber bullying
23. HACKING
Meaning
Hacking generally refers to gaining access to a computer system, network or account by exploiting weaknesses or bypassing security controls.
In the context of cyber crime, unauthorised hacking can be illegal.
Example
An attacker obtains another person's password and accesses their email account without permission.
Protection
- Use strong passwords.
- Enable multi-factor authentication where available.
- Keep software updated.
- Do not share passwords.
- Avoid suspicious links.
24. EAVESDROPPING
Meaning
Eavesdropping means secretly listening to or monitoring private communications without proper authorisation.
Example
An attacker secretly intercepts network communication to obtain confidential information.
Protection
- Use secure networks.
- Prefer encrypted websites and services.
- Avoid sensitive transactions on untrusted networks.
- Keep devices and software updated.
25. PHISHING
Meaning
Phishing is a social-engineering technique in which an attacker attempts to trick a person into revealing sensitive information or performing an unsafe action.
Phishing may happen through:
- SMS
- Websites
- Social media
- Messaging applications
- Phone calls
Example
A person receives an email:
Your bank account will be blocked today. Click here to verify your account.The link leads to a fake website designed to steal login information.
Warning Signs
- Urgent language
- Suspicious links
- Unknown sender
- Requests for passwords
- Requests for OTPs
- Unexpected attachments
- Spelling or formatting mistakes
26. FRAUD EMAILS
Fraud emails are deceptive emails designed to:
- Steal money
- Obtain passwords
- Collect personal information
- Spread malware
- Trick users into clicking malicious links
Example
An email claims:
Congratulations! You have won ₹10,00,000. Pay ₹5,000 processing fee to receive your prize.This may be an online scam.
Safety Rule
Never send money or sensitive information simply because an email asks for it. Verify independently.
27. RANSOMWARE
Meaning
Ransomware is malicious software that can block access to files or systems, often by encrypting files, and then demand payment from the victim.
Typical Process
Ransomware enters system ↓ Files are encrypted ↓ Victim cannot access files ↓ Attacker demands ransomProtection
- Maintain regular backups.
- Keep operating systems updated.
- Keep security software updated.
- Do not open suspicious attachments.
- Avoid suspicious links.
- Use strong security practices.
Important
Paying a ransom does not guarantee recovery of files.
28. CYBER TROLLS
A cyber troll is a person who deliberately posts provocative, insulting or disruptive content online to cause arguments or provoke reactions.
Example
Someone repeatedly posts offensive comments under online discussions just to create conflict.
How to Deal with Trolling
- Do not unnecessarily engage.
- Block the user when appropriate.
- Report abusive behaviour.
- Keep evidence if serious harassment is involved.
29. CYBER BULLYING
Cyber bullying is the use of digital technologies to repeatedly harass, threaten, humiliate or intimidate another person.
It can occur through:
- Social media
- Messaging apps
- Online games
- Discussion forums
Examples
- Sending threatening messages
- Spreading humiliating rumours
- Sharing embarrassing content
- Repeatedly posting abusive comments
- Creating fake accounts to harass someone
What to Do
- Do not retaliate.
- Save evidence.
- Block the offender.
- Report the account/content.
- Tell a trusted adult, teacher or appropriate authority.
- Seek help if there is a serious threat.
30. CYBER SAFETY
Cyber safety means using computers, smartphones, networks and the Internet in a secure and responsible manner.
31. SAFELY BROWSING THE WEB
Important Safety Practices
- Use trusted websites.
- Check the website address carefully.
- Look for HTTPS when entering sensitive information.
- Do not click suspicious links.
- Do not download files from unknown sources.
- Keep browsers updated.
- Avoid entering passwords on suspicious websites.
- Log out of accounts on shared computers.
- Avoid unnecessary browser extensions.
- Be careful with pop-ups and unexpected downloads.
32. IDENTITY PROTECTION
Meaning
Identity protection means protecting personal information from unauthorised use.
Information to Protect
- Full name
- Address
- Phone number
- Email address
- Passwords
- OTPs
- Bank details
- Government identification information
- Personal photographs
Safety Measures
- Use strong and unique passwords.
- Enable multi-factor authentication.
- Never share OTPs.
- Avoid sharing unnecessary personal information.
- Check privacy settings.
- Be careful with unknown callers and messages.
- Monitor suspicious account activity.
33. CONFIDENTIALITY
Confidentiality means ensuring that information is available only to authorised persons.
Example
A student's academic record should not be publicly accessible to everyone.
Ways to Maintain Confidentiality
- Password protection
- Encryption
- Access control
- Secure networks
- Multi-factor authentication
- Proper permissions
CIA Triad
Information security is often explained using:
C → Confidentiality I → Integrity A → AvailabilityConfidentiality
Only authorised people can access information.
Integrity
Information remains accurate and is not changed improperly.
Availability
Authorised users can access information when needed.
34. MALWARE
34.1 Meaning
Malware stands for Malicious Software.
It refers to software intentionally designed to perform harmful or unauthorised actions.
Examples include:
- Viruses
- Trojans
- Adware
- Ransomware
- Spyware
- Worms
This syllabus specifically includes:
- Virus
- Trojan
- Adware
35. COMPUTER VIRUS
A computer virus is malicious code that can attach itself to legitimate files or programs and replicate when the infected host is executed or otherwise activated.
Possible Effects
- Corrupt files
- Delete data
- Slow down the system
- Modify programs
- Cause unexpected behaviour
Protection
- Use reputable security software.
- Keep software updated.
- Avoid unknown files.
- Scan external storage devices.
- Do not run suspicious programs.
36. TROJAN
A Trojan or Trojan horse is malware that disguises itself as legitimate or useful software to trick a user into installing or running it.
Example
A user downloads a program advertised as a useful utility, but the program secretly performs malicious activities.
Protection
- Download software from trusted sources.
- Avoid pirated/cracked software.
- Check the publisher.
- Keep security software updated.
37. ADWARE
Adware is software that displays unwanted advertisements.
Some adware may also collect information or modify browser behaviour, depending on the program.
Common Signs
- Excessive pop-up advertisements
- Unexpected browser redirects
- Unwanted extensions
- Changes to browser settings
Protection
- Install software from trusted sources.
- Avoid suspicious downloads.
- Review browser extensions.
- Use security software.
38. VIRUS vs TROJAN vs ADWARE
Virus Trojan Adware Can replicate by infecting files/programs Disguises itself as legitimate software Displays advertisements Can damage or modify files Tricks users into installing/running it May cause unwanted pop-ups Usually spreads through infected files/programs Often relies on social engineering Often comes bundled with software 39. E-WASTE MANAGEMENT
39.1 What is E-Waste?
E-waste means discarded electrical and electronic equipment and components.
Examples:
- Old computers
- Keyboards
- Monitors
- Printers
- Mobile phones
- Chargers
- Batteries
- Television sets
- Circuit boards
- Electronic accessories
40. Problems Caused by E-Waste
Improper disposal of electronic waste can:
- Pollute soil
- Pollute water
- Release hazardous substances
- Harm human health
- Harm animals and ecosystems
- Waste valuable recyclable materials
41. Proper Disposal of Electronic Gadgets
Follow the 4R approach where applicable:
Reduce Reuse Repair RecycleGood Practices
- Repair devices when practical.
- Reuse working equipment.
- Donate usable devices where appropriate.
- Recycle through authorised e-waste collection/recycling channels.
- Do not throw electronic waste into ordinary household waste.
- Handle batteries carefully.
- Erase personal data before giving away or recycling a device.
Important
Electronic devices may contain valuable materials as well as substances requiring controlled handling. Therefore, e-waste should be managed through appropriate collection and recycling systems.
42. INFORMATION TECHNOLOGY ACT (IT ACT)
42.1 Introduction
The Information Technology Act, 2000 is an important Indian law concerning electronic records, electronic communication and various aspects of cyber activities.
It provides a legal framework for areas including:
- Electronic records
- Electronic transactions
- Digital/electronic signatures
- Certain cyber offences
- Penalties and legal procedures relating to specified activities
The Act has also been amended over time.
43. Importance of the IT Act
The IT Act provides legal recognition and a legal framework for electronic activities.
It helps address issues related to:
- Electronic records
- Electronic authentication
- Cyber offences
- Unauthorised access
- Damage to computer resources
- Certain forms of online misuse
Important
Students should understand that cyber activities are subject to laws, and misuse of computers or the Internet can have legal consequences.
44. TECHNOLOGY AND SOCIETY
Technology has changed the way people:
- Learn
- Work
- Communicate
- Travel
- Shop
- Access government services
- Obtain information
However, technology should be designed and used in a way that promotes equality, accessibility and inclusion.
Two important issues in the syllabus are:
- Gender issues
- Disability issues
45. GENDER ISSUES IN TECHNOLOGY
Meaning
Gender issues refer to unequal opportunities, access, participation or treatment based on gender in the use and development of technology.
Examples
- Unequal access to computers or Internet facilities
- Stereotypes about who should study technology
- Unequal participation in technology-related education or careers
- Online harassment based on gender
- Lack of representation in some technology-related fields
46. Addressing Gender Issues
Schools and organisations can help by:
- Providing equal opportunities.
- Encouraging all students to learn computer science.
- Avoiding gender stereotypes.
- Providing equal access to digital devices.
- Promoting safe online environments.
- Encouraging participation in technology activities.
- Supporting students according to their interests and abilities.
Important Principle
Technology education should be accessible to everyone regardless of gender.
47. DISABILITY ISSUES IN TECHNOLOGY
People with disabilities may face difficulties when accessing computers, websites or digital services.
Examples
A person may have:
- Visual impairment
- Hearing impairment
- Physical/motor limitations
- Learning difficulties
- Speech-related disabilities
Technology should be designed to reduce unnecessary barriers.
48. ASSISTIVE TECHNOLOGY
Assistive technology refers to devices or software that help people with disabilities use technology and perform tasks more independently.
Examples
Disability/Need Possible Assistive Technology Visual impairment Screen reader Low vision Screen magnification Hearing impairment Captions/subtitles Motor difficulties Alternative input devices Speech difficulties Speech-generating systems Reading difficulties Text-to-speech tools 49. ACCESSIBILITY IN COMPUTER EDUCATION
Teachers should try to make computer education accessible to all students.
Good Practices
- Provide accessible learning materials.
- Use captions for videos.
- Use readable fonts and suitable contrast.
- Provide alternative text for meaningful images.
- Allow assistive technologies.
- Give sufficient time when appropriate.
- Provide alternative methods of interaction.
- Encourage inclusive classroom participation.
50. DIGITAL DIVIDE
The digital divide is the gap between people who have adequate access to digital technology and those who do not.
Factors can include:
- Income
- Location
- Internet availability
- Digital literacy
- Disability
- Availability of devices
Example
If one group of students has high-speed Internet and personal computers while another group has no reliable device or Internet access, there is a digital access gap.
51. RESPONSIBLE DIGITAL CITIZEN
A responsible digital citizen:
RESPONSIBLE DIGITAL CITIZEN | ┌──────────────┼──────────────┐ ↓ ↓ ↓ Privacy Respect Safety ↓ ↓ ↓ Security Ethics Laws ↓ ↓ ↓ IPR Netiquette ResponsibilityMain Responsibilities
- Respect privacy.
- Follow cyber laws.
- Respect intellectual property.
- Communicate politely.
- Protect accounts.
- Avoid cyber bullying.
- Verify information.
- Report harmful activities.
- Dispose of electronic waste properly.
52. IMPORTANT DIFFERENCES
Active vs Passive Digital Footprint
Active Passive Deliberately created/shared by user Collected through online activity Posts and comments Cookies and visit records Emails Some usage/technical data Copyright vs Plagiarism
Copyright Plagiarism Legal protection for original works Presenting another's work as your own Concerned with legal rights Concerned with academic/ethical attribution and may also involve legal issues Example: unauthorised copying of protected content Submitting copied assignment without acknowledgement Phishing vs Hacking
Phishing Hacking Usually involves deception/social engineering Often involves exploiting weaknesses or bypassing controls Attempts to trick users into revealing information or taking unsafe actions May involve unauthorised access Often uses fake emails/websites/messages May target systems, accounts or networks Virus vs Trojan
Virus Trojan Can infect/replicate through host files or programs Disguises itself as legitimate software Replication is a characteristic feature Does not need to replicate like a virus Often spreads through infected files/programs Often relies on tricking users into executing it 53. QUICK REVISION
Digital Footprints
Digital Footprint = Record/trail of online activitiesNetizen
Netizen = Internet + CitizenNetiquette
Netiquette = Good manners and responsible behaviour onlineIPR
IPR = Intellectual Property RightsMain IPR Terms
Copyright → Creative works Patent → Qualifying inventions Trademark → Brand identity/marksCyber Crime
Hacking Eavesdropping Phishing Fraud emails Ransomware Cyber trolling Cyber bullyingMalware
Virus Trojan AdwareCyber Safety
Safe browsing Identity protection ConfidentialityE-Waste
Old/discarded electronic equipmentTechnology and Society
Gender equality Accessibility Inclusion Digital divide Assistive technology54. IMPORTANT EXAM QUESTIONS
Very Short Answer Questions
- What is a digital footprint?
- What is an active digital footprint?
- What is a passive digital footprint?
- What is a digital society?
- Who is a netizen?
- What is netiquette?
- Write any four rules of netiquette.
- What is data protection?
- What is Intellectual Property?
- What is IPR?
- Define copyright.
- What is a patent?
- What is a trademark?
- What is plagiarism?
- What is copyright infringement?
- What is trademark infringement?
- What is open source software?
- What is a software licence?
- What is Creative Commons?
- What is GPL?
- What is Apache License?
- Define cyber crime.
- What is hacking?
- What is eavesdropping?
- What is phishing?
- What is ransomware?
- What is cyber bullying?
- What is malware?
- What is a computer virus?
- What is a Trojan?
- What is adware?
- What is e-waste?
- What is cyber safety?
- What is confidentiality?
- What is identity protection?
- What is the Information Technology Act, 2000?
- What is assistive technology?
- What is the digital divide?
55. SHORT ANSWER QUESTIONS
Q1. Differentiate between active and passive digital footprints.
Answer:
An active digital footprint is deliberately created by a user, such as posting a photograph or writing a comment.
A passive digital footprint is information collected through online activities without the user deliberately posting it, such as certain website visit records or cookies.
Q2. Write four rules of social media etiquette.
Answer:
- Think before posting.
- Respect other users.
- Do not spread false information.
- Do not share private information unnecessarily.
Q3. Differentiate between copyright, patent and trademark.
Answer:
- Copyright protects original creative works.
- Patent protects qualifying inventions.
- Trademark identifies and distinguishes goods or services.
Q4. What is plagiarism? How can it be avoided?
Answer:
Plagiarism is presenting another person's work or ideas as one's own without proper acknowledgement.
It can be avoided by:
- Writing in one's own words.
- Giving credit to sources.
- Using quotations appropriately.
- Providing references where required.
Q5. What is phishing?
Answer:
Phishing is a social-engineering technique in which an attacker attempts to trick a user into revealing sensitive information or performing an unsafe action, often through fake emails, messages or websites.
Q6. Write four precautions against phishing.
Answer:
- Do not click suspicious links.
- Check the sender carefully.
- Never share passwords or OTPs through unsolicited messages.
- Verify requests through an independent trusted channel.
Q7. What is ransomware?
Answer:
Ransomware is malware that can deny access to files or systems, commonly by encrypting files, and then demand payment from the victim.
Q8. What is e-waste? How should it be disposed of?
Answer:
E-waste is discarded electrical and electronic equipment.
It should be:
- Reused where possible.
- Repaired where practical.
- Donated if usable.
- Sent to appropriate authorised collection/recycling channels.
Q9. What is assistive technology?
Answer:
Assistive technology consists of devices or software that help people with disabilities use computers and digital services more effectively.
Examples include screen readers, screen magnifiers and captions.
56. LONG ANSWER QUESTIONS
Q1. Explain digital footprints and their types.
Include:
- Definition
- Active digital footprint
- Passive digital footprint
- Examples
- Importance
- Methods of managing digital footprints
Q2. Explain Intellectual Property Rights.
Include:
- Meaning of intellectual property
- Copyright
- Patent
- Trademark
- Plagiarism
- Copyright infringement
- Trademark infringement
Q3. Explain different types of cyber crime.
Discuss:
- Hacking
- Eavesdropping
- Phishing
- Fraud emails
- Ransomware
- Cyber trolling
- Cyber bullying
Q4. Explain cyber safety measures.
Include:
- Safe web browsing
- Strong passwords
- Multi-factor authentication
- Identity protection
- Confidentiality
- Avoiding suspicious links and attachments
- Software updates
- Backups
Q5. Explain malware and its types.
Explain:
- Virus
- Trojan
- Adware
Also include their effects and prevention methods.
Q6. Explain gender and disability issues in technology.
Include:
- Equal access
- Avoiding gender stereotypes
- Online safety
- Accessibility
- Assistive technology
- Inclusive teaching
- Digital divide
57. IMPORTANT KEYWORDS FOR CBSE EXAM
Keyword Meaning Digital Footprint Trail/record of online activity Netizen Internet user participating in digital society Netiquette Good online manners IPR Intellectual Property Rights Copyright Protection for original creative works Patent Protection for qualifying inventions Trademark Identifying/distinguishing mark Plagiarism Presenting another's work as one's own Phishing Deceptive attempt to obtain information Hacking Unauthorised access/exploitation of systems Eavesdropping Unauthorised monitoring of communication Ransomware Malware that denies access and demands ransom Malware Malicious software Virus Malware that can infect/replicate through host files or programs Trojan Malware disguised as legitimate software Adware Software that displays unwanted advertisements E-Waste Discarded electronic equipment Confidentiality Preventing unauthorised access to information Accessibility Making technology usable by people with different needs Assistive Technology Technology supporting people with disabilities 58. ONE-PAGE REVISION MAP
UNIT 3 SOCIETY, LAW AND ETHICS | ┌─────────────────┼─────────────────┐ ↓ ↓ ↓ DIGITAL SOCIETY DATA CYBER | PROTECTION SAFETY | | | Digital Footprint IPR Safe Browsing Netizen Copyright Identity Netiquette Patent Confidentiality Communication Trademark Social Media Open Source Licensing | ↓ CYBER CRIME | ┌───────────────┼────────────────┐ ↓ ↓ ↓ Hacking Phishing Ransomware Eavesdropping Fraud Emails Cyber Bullying Cyber Trolls | ↓ MALWARE | ┌─────────┼─────────┐ ↓ ↓ ↓ Virus Trojan Adware | ↓ E-WASTE | Reduce / Reuse Repair / Recycle | ↓ IT ACT, 2000 | ↓ TECHNOLOGY & SOCIETY | ┌─────────┴─────────┐ ↓ ↓ Gender Issues Disability Issues | Assistive Technology Accessibility Inclusion59. FINAL EXAM REMEMBER POINTS
- Digital footprint is the trail of information left through digital activities.
- Netizen means a citizen/user of the Internet.
- Netiquette means good manners and responsible behaviour online.
- Copyright protects original creative works.
- Patent protects qualifying inventions.
- Trademark identifies and distinguishes goods or services.
- Plagiarism means presenting someone else's work or ideas as one's own without proper acknowledgement.
- Phishing uses deception to obtain information or cause unsafe actions.
- Ransomware commonly encrypts files and demands payment.
- Cyber bullying involves harassment or intimidation through digital technologies.
- Malware means malicious software.
- Virus, Trojan and adware are examples of malware.
- Confidentiality protects information from unauthorised access.
- E-waste should be handled through proper reuse, collection and recycling channels.
- The Information Technology Act, 2000 is an important Indian law concerning electronic records, electronic transactions and specified cyber activities.
- Technology should promote equality, accessibility and inclusion.
- Assistive technology helps people with disabilities use digital technologies.
- Every user should behave as a responsible digital citizen.
Golden Rule of Digital Citizenship
Use technology safely, legally, ethically and respectfully.
-

RUonTop: Hi Welcome to our Blog...