0% found this document useful (0 votes)
7 views94 pages

Chapter 1

The document provides an overview of computer systems, detailing components such as the CPU, memory types, input/output devices, and the evolution of computing technology. It explains the significance of software, including system software and programming tools, and discusses data types, encoding schemes, and the role of operating systems. Key concepts like microprocessors, data management, and various software categories are also highlighted.

Uploaded by

pragun27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views94 pages

Chapter 1

The document provides an overview of computer systems, detailing components such as the CPU, memory types, input/output devices, and the evolution of computing technology. It explains the significance of software, including system software and programming tools, and discusses data types, encoding schemes, and the role of operating systems. Key concepts like microprocessors, data management, and various software categories are also highlighted.

Uploaded by

pragun27
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Chapter 1: Computer System

1.1 Introduction to Computer System


A computer is an electronic device that can be programmed to accept data
(input), process it, and generate a result (output). A computer, along with
additional hardware and software, is called a computer system.

A computer system primarily comprises:

A Central Processing Unit (CPU)


Memory
Input/Output Devices
Storage Devices
These components function together to deliver the desired output and come in
various forms and sizes, from high-end servers to smartphones.

🧠 1.1.1 Central Processing Unit (CPU)


The CPU is the electronic circuitry that carries out the actual processing and is
often referred to as the "brain" of the computer. It is commonly called the
processor.

Physically, a CPU can be placed on one or more microchips called integrated


circuits (ICs), which comprise semiconductor materials.
The CPU fetches programs and data from memory, performs arithmetic and
logic operations as per the given instructions, and stores the result back to
memory.
While processing, the CPU stores data and instructions in its local memory
called registers.
Registers are part of the CPU chip and are limited in size and number.
The CPU has two main components:
Arithmetic Logic Unit (ALU): Performs all arithmetic and logic operations.
Control Unit (CU): Controls sequential instruction execution, interprets
instructions, and guides data flow.
The CPU is also known as a microprocessor.

⌨️1.1.2 Input Devices


Input devices are devices through which control signals are sent to a computer.
They convert input data into a digital form that is acceptable by the computer
system.

Examples of input devices:

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.

1.1.3 Output Devices


An output device receives data from a computer system for display or physical
production. It converts digital information into human-understandable form.

Examples of output devices:

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.

Key milestones in computing technology:

Year Device/Concept Inventor/Contributor Description


500 BC Abacus Unknown A mechanical device capable of doing
simple arithmetic calculations.
1642 Pascaline Blaise PascalA mechanical calculator capable of addition
and subtraction.
1834 Analytical Engine Charles Babbage A mechanical computing device for
inputting, processing, storing, and displaying output, considered the basis of
modern computers.
1890 Tabulating Machine Herman Hollerith A machine for summarizing
data stored on punched cards, a step towards programming.
1937 Turing Machine Alan Turing A general-purpose programmable
machine capable of solving any problem by executing a program stored on
punched cards.
1945 EDVAC/ENIAC John Von Neumann Introduced the concept of a
stored program computer, capable of storing data and programs in memory.
1947 Transistor Bell Labs Replaced vacuum tubes, using semiconductor
materials.
1970 Integrated Circuit (IC) Unknown A silicon chip containing an entire
electronic circuit on a small area, drastically reducing the size of computers.
1981 IBM PC IBM First personal computer for home use.
1984 Macintosh Apple Apple introduced its Macintosh machines
Von Neumann Architecture
The Von Neumann architecture consists of:

A Central Processing Unit (CPU) for processing arithmetic and logical


instructions.
Memory to store data and programs.
Input and output devices.
Communication channels to send or receive data.
Moore's Law
Moore's Law predicted that the number of transistors on a chip would double
approximately every two years.

💾 1.3 Computer Memory


A computer system needs memory to store data and instructions for
processing.

📏 1.3.1 Units of Memory


A bit is a binary digit (0 or 1) and is the basic unit of memory.
A nibble is a 4-bit word.
A byte is an 8-bit word (two nibbles).
Measurement units for digital data:

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.

Primary memory is of two types:

Random Access Memory (RAM): Volatile memory used to store data


