Chapter 1
Chapter 1
Keyboard
Mouse
Scanner
Touchscreen
Data entered through an input device is temporarily stored in the main
memory (RAM) of the computer system. For permanent storage, data and
instructions are stored in secondary memory.
Monitor
Projector
Headphone
Speaker
Printer
3D printer
⏳ 1.2 Evolution of Computer
The evolution of computing devices from simple calculators to modern data
processors has occurred in a relatively short time span.
Unit Description
KB (Kilobyte) 1 KB = 1024 Bytes
MB (Megabyte) 1 MB = 1024 KB
GB (Gigabyte) 1 GB = 1024 MB
TB (Terabyte) 1 TB = 1024 GB
PB (Petabyte) 1 PB = 1024 TB
EB (Exabyte)1 EB = 1024 PB
ZB (Zettabyte) 1 ZB = 1024 EB
YB (Yottabyte) 1 YB = 1024 ZB
🧠 1.3.2 Types of Memory
Computers have two types of memory:
Primary Memory
Secondary Memory
(A) Primary Memory
Primary memory is essential for a computer system. Programs and data are
loaded into primary memory before processing. The CPU interacts directly with
primary memory to perform read or write operations.
Chip type
Word size
Memory size
Clock speed
(A) Word Size
Word size is the maximum number of bits that a microprocessor can process at
a time.
(D) Cores
A core is a basic computation unit of the CPU. Multicore processors can
execute multiple tasks simultaneously.
Keyboard
Mouse
Washing machine
Digital camera
Pendrive
Remote controller
Microwave
📊 1.6 Data and Information
A computer is primarily for processing data.
Data can be raw and unorganized facts that are processed to get meaningful
information.
Structured Data
Unstructured Data
Semi-structured Data
(A) Structured Data
Structured data follows a strict record structure and is easy to comprehend.
(B) Unstructured Data
Unstructured data is not organized in a pre-defined record format.
Software categories:
System Software
Programming Tools
Application Software
💻 1.7.2 System Software
System software provides the basic functionality to operate a computer by
interacting directly with its constituent hardware.
Operating Systems
System Utilities
Device Drivers
(A) Operating System
An operating system is a system software that operates the computer.
Utility Software
These are programs that aren't part of the operating system but are crucial for
improving system performance. Examples include:
Anti-virus software
Disk cleaner tools
Disk compression software
Device Drivers
The primary role of a device driver is to ensure a device functions correctly.
A device driver acts as an interface between a device and the operating system,
providing the necessary services by abstracting the hardware-level operations.
It mediates between the OS and the attached device.
💻 Programming Tools
Programming Languages
These are languages used to give instructions to computers to process input
data and produce desired outcomes.
Types of Translators:
Text Editor: Software for creating and storing source code files.
Integrated Development Environment (IDE): Combines a text editor, building
tools, and a debugger. Examples include Python IDLE, Netbeans, Eclipse, Atom,
Lazarus.
Debugger: Software to detect and correct errors in source code.
🚀 Application Software
General Purpose Software
These applications are designed for generic use by a broad audience. Examples:
Websites
School management software
Accounting software
Proprietary or Free and Open Source Software
Free and Open Source Software (FOSS)
Software with freely available source code, allowing public development and
improvement. Examples:
Ubuntu
Python
LibreOffice
OpenOffice
Mozilla Firefox
Freeware
Software that is freely available but may not have accessible source code.
Examples:
Skype
Adobe Reader
Proprietary Software
Software that must be purchased from the vendor, who retains the copyright.
Examples:
Microsoft Windows
Tally
Quickheal
⚙️Operating System (OS)
An operating system (OS) is a resource manager that manages all computer
resources, including hardware (CPU, RAM, Disk, Network, I/O devices),
application software, and device drivers.
Primary Objectives:
Provide services for building and running application programs.
Provide a user interface for interaction with the computer.
OS User Interface
Different types of user interfaces provide varying functionalities.
Memory Management
Manages the main memory by allocating and freeing memory for running
processes dynamically.
It concerns with management of main memory so that maximum memory is
occupied or utilised by large number of processes while keeping track of each
and every location within the memory as free or occupied.
File Management
Involves the creation, updating, deletion, and protection of files in secondary
storage. Includes mechanisms to prevent unauthorized access.
Device Management
Manages heterogeneous I/O devices and hardware connected to the system.
Includes device driver interaction and security measures.
The operating system interacts with the device driver and the related software
for a particular device.
Encoding Schemes
Introduction
We owe a lot to the Indians, who taught us how to count. Without it, no
worthwhile scientific discovery could have been made.
Have you ever wondered how the keys on a computer keyboard are interpreted
by the computer system? This section will briefly discuss text interpretation by
the computer. Computers only understand binary language (0s and 1s).
Therefore, when a key is pressed, it's mapped to a unique code, which is then
converted to binary.
💡 What is Encoding?
The mechanism of converting data into an equivalent cipher using a specific
code.
Why is code value 65 used for "A" and not another value? Is it the same for all
keyboards?
Yes, it is the same for all keyboards due to standard encoding schemes, where
each letter, numeral, and symbol is encoded or assigned a unique code.
Example: Encode the word "DATA" and convert the encoded value into binary
values:
🌐 UNICODE
Many encoding schemes exist for different languages, but they couldn't
communicate with each other. Therefore, UNICODE was developed to
incorporate all characters of every written language. UNICODE provides a
unique number for every character, irrespective of device, operating system, or
software application. Commonly used UNICODE encodings are UTF-8, UTF-16,
and UTF-32. It is a superset of ASCII, and the values 0-128 have the same
characters as in ASCII.
🔢 Number Systems
Every key of the keyboard is internally mapped to an ASCII code following an
encoding scheme. This encoded value is further converted to its equivalent
binary representation so that the computer can understand it. A number
system is a method to represent (write) numbers.
Every number system has a set of unique characters or literals. The count of
these literals is called the radix or base of the number system.
Each symbol in a number has a positional value, computed using its position
value and the base value of the number system.
Decimal Binary
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
🎱 Octal Number System
With the increase in the value of a decimal number, the number of bits in its
binary representation also increases. Sometimes, a binary number is so large
that it becomes difficult to manage. The octal number system was devised for
compact representation of binary numbers. The octal number system is called
the base-8 system as it has a total of eight digits (0-7). Three binary digits (
8
=
2
3
8=2
3
) are sufficient to represent any octal digit.
2
∣
65
Remainder
1
2∣65 Remainder 1
2
∣
32
Remainder
0
2∣32 Remainder 0
2
∣
16
Remainder
0
2∣16 Remainder 0
2
∣
8
Remainder
0
2∣8 Remainder 0
2
∣
4
Remainder
0
2∣4 Remainder 0
2
∣
2
Remainder
0
2∣2 Remainder 0
2
∣
1
Remainder
0
2∣1 Remainder 0
2
∣
0
Remainder
1
2∣0 Remainder 1
(
65
)
10
=
(
1000001
)
2
(65)
10
=(1000001)
2
8
∣
65
Remainder
1
8∣65 Remainder 1
8
∣
8
Remainder
0
8∣8 Remainder 0
8
∣
1
Remainder
1
8∣1 Remainder 1
8
∣
0
Remainder
1
8∣0 Remainder 1
(
65
)
10
=
(
101
)
8
(65)
10
=(101)
8
16
∣
65
Remainder
1
16∣65 Remainder 1
16
∣
4
Remainder
4
16∣4 Remainder 4
16
∣
0
Remainder
4
16∣0 Remainder 4
(
65
)
10
=
(
41
)
16
(65)
10
=(41)
16
1
∗
2
3
+
1
∗
2
2
+
0
∗
2
1
+
1
∗
2
0
=
8
+
4
+
0
+
1
=
(
13
)
10
1∗2
3
+1∗2
2
+0∗2
1
+1∗2
0
=8+4+0+1=(13)
10
2
∗
8
2
+
5
∗
8
1
+
7
∗
8
0
=
128
+
40
+
7
=
(
175
)
10
2∗8
2
+5∗8
1
+7∗8
0
=128+40+7=(175)
10
3
∗
1
6
2
+
10
∗
1
6
1
+
5
∗
1
6
0
=
768
+
160
+
5
=
(
933
)
10
3∗16
2
+10∗16
1
+5∗16
0
=768+160+5=(933)
10
to octal number.
Make group of 3-bits of the given binary number (right to left) = 010 101 100
Therefore,
(
10101100
)
2
=
(
254
)
8
(10101100)
2
=(254)
8
Octal Number to Binary Number
Example: Convert
(
705
)
8
(705)
8
to binary number.
Octal digits = 7 0 5
Write 3-bits binary value for each digit = 111 000 101
Therefore,
(
705
)
8
=
(
111000101
)
2
(705)
8
=(111000101)
2
to hexadecimal number.
Make group of 4-bits of the given binary number (right to left) = 0001 1010
1100
Therefore,
(
0110101100
)
2
=
(
1
A
C
)
16
(0110101100)
2
=(1AC)
16
to binary number.
Hexadecimal digits = 2 3 D
Write 4-bit binary value for each digit = 0010 0011 1101
Therefore,
(
23
D
)
16
=
(
001000111101
)
2
(23D)
16
=(001000111101)
2
Conversion of a Number with Fractional Part
Decimal Number with Fractional Part to another Number System
To convert the fractional part of a decimal number to another number system
with base value b, repeatedly multiply the fractional part by the base value b
until the fractional part becomes 0. Use integer part from top to bottom to get
equivalent number in that number system. If the fractional part does not
become 0 in successive multiplication, then stop after a certain number of
multiplications.
Example: Convert
(
0.25
)
10
(0.25)
10
to binary.
0.25
∗
2
=
0.50
Integer part
0
0.25∗2=0.50 Integer part 0
0.50
∗
2
=
1.00
Integer part
1
0.50∗2=1.00 Integer part 1
Since the fractional part is 0, the multiplication is stopped. Write the integer
part from top to bottom to get binary number for the fractional part.
Therefore,
(
0.25
)
10
=
(
0.01
)
2
(0.25)
10
=(0.01)
2
Example: Convert
(
100101.101
)
2
(100101.101)
2
into decimal.
1
∗
2
5
+
0
∗
2
4
+
0
∗
2
3
+
1
∗
2
2
+
0
∗
2
1
+
1
∗
2
0
+
1
∗
2
−
1
+
0
∗
2
−
2
+
1
∗
2
−
3
=
32
+
0
+
0
+
4
+
0
+
1
+
0.5
+
0
+
0.125
=
37.625
1∗2
5
+0∗2
4
+0∗2
3
+1∗2
2
+0∗2
1
+1∗2
0
+1∗2
−1
+0∗2
−2
+1∗2
−3
=32+0+0+4+0+1+0.5+0+0.125=37.625
Therefore,
(
100101.101
)
2
=
(
37.625
)
10
(100101.101)
2
=(37.625)
10
Example: Convert
(
10101100.01011
)
2
(10101100.01011)
2
to octal number.
Therefore,
(
10101100.01011
)
2
=
(
254.26
)
8
(10101100.01011)
2
=(254.26)
8
Chapter 3: Emerging Trends
💡 Introduction
Computer science is continuously evolving with new technologies and
initiatives emerging frequently. Emerging trends are state-of-the-art
technologies that gain popularity and set new standards in the digital world.
This chapter will explore some of these trends that are poised to significantly
impact the digital economy and interactions in digital societies.
🧠 Artificial Intelligence (AI)
Artificial Intelligence (AI) seeks to replicate human intelligence in machines,
enabling them to perform tasks intelligently. Intelligent machines aim to mimic
cognitive functions such as learning, decision-making, and problem-solving
with minimal human intervention.
AI systems are programmed to create a knowledge base and make decisions
based on it, learning from past experiences to inform future choices.
🤖 Machine Learning
Machine Learning (ML) is a subset of AI where computers learn from data
using statistical techniques without explicit programming.
ML algorithms, known as models, are trained and tested using training
and testing data.
After training, these models predict outcomes for new, unknown data
with acceptable accuracy.
Natural Language Processing (NLP)
Natural Language Processing (NLP) focuses on the interaction between
humans and computers using natural languages.
Examples include predictive typing in search engines and spell-checking
features.
NLP enables voice-based interaction, text-to-speech, and speech-to-text
conversions.
Machine translation and automated customer service are rapidly
emerging fields utilizing NLP.
👓 Immersive Experiences
Immersive experiences use technology to stimulate our senses, making
interactions more realistic and engaging.
These experiences enhance visualization, feeling, and reaction.
Applications include training simulators (e.g., driving and flight
simulators).
Virtual Reality (VR)
Virtual Reality (VR) is a three-dimensional, computer-generated environment
that simulates the real world.
Users can interact with and explore VR environments, often using VR headsets.
VR promotes sensory information like sound, smell, motion, and
temperature to enhance realism.
Applications: gaming, military training, medical procedures,
entertainment, social science, psychology, and engineering.
📍 Augmented Reality (AR)
Augmented Reality (AR) superimposes computer-generated information onto
the physical world.
AR enhances the perception of the real world through additional digital
information.
Users can access real-time information about nearby places or historical
sites via location-based AR apps.
⚙️Robotics
Robotics is an interdisciplinary field involving the design, fabrication, operation,
and application of robots.
A robot is a machine capable of automatically performing tasks with accuracy
and precision, programmable via computer instructions.
Robots often perform repetitive, stressful, or labor-intensive tasks.
Sensors are key components of robots.
Types of robots: wheeled robots, legged robots, manipulators, and
humanoids.
Applications: industries, medical science, bionics, scientific research, and
military.
Examples include:
Robot Description
Sophia A humanoid robot that uses AI, visual data processing, and facial reco
Drones are used in various fields such as journalism, filming, shipping, disaster
management, healthcare, and law enforcement.
Big Data
Big Data refers to extremely large and complex datasets that are difficult to
process using traditional data processing tools.
Arises from the colossal rate at which data is produced, driven by increasing
Internet users and IoT evolution.
Big Data presents challenges in integration, storage, analysis, searching,
processing, transfer, querying, and visualization.
🔑 Characteristics of Big Data
Big data is distinguished from traditional data by five key characteristics:
Characteristic Description
Volume Enormous size, making it difficult to process with traditional database management systems (DBMS).
Variety The varied nature of data, including structured, semi-structured, and unstructured types (e.g., text, images, videos).
Veracity The trustworthiness of the data, addressing issues like inconsistency, bias, and noise.
Characteristic Description
Value The potential for hidden patterns and useful knowledge that can provide high business value.
📊 Data Analytics
Data analytics is the process of examining datasets to draw conclusions about
the information they contain, often using specialized systems and software.
Used in commercial industries to enable more informed business
decisions.
In science and technology, it helps researchers verify or disprove
scientific models and theories.
Pandas, a Python library, simplifies data analysis.
🌐 Internet of Things (IoT)
Internet of Things (IoT) is a network of devices with embedded hardware and
software that can communicate and exchange data with other devices on the
same network.
Connects everyday devices, allowing them to work collaboratively and
intelligently.
Enables remote access and control of devices via computers or
smartphones.
Web of Things (WoT)
Web of Things (WoT) aims to integrate physical objects with web services for
efficient communication.
Allows the use of web services to connect anything in the physical world,
enabling smart homes, smart offices, and smart cities.
Sensors
Sensors are used as monitoring and observing elements in real-world
applications.
A smart sensor takes input from the physical environment and uses built-in
computing resources to perform predefined functions upon detection of specific
input.
Examples: Accelerometers and gyroscopes in mobile phones that detect
orientation and track rotation.
Smart Cities
Smart cities use computer and communication technology along with IoT to
manage and distribute resources efficiently.
Integrates various city services to optimize efficiency and sustainability.
Examples: smart buildings, smart bridges, and smart tunnels use sensors to
detect issues and alert authorities.
☁️Cloud Computing
Cloud computing delivers computer-based services over the Internet,
accessible from anywhere using any device.
Services include software, hardware (servers), databases, and storage, typically
charged on a pay-per-use basis.
Enables users to run large applications or process large amounts of data
without needing local storage or processing power.
Offers cost-effective, on-demand resources.
☁️Cloud Services
Cloud services are categorized into three standard models:
Service Model Description
Platform as a Service Offers a platform or environment to develop, test, and deliver soft
(PaaS) infrastructure. Simplifies deployment and reduces the complexity
🌐 Grid Computing
Grid computing is a computer network of geographically dispersed and
heterogeneous computational resources.
Creates a virtual supercomputer with enormous processing power and storage.
Nodes (constituent resources) temporarily combine to solve a single
large task.
Grids can be data grids (managing large distributed data) or
CPU/processor grids (distributing processing tasks).
Differs from IaaS cloud service in that grid computing involves multiple
computing nodes joining together to solve a common problem, rather than
renting infrastructure from a service provider.
Blockchains
Blockchain is a decentralized and shared database where each computer has a
copy of the database.
Allows a group of connected computers to maintain a single updated and
secure ledger.
Each block contains data and a header visible to all nodes.
Transactions are authenticated by all nodes in the network.
Ensures safety and security as all members keep a copy of the
blockchain, preventing single-member alterations.
Commonly used in digital currency and seen as a way to ensure transparency,
accountability, and efficiency in business and governance systems.
⌨️Pseudocode
Pseudocode is a non-formal language that helps programmers write
algorithms.
It is a detailed description of instructions that a computer must follow in
a particular order.
Intended for human reading and cannot be executed directly by the
computer.
No specific standard exists.
Frequently Used Keywords
INPUT
COMPUTE
PRINT
INCREMENT
DECREMENT
IF/ELSE
WHILE
TRUE/FALSE
Benefits of Pseudocode
Helps in representing the basic functionality of the intended program
before coding.
Safeguards against leaving out important steps.
Helps non-programmers review the steps to confirm the proposed
implementation.
🔄 Flow of Control
Sequence
Statements are executed one after another.
Algorithms execute steps in a sequential order.
Selection
Involves decision-making based on certain conditions.
Conditionals are used to check possibilities.
The program checks conditions and performs operations based on true
or false values.
Conditionals
If <condition> then
steps to be taken when the condition is true/fulfilled
True/False Conditionals
If <condition> is true then
steps to be taken when the condition is true/fulfilled
otherwise
steps to be taken when the condition is false/not fulfilled
Repetition
Also known as iteration or loop.
Involves executing program statements repeatedly until a condition is
satisfied.
A counter keeps track of the number of times the loop has been
repeated.
The WHILE construct is used when the number of repetitions is
unknown.
✅ Verifying Algorithms
Importance of Verification
Ensures that the functioning of all components are defined correctly.
Helps identify incorrect steps and missing details.
Involves taking different input values and going through all steps.
A dry run is used to simulate the algorithm.
⚖️Comparison of Algorithms
Efficiency Considerations
Different algorithms can solve the same problem, but some are more
efficient.
Efficiency is determined by processing time and the number of
calculations required.## Algorithm Efficiency and Complexity
Prime Number Algorithm Analysis
Different algorithms can solve the same problem with varying efficiency.
Consider the example of determining if a number is prime. The lecture
references four algorithms for this, with increasing efficiency:
1. Divisibility Check Up to Half the Number: This method checks for
divisibility up to half of the given number.
2. Divisibility Check Up to the Square Root of the Number: This is more
efficient as it only checks up to the square root.
3. Divisibility Check Using Prime Numbers: This algorithm uses only prime
numbers smaller than the given number for divisibility checks. While it
may involve fewer calculations, it requires storing a list of prime
numbers, thus using more memory.
Time and Space Complexity ⏳
Algorithms are compared based on:
Time Complexity: The amount of processing time needed to run.
Space Complexity: The amount of memory required to execute.
The choice of algorithm depends on the efficiency concerning time and space
complexity.
Coding 💻
High-Level vs. Low-Level Languages
Machine Language (Low-Level): Consists of 0s and 1s. Directly
understood by computer hardware but difficult for humans.
High-Level Languages: Closer to natural languages (e.g., FORTRAN, C, C+
+, Java, Python). Easier to read, write, and maintain, but require
translation.
Syntax
Syntax is the set of rules or grammar that governs the formulation of
statements in a language, such as spellings, order of words, punctuation, etc.
Source Code and Translation
A program written in a high-level language is called source code. It must be
translated into machine language using a compiler or an interpreter for the
computer to understand it.
Factors Influencing Language Choice
Platform (OS): Where the program will run.
Application Type: Desktop, mobile, or web application.
Target System: General-purpose computer or embedded systems.
Decomposition 🧩
Breaking Down Complex Problems
The basic idea of solving a complex problem by decomposition is to break it
down into smaller, more manageable sub-problems.
"Decompose a complex problem into simpler problems get ones thinking
straight in these simpler problems, put these analyses together with logical
glue" -- Howard Raffa
Railway Reservation System Example
A complex system like a railway reservation system can be broken down into
components:
Trains' information
Reservation information
Information about days, timings, booking status
Staff, security, stations, classes, and available/waiting lists
Railway births cancellation and refund infrastructure
Other details such as food and billing services
Advantages of Decomposition
Each sub-problem can be examined in detail.
Sub-problems can be solved independently.
Different teams can work on different sub-problems based on their
expertise.
Examples of Problems Solvable by Decomposition
Mathematics and science problems
Events management in school
Weather forecasting
Delivery management systems
Integration and Testing
After solving individual sub-problems, it is necessary to test them for
correctness and integrate them to achieve a complete solution.
Chapter 5: Getting Started with Python
5.1 Introduction to Python 🐍
A program is an ordered set of instructions executed by a computer to carry out
a specific task, and the language used to specify these instructions is
a programming language.
Computers understand machine language (0s and 1s), which is a low-
level language.
Humans use high-level programming languages like Python, C++, Visual
Basic, PHP, and Java.
Source code is a program written in a high-level language.
Interpreters and compilers translate source code into machine language.
Python uses an interpreter.
An interpreter translates and executes statements one by one.
A compiler translates the entire source code into object code at
once and generates error messages after scanning the whole
program.
5.1.1 Features of Python ✨
High-level language
Free and open-source
Interpreted language
Easy to understand (simple syntax)
Case-sensitive (NUMBER and number are different)
Portable and platform-independent
Rich library of predefined functions
Helpful in web development
Uses indentation for blocks and nested blocks
5.1.2 Working with Python 💻
Python interpreter (or shell) is needed to execute Python programs.
The >>> symbol is the Python prompt, indicating the interpreter is ready
for instructions.
5.1.3 Execution Modes ⚙️
Interactive Mode: Executes individual statements instantaneously.
Script Mode: Allows writing multiple instructions in a file (Python source
code file) with a .py extension.
(A) Interactive Mode
Type Python statements directly at the >>> prompt and press Enter to
execute.
Convenient for testing single lines of code.
Statements cannot be saved for future use.
(B) Script Mode
Write a Python program in a file and save it with a .py extension.
Execute the script by:
Typing the file name with the path at the prompt.
Opening the program directly from IDLE.
Clicking [Run]->[Run Module] in IDLE after saving the file.
5.2 Python Keywords 🔑
Keywords are reserved words with specific meanings to the Python
interpreter.
Must be written exactly as given because Python is case-sensitive.
Table of Python keywords:
Keyword Keyword Keyword
as elif if
break except in
5.3 Identifiers
Identifiers are names used to identify variables, functions, or other entities in a
program.
Rules for naming identifiers:
Begin with an uppercase or lowercase alphabet or an
underscore _.
Followed by any combination of characters a-z, A-Z, 0-9, or _.
Cannot start with a digit.
Should not be a keyword.
Cannot contain special symbols like !, @, #, $, %, etc.
Keep it short and meaningful.
Example:
avg = (marks1 + marks2 + marks3)/3
area = length * breadth
5.4 Variables 📦
A variable is uniquely identified by a name (identifier) and refers to an object
stored in memory.
Value can be a string, numeric, or alphanumeric.
Use an assignment statement to create new variables and assign values.
Variable declaration is implicit in Python.
Variables must be assigned values before use.
message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)
length = 10
breadth = 20
area = length * breadth
print(area)
5.5 Comments 💬
Comments are used to add remarks or notes in the source code for explanation
and documentation.
Comments are ignored by the interpreter.
Start with # (hash sign).
# Variable amount is the total spending on grocery
amount = 3400
# totalMarks is sum of marks in all the tests of Mathematics
totalMarks = test1 + test2 + finalTest
# Program to find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)
5.6 Everything Is an Object 💡
Python treats every value or data item as an object.
Each object has a unique identity (ID), akin to its memory address.
The id() function returns the identity of an object.
num1 = 20
print(id(num1))
num2 = 30 - 10
print(id(num2)) # identity of num2 and num1 are same as both refers to object
20
5.7 Data Types
A data type identifies the type of data values a variable can hold and the
operations that can be performed on that data.
Common data types:
Number (int, float, complex)
Sequence (String, List, Tuple)
Set
None
Mapping (Dictionary)
5.7.1 Number
Stores numerical values.
Types:
Type/Class Description
num1 = 10
print(type(num1))
num2 = -1210
print(type(num2))
var1 = True
print(type(var1))
float1 = -1921.9
print(type(float1))
float2 = -9.8*10**2
print(float2, type(float2))
var2 = -3+7.2j
print(var2, type(var2))
5.7.2 Sequence
An ordered collection of items, each indexed by an integer.
Types:
String
List
Tuple
(A) String
A group of characters enclosed in single or double quotes.
str1 = 'Hello Friend'
str2 = "452"
(B) List
A sequence of items separated by commas and enclosed in square brackets [].
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1)
(C) Tuple
A sequence of items separated by commas and enclosed in parentheses ().
Cannot be changed once created.
tuple1 = (10, 20, "Apple", 3.4, 'a')
print(tuple1)
5.7.3 Set
An unordered collection of unique items separated by commas and enclosed in
curly brackets {}.
set1 = {10,20,3.14,"New Delhi"}
print(type(set1))
print(set1)
set2 = {1,2,1,3}
print(set2) # duplicate elements are not included in set
5.7.4 None
A special data type with a single value, signifying the absence of a value.
myVar = None
print(type(myVar))
print(myVar)
5.7.5 Mapping
An unordered data type; currently only the dictionary.
(A) Dictionary
Holds data items in key-value pairs enclosed in curly brackets {}.
Keys are separated from values using a colon :.
dict1 = {'Fruit':'Apple','Climate':'Cold', 'Price(kg)':120}
print(dict1)
print(dict1['Price(kg)'])
5.7.6 Mutable and Immutable Data Types 🔄
Mutable: Values can be changed after creation (e.g., Lists, Dictionaries,
Sets).
Immutable: Values cannot be changed after creation (e.g., Numbers,
Strings, Tuples).
5.7.7 Deciding Usage of Python Data Types 🤔
Lists: Use when you need a simple, iterable collection that requires
frequent modifications.
Tuples: Use when data should not be changed.
Sets: Use when uniqueness of elements is required.
Dictionaries: Use when data is constantly modified, requires fast lookup
based on a custom key, or needs a logical association between key-value
pairs.
5.8 Operators 🧮
An operator performs specific mathematical or logical operations on values
(operands).
5.8.1 Arithmetic Operators
Operator Operation Description
is Evaluates True if the variables on either side point towards the same memor
is not Evaluates True if the variables on either side do not point to the same memo
5.9 Expressions 📝
A combination of constants, variables, and operators that always evaluates to
a value.
Examples:
100
num
num + 20.4
3.0 + 3.14
23 / 3 - 5 * 7
"Global" + "Citizen"
5.9.1 Precedence of Operators
Higher precedence operators are evaluated before lower precedence
operators.
Table of operator precedence (highest to lowest):
Order of Precedence Operators
1 **
2 ~, +, -
Order of Precedence Operators
3 *, /, %, //
4 +, -
7 is, is not
8 in, not in
9 not
10 and
11 or
**Example:**
## 📜 Statements
> In Python, a **statement** is a unit of code that the Python interpreter can
execute.
**Examples:**
* Assignment statement:
```
x=4
cube = x ** 3
```
* Print statement:
```
print (x, cube)
```
Programs often need to interact with users to get input and provide output.
### Input
**Example:**
fname = input("Enter your first name: ") # Prompts user to enter their first
name age = input("Enter your age: ") # Prompts user to enter their age
print(type(age)) # <class 'str'>
In the example above, even if the user enters a number for age, it's treated as a
string. To treat it as a number, you must convert the string to the appropriate
numeric type, for example, using `int()`.
**Example:**
### Output
* The `print()` function is used to output data to the standard output device
(the screen).
* It evaluates the expression before displaying it.
* **Syntax:** `print(value [, ..., sep = ' ', end = '\n'])`
* `sep`: Optional separator between the output values (default is space).
* `end`: Optional string to be appended after the last value (default is a new
line).
**Examples:**
| Statement | Output |
| :--------------------------------- | :-------------------- |
| `print("Hello")` | `Hello` |
| `print(10*2.5)` | `25.0` |
| `print("I" + "love" + "my" + "country")` | `Ilovemycountry` |
| `print("I'm", 16, "years old")` | `I'm 16 years old` |
* Using `+` concatenates strings, while using `,` passes multiple arguments to
the `print` function, which can handle different data types.
## 🔄 Type Conversion
Sometimes, you need to convert a variable's data type. This can be done
explicitly (by the programmer) or implicitly (by Python).
**Example:**
| Function | Description |
| :--------- | :--------------------------------- |
| `int(x)` | Converts `x` to an integer |
| `float(x)` | Converts `x` to a floating-point number |
| `str(x)` | Converts `x` to a string |
| `chr(x)` | Converts ASCII value `x` to character |
| `ord(x)` | Returns the ASCII code of character `x` |
**Examples:**
```python
# Explicit type conversion from int to float
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3) # Output: 30
print(type(num3)) # Output: <class 'int'>
# String concatenation
price = icecream + brownie
print("Total Price Rs." + price) # Output: Total Price Rs.2545
tuple3 = ('Red','Green','Blue')
tuple4 = ('Cyan', 'Magenta', 'Yellow','Black')
tuple5 = tuple3 + tuple4
print(tuple5) # ('Red', 'Green', 'Blue', 'Cyan', 'Magenta', 'Yellow', 'Black')
Concatenation can extend an existing tuple, creating a new tuple.
tuple6 = (1,2,3,4,5)
tuple6 = tuple6 + (6,)
print(tuple6) # (1, 2, 3, 4, 5, 6)
tuple2 = ("Hello",)
tuple2 * 4 # ('Hello', 'Hello', 'Hello', 'Hello')
Membership
The in operator checks if an element is present in the tuple and
returns True or False.
tuple1 = ('Red','Green','Blue')
'Green' in tuple1 # True
'Green' not in tuple1 # False
Slicing
Slicing can be applied to tuples, similar to strings and lists.
tuple1 = (10,20,30,40,50,60,70,80)
tuple1[2:7] # (30, 40, 50, 60, 70)
tuple1[0:len(tuple1)] # (10, 20, 30, 40, 50, 60, 70, 80)
tuple1[:5] # (10, 20, 30, 40, 50)
tuple1[2:] # (30, 40, 50, 60, 70, 80)
tuple1[0:len(tuple1):2] # (10, 30, 50, 70)
tuple1[-6:-4] # (30, 40)
tuple1[::-1] # (80, 70, 60, 50, 40, 30, 20, 10)
⚙️Tuple Methods and Built-In Functions
Python provides several built-in functions and methods to work with tuples:
Method Description Example
Returns a new sorted list from the elements python tuple1 = ("Rama","Heena",
sorted() of the tuple. 'Heena', 'Mohsin', 'Raj', 'Rama']
min() Returns the smallest element of the tuple. python tuple1 = (19,12,56,18,9,87,
max() Returns the largest element of the tuple. python tuple1 = (19,12,56,18,9,87,
🔀 Tuple Assignment
Tuple assignment allows assigning values from a tuple on the right side of the
assignment operator to a tuple of variables on the left side. The number of
variables must match the number of elements in the tuple.
(num1,num2) = (10,20)
print(num1) # 10
print(num2) # 20
record = ( "Pooja",40,"CS")
(name,rollNo,subject) = record
print(name) # Pooja
print(rollNo) # 40
print(subject) # CS
If there is an expression on the right side, it is evaluated first.
(num3,num4) = (10+5,20+5)
print(num3) # 15
print(num4) # 25
🪆 Nested Tuples
A tuple inside another tuple is called a nested tuple.
st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])
Output:
S_No Roll_No Name Marks
1 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79
⚙️Tuple Handling
Here are some programs that demonstrate tuple handling:
1. Swapping two numbers without a temporary variable:
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("\nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("\nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)
2. Compute area and circumference of a circle using a function:
def circle(r):
area = 3.14*r*r
circumference = 2*3.14*r
return (area,circumference)