temporarily while the computer is working.
Read Only Memory (ROM): Non-volatile memory used for permanent storage
of contents that are rarely changed, such as the startup program (boot loader).
(B) Cache Memory
Cache memory is a high-speed memory placed between the CPU and the
primary memory. It stores copies of frequently accessed data from primary
memory locations, reducing the average time required to access data.

(C) Secondary Memory


Secondary memory is non-volatile memory with larger storage capacity than
primary memory. It is used to permanently store data or instructions for future
use.

Examples of secondary memory devices:

Hard Disk Drive (HDD)


CD/DVD
Memory Card
Solid State Drive (SSD)
↔️1.4 Data Transfer Between Memory and CPU
Data needs to be transferred between the CPU and primary memory and
between primary and secondary memory.

Data is transferred using physical wires called buses.


Types of buses:
Data bus: Transfers data between components.
Address bus: Transfers addresses between CPU and main memory.
Control bus: Communicates control signals between components.
Collectively, these three buses make the system bus.
⚙️1.5 Microprocessors
A microprocessor is a processor (CPU) implemented on a single microchip.

Microprocessors have evolved over time with increased processing capability,


decreasing physical size, and reduced cost.

🔢 1.5.1 Microprocessor Specifications


Microprocessors are classified based on features such as:

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.

(B) Memory Size


The size of RAM varies depending on the word size.

(C) Clock Speed


Clock speed is the number of pulses generated per second by the clock inside a
computer. It indicates the speed at which the computer can execute
instructions.

(D) Cores
A core is a basic computation unit of the CPU. Multicore processors can
execute multiple tasks simultaneously.

Dual-core: Two cores


Quad-core: Four cores
Octa-core: Eight cores
💾 1.5.2 Microcontrollers
A microcontroller is a small computing device with a CPU, a fixed amount of
RAM, ROM, and other peripherals embedded on a single chip.
Examples of microcontrollers:

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.

📑 1.6.1 Data and Its Types


Data can be input in various forms, but internally, everything is stored in binary
form (0 and 1).

Three types of data:

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.

(C) Semi-structured Data


Semi-structured data has no well-defined structure but maintains internal tags
or markings to separate data elements.

📦 1.6.2 Data Capturing, Storage, and Retrieval


Data Capturing: Gathering data from different sources in digital form.
Data Storage: Storing captured data for processing later.
Data Retrieval: Fetching data from storage devices for processing.
1.6.3 Data Deletion and Recovery
Data Deletion: Involves changing the details of data at the bit level.
Data Recovery: Retrieving deleted, corrupted, and lost data from secondary
storage devices.
⚙️1.7 Software
Software comprises the instructions and data to be processed using computer
hardware. It makes the computer hardware useful and operational.

💡 1.7.1 Need for Software


Software acts as an interface between human users and hardware.

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.

Examples of system software:

Operating Systems
System Utilities
Device Drivers
(A) Operating System
An operating system is a system software that operates the computer.

(B) System Utilities


System utilities are software used for maintenance and configuration of the
computer system.## System Software Enhancements

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.

Classification of Programming Languages


Low-Level Languages: Machine-dependent languages.
Machine Language: Uses 1s and 0s, directly understood by computers. Difficult
to code and debug.
Assembly Language: Uses English-like words and symbols, simplifying coding.
Code is specific to the computer.
High-Level Languages: Machine-independent and easier to write, using English-
like sentences. Requires translators. Examples: C++, Java, Python.
Language Translators
Because computers understand only machine language, translators are needed
to convert assembly or high-level languages into machine code.

Source Code is the program code written in assembly or a high-level language.


It is converted into Object (Machine) Code, which the computer can
understand.

Types of Translators:

Assembler: Converts assembly language code to machine language. Specific to


a microprocessor instruction set.
Compiler: Converts the entire source code into machine code at once. Not
needed after translation.
Interpreter: Translates one line at a time, requiring it to be present whenever
the source code is executed.
Program Development Tools
These are tools used to simplify program development.

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:

Spreadsheet tools (e.g., Calc of LibreOffice)


Adobe Photoshop
GIMP
Mozilla web browser
iTunes
Customised Software
These are tailor-made applications developed for specific organizational or
individual needs. 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.

Types of User Interfaces:


Command-based Interface: Requires users to enter commands. Uses keyboard
as primary input. Examples: MS-DOS, Unix.
Graphical User Interface (GUI): Uses icons, menus, and visual options. Input
devices include mouse and keyboard. Examples: Microsoft Windows, Ubuntu,
Fedora, Macintosh.
Touch-based Interface: Allows interaction using touch input. Examples:
Android, iOS, Windows 8.1 and 10.
Voice-based Interface: Uses voice commands for interaction. Examples: iOS
(Siri), Android (Google Now/OK Google), Microsoft Windows 10 (Cortana).
Gesture-based Interface: Allows interaction through gestures like waving,
tilting, and eye motion. Examples: Android and iOS smartphones, laptops.
Functions of Operating System
Process Management
Manages the execution of tasks (processes) to complete them in minimum
time.

It concerns the management of multiple processes, allocation of required


resources, and exchange of information among processes.

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.

File management system manages secondary memory, while memory


management system handles the main memory of a computer system.

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.

Example: When the key "A" is pressed, it is internally mapped to a decimal


value 65, which is then converted to its equivalent binary value for the
computer to understand.

💡 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.

🇺🇸 American Standard Code for Information Interchange (ASCII)


In the early 1960s, computers couldn't communicate with each other due to
different ways of representing keyboard keys. Thus, ASCII was developed to
standardize character representation. ASCII is still commonly used.
Initially, ASCII used 7 bits to represent characters. The total number of different
characters that can be encoded by 7-bit ASCII code is
2
7
=
128
2
7
=128. However, ASCII can only encode the character set of the English
language.

Example: Encode the word "DATA" and convert the encoded value into binary
values:

ASCII value of D is 68 and its equivalent 7-bit binary code = 1000100


ASCII value of A is 65 and its equivalent 7-bit binary code = 1000001
ASCII value of T is 84 and its equivalent 7-bit binary code = 1010100
ASCII value of A is 65 and its equivalent 7-bit binary code = 1000001
Character ASCII Code Binary Code
D 68 1000100
A 65 1000001
T 84 1010100
A 65 1000001
🇮🇳 Indian Script Code for Information Interchange (ISCII)
To facilitate the use of Indian languages on computers, ISCII was developed in
India during the mid-1980s. It is an 8-bit code representation for Indian
languages, which means it can represent
2
8
=
256
2
8
=256 characters. It retains all 128 ASCII codes and uses the rest of the codes
for the additional Indian language character set. Additional codes have been
assigned in the upper region (160-255) for the aksharas of the language.

🌐 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.

Different Number Systems Used in Computers


Decimal
Binary
Octal
Hexadecimal
Number systems are also called positional number systems because the value
of each symbol depends upon its position within the number.

Each symbol in a number has a positional value, computed using its position
value and the base value of the number system.

💯 Decimal Number System


The decimal number system is used in our day-to-day life and is known as the
base-10 system since 10 digits (0 to 9) are used.

💻 Binary Number System


The ICs (Integrated Circuits) in a computer are made up of transistors activated
by electronic signals. The ON/high and OFF/low states of a transistor are
represented using the digits 1 and 0, respectively. These two digits form the
binary number system. This system is also referred to as the base-2 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.

Octal Decimal Value 3-bit Binary Number


0 0 000
1 1 001
2 2 010
3 3 011
4 4 100
5 5 101
6 6 110
7 7 111
🧮 Hexadecimal Number System
Hexadecimal numbers are also used for compact representation of binary
numbers. It consists of 16 unique symbols (0-9, A-F) and is called the base-16
system. In the hexadecimal system, each alphanumeric digit is represented as a
group of 4 binary digits because 4 bits (
2
4
=
16
2
4
=16) are sufficient to represent 16 alphanumeric symbols. The decimal
numbers 10 through 15 are represented by the letters A through F.

Hexadecimal Symbol Decimal Value 4-bit Binary Number


0 0 0000
1 1 0001
2 2 0010
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
A 10 1010
B 11 1011
C 12 1100
D 13 1101
E 14 1110
F 15 1111
⚙️Applications of Hexadecimal Number System
Main Memory Addresses: Memory locations in main memory have unique
addresses. Hexadecimal notation simplifies the representation of these
addresses.
Webpage Colors: Colors on webpages are described using hexadecimal
numbers, representing the RGB (Red, Green, Blue) components.
Color Name Decimal Binary Hexadecimal
Black (0,0,0) (00000000,00000000,00000000) (00,00,00)
White (255,255,255) (11111111,11111111,11111111) (FF,FF,FF)
Yellow (255,255,0) (11111111,11111111,00000000) (FF,FF,00)
Grey (128,128,128) (10000000,10000000,10000000) (80, 80, 80)
🔄 Conversion Between Number Systems
Decimal to Other Number Systems
Divide the given number by the base value (b) of the target number system.
Note the remainder.
Keep dividing the quotient by the base value and note the remainder until the
quotient is zero.
Write the noted remainders in reverse order.
Decimal to Binary Conversion
Example: Convert
(
65
)
10
(65)
10
to binary:

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

Decimal to Octal Conversion


Example: Convert
(
65
)
10
(65)
10
to octal:

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

Decimal to Hexadecimal Conversion


Example: Convert
(
65
)
10
(65)
10
to hexadecimal:

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

From Other Number Systems to Decimal Number System


Write the position number for each alphanumeric symbol in the given number.
Get the positional value for each symbol by raising its position number to the
base value b.
Multiply each digit with the respective positional value to get a decimal value.
Add all these decimal values to get the equivalent decimal number.
Binary Number to Decimal Number
Example: Convert
(
1101
)
2
(1101)
2
into decimal number.

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

Octal Number to Decimal Number


Example: Convert
(
257
)
8
(257)
8

into decimal number.

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

Hexadecimal Number to Decimal Number


Example: Convert
(
3
A
5
)
16
(3A5)
16

into decimal number.

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

Binary Number to Octal/Hexadecimal Number and Vice-Versa


A binary number is converted to octal or hexadecimal number by making
groups of 3 and 4 bits, respectively, and replacing each group by its equivalent
octal/hexadecimal digit.

Binary Number to Octal Number


Example: Convert
(
10101100
)
2
(10101100)
2

to octal number.

Make group of 3-bits of the given binary number (right to left) = 010 101 100

Write octal number for each 3-bit group = 2 5 4

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

Binary Number to Hexadecimal Number


Example: Convert
(
0110101100
)
2
(0110101100)
2

to hexadecimal number.

Make group of 4-bits of the given binary number (right to left) = 0001 1010
1100

Write hexadecimal symbol for each group = 1 A C

Therefore,
(
0110101100
)
2
=
(
1
A
C
)
16
(0110101100)
2

=(1AC)
16

Hexadecimal Number to Binary Number


Example: Convert
(
23
D
)
16
(23D)
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

Non-decimal Number with Fractional Part to Decimal Number System


Compute positional value of each digit in the given number using its base
value. Add the product of positional value and the digit to get the equivalent
decimal number with fractional part.

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

Fractional Binary Number to Octal or Hexadecimal Number


To convert the fractional binary number into octal or hexadecimal value,
substitute groups of 3-bit or 4-bit in integer part by the corresponding digit.
Similarly, make groups of 3-bit or 4-bit for fractional part starting from left to
right, and substitute each group by its equivalent digit or symbol in Octal or
Hexadecimal number system. Add 0s at the end of the fractional part to make a
perfect group of 3 or 4 bits.

Example: Convert
(
10101100.01011
)
2
(10101100.01011)
2

to octal number.

Make perfect group of 3 bits = 010 101 100 . 010 110

Write octal symbol for each group = 2 5 4 . 2 6

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

NASA's Mars Rover Robotic space mission to study Mars.

Sophia A humanoid robot that uses AI, visual data processing, and facial reco

Drone Unmanned aircraft remotely controlled or autonomously flown via soft

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).

Velocity The high rate at which data is generated and stored.

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

Infrastructure as a Provides computing infrastructure such as servers, virtual machines, storage,


Service (IaaS) applications on this remote infrastructure, saving on hardware and software c

Platform as a Service Offers a platform or environment to develop, test, and deliver soft
(PaaS) infrastructure. Simplifies deployment and reduces the complexity

Software as a Service Provides on-demand access to application software, often requirin


(SaaS) about installation or configuration. Examples include Google Docs,

🌐 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.

Introduction to Problem Solving


Computer Science as a Science of Abstraction
 Computer science involves creating models for problems and devising
techniques to solve them.
 Computerization is the use of computers to develop software that
automates routine human tasks efficiently.
 Problem solving is an essential skill, involving:
 Identifying a problem
 Developing an algorithm
 Implementing the algorithm to develop a computer program
🪜 Steps for Problem Solving
1. Analysing the Problem
 Thoroughly understand the problem statement.
 Identify the core functionalities required for the solution.
 Determine the necessary inputs and expected outputs.
2. Developing an Algorithm
 Create a step-by-step solution in natural language.
 Refine the algorithm to capture all aspects of the desired solution.
 Multiple algorithms may be possible; select the most suitable one.
3. Coding
 Convert the algorithm into a format understandable by the
computer, using a high-level programming language.
 Document the coding procedures for future reference.
4. Testing and Debugging
 Test the program on various parameters to ensure it meets user
requirements.
 Check for syntactical errors (no output) and logical
errors (incorrect output).
 Debugging involves rectifying errors found during testing.
5. Maintenance
 Address issues faced by users after the software is deployed.
 Answer user queries and implement modifications or additional
features as needed.
GIGO (Garbage In, Garbage Out)
The correctness of the output a computer provides depends on the correctness
of the input provided.
📝 Algorithm Defined
An algorithm is a set of exact steps which, when followed, solve a problem or
accomplish a required task.
Key Aspects of Algorithms
 Algorithms lead to the desired result in a finite amount of time.
 They have a definite beginning and end.
 They consist of a finite number of steps.
Why Algorithms are Needed
 Algorithms serve as a roadmap for programmers.
 They help visualize instructions before writing code.
 They increase the reliability, accuracy, and efficiency of solutions.
Characteristics of a Good Algorithm
 Precision: Steps are clearly defined.
 Uniqueness: Results of each step are uniquely defined.
 Finiteness: The algorithm stops after a finite number of steps.
 Input: The algorithm receives some input.
 Output: The algorithm produces some output.
Essential Considerations When Writing Algorithms
 Input to be taken from the user.
 Processing or computation required.
 Desired output.
✍️Representation of Algorithms
Common Methods
 Flowcharts: Visual representation using diagrams.
 Pseudocode: Non-formal language for human reading.
Key Considerations
 Showcase the logic of the problem solution.
 Clearly reveal the flow of control during execution.
📊 Flowchart Symbols
Flowchart Symbol Function Description

Start/End Terminator Indicates where the flow starts and ends.

Process Action Represents a process, action, or single step.

Decision Branching A decision point with yes/no or true/false questions.

Input/Output Data Used to input or output data.

Arrow Connector Shows the order of flow between shapes.

⌨️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

False class finally

None continue for

True def from

and del global

as elif if

assert else import

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

int Integer numbers

float Real or floating-point numbers

complex Complex numbers

bool Boolean (True or False)

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

+ Addition Adds two numeric values

- Subtraction Subtracts the right operand from the

* Multiplication Multiplies two values

/ Division Divides the left operand by the right

% Modulus Returns the remainder of the division

// Floor Division Returns the quotient without the dec

** Exponent Performs exponential calculation (pow

5.8.2 Relational Operators


Operator Operation Description

== Equals to True if values of two operands

!= Not equal to True if values of two operands

> Greater than True if the left operand is great

< Less than True if the left operand is less t

>= Greater than or equal to True if the left operand is great

<= Less than or equal to True if the left operand is less t


Operator Operation Description

5.8.3 Assignment Operators


Operator Description

= Assigns value from right-side operand to left-side

+= Adds right-side operand to left-side and assigns result

-= Subtracts right-side operand from left-side and assigns

*= Multiplies right-side operand with left-side and assigns

/= Divides left-side operand by right-side and assigns

%= Performs modulus and assigns

//= Performs floor division and assigns

**= Performs exponential calculation and assigns

5.8.4 Logical Operators


Operator Operation Description

and Logical AND True if both operands are True

or Logical OR True if any of the two operands are

not Logical NOT Reverses the logical state of its oper

5.8.5 Identity Operators


Operator 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.8.6 Membership Operators


Operator Description

in Returns True if the value is found in the sequence

not in Returns True if the value is not found in the sequence

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 +, -

5 <=, <, >, >=, ==, !=

6 =, %=, /=, //=, -=, +=, *=, **=

7 is, is not

8 in, not in

9 not

10 and

11 or

 Parentheses () can override operator precedence.


 For operators with equal precedence, the expression is evaluated from
left to right.
Example: 20 + 30 * 40
Step 1: 20 + (30 * 40)
Step 2: 20 + 1200
Step 3: 1220
Example: 20 - 30 + 40
Step 1: (20 - 30) + 40
Step 2: -10 + 40
Step 3: 30
Example: (20 + 30) * 40
Step 1: (20 + 30) * 40
Step 2: 50 * 40
Step 3: 2000
```## 🔢 Expression Evaluation

Expressions are evaluated based on the order of operations. Here's an


example:

**Example:**

1. **Step 1:** $15.0 / 4 + (8.0 + 3.0)$


2. **Step 2:** $15.0 / 4.0 + 11.0$
3. **Step 3:** $3.75 + 11.0$
4. **Step 4:** $14.75$

## 📜 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)
```

## ⌨️Input and Output

Programs often need to interact with users to get input and provide output.

### Input

* The `input()` function is used to take user input.


* It prompts the user to enter data and accepts all input as a **string**,
regardless of whether the user enters a number or text.
* **Syntax:** `input([Prompt])` where Prompt is the string displayed to the
user (optional).

**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:**

age = int(input("Enter your age:")) print(type(age)) # <class 'int'>

### 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).

### Explicit Conversion (Type Casting)

* Explicit conversion, or **type casting**, happens when the programmer


intentionally converts a data type.
* **Syntax:** `(new_data_type)(expression)`
* It may lead to loss of information because you are forcing the expression to
be a specific type.

**Example:**

x = 20.67 int(x) # Results in 20, discarding the fractional part

**Explicit Type Conversion Functions:**

| 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'>

num4 = float(num1 + num2)


print(num4) # Output: 30.0
print(type(num4)) # Output: <class 'float'>
# Explicit type conversion from float to int
num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3) # Output: 30.8
print(type(num3)) # Output: <class 'float'>

num4 = int(num1 + num2)


print(num4) # Output: 30
print(type(num4)) # Output: <class 'int'>
# Type Conversion between Numbers and Strings
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
# print("The total is Rs." + totalPrice ) # This line will cause an error

# Explicit type casting


priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice)) # Output: The total in Rs.70
# Explicit type conversion
icecream = '25'
brownie = '45'

# String concatenation
price = icecream + brownie
print("Total Price Rs." + price) # Output: Total Price Rs.2545

# Explicit type conversion - string to integer


price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price)) # Output: Total Price Rs.70
Implicit Conversion (Coercion)
 Implicit conversion, or coercion, happens automatically by Python
without the programmer's instruction.
 Typically, Python converts data into a "wider" data type to avoid loss of
information.
Example:
# Implicit type conversion from int to float
num1 = 10 # num1 is an integer
num2 = 20.0 # num2 is a float
sum1 = num1 + num2 # sum1 is sum of a float and an integer
print(sum1) # Output: 30.0
print(type(sum1)) # Output: <class 'float'>
In the example above, the integer num1 is added to the float num2, and the
result is automatically converted to a float sum1. This is known as type
promotion.
🐞 Debugging
Debugging is the process of identifying and removing mistakes (bugs or errors)
from a program.
Types of Errors:
1. Syntax Errors:
 Occur when the code violates Python's syntax rules.
 The interpreter shows error messages and stops execution.
 Example: Missing parentheses.
2. Logical Errors:
 Occur when the program behaves incorrectly, producing an
undesired output.
 The program runs successfully, but the output is wrong.
 Example: Incorrect formula for calculating average.
3. Runtime Errors:
 Cause abnormal termination of the program during execution.
 Occur when the interpreter cannot execute a statement, even if it
is syntactically correct.
 Example: Division by zero.
Example of Runtime Errors:
# Runtime Errors Example
num1 = 10.0
num2 = int(input("num2 = ")) # If user inputs a string or a zero, it leads to
runtime error
print(num1/num2)

Chapter 10: Tuples and Dictionaries


🧱 Introduction to Tuples
A tuple is an ordered sequence of elements of different data types, such as
integer, float, string, list, or even another tuple.
Elements of a tuple are enclosed in parentheses (round brackets) and are
separated by commas. Like lists and strings, elements of a tuple can be
accessed using index values, starting from 0.
Here are some tuple examples:
tuple1 = (1,2,3,4,5)
tuple2 =('Economics',87,'Accountancy',89.6)
tuple3 = (10,20,30,[40,50])
tuple4 = (1,2,3,4,5,(10,20))
If there is only a single element in a tuple, the element should be followed by a
comma. Otherwise, it is treated as an integer.
# Incorrect
tuple5 = (20)
# Correct
tuple5 = (20,)
A sequence without parentheses is treated as a tuple by default.
seq = 1,2,3
type(seq) # <class 'tuple'>
print(seq) # (1, 2, 3)
Accessing Elements in a Tuple
Elements of a tuple can be accessed using indexing and slicing, similar to lists
or strings.
tuple1 = (2,4,6,8,10,12)
tuple1[0] # 2
tuple1[3] # 8
tuple1[-1] # 12
tuple1[1+4] # 12
♾️Tuple Immutability
Tuples are immutable, meaning their elements cannot be changed after
creation, which will raise a TypeError.
tuple1 = (1,2,3,4,5)
# tuple1[4] = 10 # TypeError: 'tuple' object does not support item assignment
However, if an element of a tuple is of a mutable type (e.g., a list), that element
can be modified.
tuple2 = (1,2,3,[8,9])
tuple2[3][1] = 10
print(tuple2) # (1, 2, 3, [8, 10])
Iterating through a tuple is faster compared to a list. If the data does not
change, storing it in a tuple ensures it is not changed accidentally.
➗ Tuple Operations
Concatenation
Tuples can be joined using the concatenation operator +.
tuple1 = (1,3,5,7,9)
tuple2 = (2,4,6,8,10)
tuple1 + tuple2 # (1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

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)

tuple6 = tuple6 + (7,8,9)


print(tuple6) # (1, 2, 3, 4, 5, 6, 7, 8, 9)
Repetition
The repetition operator * repeats elements of a tuple.
tuple1 = ('Hello','World')
tuple1 * 3 # ('Hello', 'World', 'Hello', 'World', 'Hello', 'World')

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 the number of elements in the


len() tuple. python tuple1 = (10,20,30,40,50) le

Creates an empty tuple or converts a


tuple() sequence to a tuple. python tuple1 = tuple() # () tuple1

count() Returns the number of times an element python tuple1 = (10,20,30,10,40,10


Method Description Example

appears in the tuple.

Returns the index of the first occurrence of


index() an element. python tuple1 = (10,20,30,40,50) tu

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,

Returns the sum of the elements of the


sum() 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)

radius = int(input('Enter radius of circle: '))


area,circumference = circle(radius)
print('Area of circle is:',area)
print('Circumference of circle is:',circumference)
3. Input n numbers, store in a tuple, and print max/min:
numbers = tuple()
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
📓 Introduction to Dictionaries
The dictionary data type falls under mapping. It is a mapping between a set
of keys and a set of values.
The key-value pair is called an item. A key is separated from its value by a colon
(:) and consecutive items are separated by commas. Items in dictionaries are
unordered.
Creating a Dictionary
Items are separated by commas and enclosed in curly braces {}. Each item is a
key-value pair separated by a colon :. Keys must be unique and immutable
(number, string, or tuple), while values can be repeated and of any data type.
dict1 = {} # Empty Dictionary
dict2 = dict() # Empty dictionary using built-in function
dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(dict3) # {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Accessing Items in a Dictionary
Items are accessed via keys, not indices.
dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print(dict3['Ram']) # 89
print(dict3['Sangeeta']) # 85
# print(dict3['Shyam']) # KeyError: 'Shyam'
If the key is not present, a KeyError is raised.
✏️Dictionaries are Mutable
Dictionaries are mutable, meaning their contents can be changed after
creation.
Adding a New Item
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
dict1['Meena'] = 78
print(dict1) # {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}
Modifying an Existing Item
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
dict1['Suhel'] = 93.5
print(dict1) # {'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}
🧭 Dictionary Operations
Membership
The in operator checks if a key is present in the dictionary.
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
print('Suhel' in dict1) # True
print('Suhel' not in dict1) # False
🚶 Traversing a Dictionary
We can access each item of the dictionary using a for loop.
Method 1:
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
for key in dict1:
print(key,':',dict1[key])
Output:
Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85
Method 2:
dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
for key,value in dict1.items():
print(key,':',value)
Output:
Mohan : 95
Ram : 89
Suhel : 92
Sangeeta : 85
Dictionary Methods and Built-In Functions
Python provides many functions to work on dictionaries. Here are some of the
commonly used dictionary methods:
Method Description Example

Returns the number of key-value


len() pairs in the dictionary. python dict1 = {'Mohan':95,'Ram':89,'Suhe

Creates a dictionary from a python pair1 = [('Mohan',95),('Ram',89),('S


dict() sequence of key-value pairs. 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}

Returns a list of keys in the python dict1 = {'Mohan':95, 'Ram':89, 'Suh


keys() dictionary. 'Ram', 'Suhel', 'Sangeeta'])

Returns a list of values in the python dict1 = {'Mohan':95, 'Ram':89, 'Suh


values() dictionary. 92, 85])

Returns a list of tuples (key-value python dict1 = {'Mohan':95, 'Ram':89, 'Suh


items() pairs). dict_items([('Mohan', 95), ('Ram', 89), ('Su

Returns the value corresponding to


the key, or None if the key is not python dict1 = {'Mohan':95, 'Ram':89, 'Suh
get() present. dict1.get('Sohan') # None

Appends key-value pairs from


update( another dictionary to the current python dict1 = {'Mohan':95, 'Ram':89, 'Suh
) dictionary. dict1.update(dict2) # {'Mohan': 95, 'Ram':

python dict1 = {'Mohan':95,'Ram':89, 'Suh


del() Deletes an item with the given key. 'Suhel': 92, 'Sangeeta': 85}

Deletes all items from the


clear() dictionary. python dict1 = {'Mohan':95,'Ram':89, 'Suh
🔄 Manipulating Dictionaries
Here are some programs that demonstrate dictionary manipulation:
1. Create a dictionary of odd numbers between 1 and 10 with number
names:
ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
print(ODD) # {1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}

print(ODD.keys()) # dict_keys([1, 3, 5, 7, 9])


print(ODD.values()) # dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
print(ODD.items()) # dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'),
(9, 'Nine')])
print(len(ODD)) # 5
print(7 in ODD) # True
print(2 in ODD) # False
print(ODD.get(9)) # Nine
del ODD[9]
print(ODD) # {1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
2. Enter names of employees and their salaries into a dictionary:
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict()
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
3. Count the number of times a character appears in a string:
st = input("Enter a string: ")
dic = {}
for ch in st:
if ch in dic:
dic[ch] += 1
else:
dic[ch] = 1

for key in dic:


print(key,':',dic[key])
4. Convert a number into its corresponding number in words:
def convert(num):
numberNames =
{0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Ni
ne'}
result = ''
for ch in num:
key = int(ch)
value = numberNames[key]
result = result + ' ' + value
return result

num = input("Enter any number: ")


result = convert(num)
print("The number is:",num)
print("The numberName is:",result)

You might also like