0% found this document useful (0 votes)
20 views37 pages

Introduction to Computer Science Concepts

This document provides an introduction to Computer Science, focusing on key areas such as algorithms, problem-solving techniques, and the components of computers. It defines algorithms and their characteristics, discusses the limits of computational problem solving, and outlines the hardware and software aspects of computers. Additionally, it covers programming paradigms, error types, and the process of computational problem solving with examples like the Tower of Hanoi.

Uploaded by

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

Introduction to Computer Science Concepts

This document provides an introduction to Computer Science, focusing on key areas such as algorithms, problem-solving techniques, and the components of computers. It defines algorithms and their characteristics, discusses the limits of computational problem solving, and outlines the hardware and software aspects of computers. Additionally, it covers programming paradigms, error types, and the process of computational problem solving with examples like the Tower of Hanoi.

Uploaded by

thunderemp49
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 1

Introduction

1.1 Computer Science

Computer Science deals with the study of computers and computational systems. The main
areas of studies within Computer Science include the following:

 Artificial Intelligence
 Database Systems
 Software Engineering
 Programming Languages
 Computer Vision

However one of the major goals of Computer Science is to solve problems applying
computational techniques. In order to solve computational problems we need to visualize them
as algorithms.

1.2 Algorithm

Algorithms are the basic design strategies that tell how your computer programs need to
be organized so that they can be developed and executed correctly. Algorithms can be expressed
in natural languages or in terms of pseudo-codes. Natural languages statements at times can
lead to ambiguity. Pseudo code is a more structured way to express algorithms.

1.3 Definition of Algorithm

An algorithm is a well-ordered set of instructions for a specific computational task.

1.3.1 Characteristics of an Algorithm


 Unambiguous statement: Algorithm statements must be simple and straightforward.
 Input: An algorithm should accept zero or more inputs.
 Has a result: An algorithm must generate a result so that the output can be verified.
 Takes a finite amount of time: Algorithms should be able to accomplish their tasks in
a finite amount of time.

1
1.4 The Essence of Computational Problem Solving

In order to solve any problem using computers we first need to visualize the problem, next
we need to identify the main actors in the problems and then write an algorithm to express the
solutions, by the following steps.

1. Identify, visualize or abstract the relevant ideas of the problem.


2. Build a computational model
3. Write an algorithm to solve the problem

Example: Write an algorithm to compute the area of circle.

Step 1: Problem is given a value for radius compute the area of a circle

Step 2: The mathematical formula is

area = 𝜋 𝑋 𝑟 2

The equivalent computational model or representational formula is

area = 𝜋 𝑋 𝑟 2 ∗ r

Step 3: Write an algorithm to solve the problem.

Algorithm: Area of Circle

Input: Two floating point variable area, radius

Output: The floating point variable area

Step 1: Start

Step 2: Read “Enter the value of radius”, radius

Step 3: Compute the area

area = 3.4 ∗ r ∗ r

Step 4: Write “The area of circle is:”, area

Step 5: Stop

In the above algorithm you observe the steps are executed one after another in a sequential
manner. Also the algorithm area of circle takes an input radius, computes the area and is
capable of executing in a finite number of steps.

2
1.5 Limits of Computational Problem Solving

If an algorithm cannot be implemented in a finite amount of time it becomes


computationally infeasible or we say we have reached the limits of computational problem
solving.

Example 1: Tower of Hanoi

The Tower of Hanoi puzzle was invented by the French mathematician Edouard Lucas in
[Link] job was to move all 64 disks from one of the three poles to another, with two
important constraints.

 They could only move one disk at a time, and


 They could never place a larger disk on top of a smaller one.

The number of moves necessary to move a tower with n disks can be calculated as: 2 n –
1. Thus the number of moves required to correctly move a tower of 64 disks is 2 64 – 1 = 18,
446, 744, 073, 709, 551, 615. At a rate of one move per second, that is going to be for 584,
942, 417, 355 years. Thus to solve the above problem it would be computationally infeasible as
it takes such a long duration.

3
1.6 Computer

A computer is defined as a fast calculating electronic machine which can accept input,
store and process data and display the results. A block diagram of a computer is as illustrated
in Figure 1.

Central Processing Unit (CPU)

Arithmetic Logic Unit


(ALU)

Input Device Control Unit Output Device

Memory

Figure 1.1 Block architecture diagram of a computer

 The input device allows you to enter information to the computer or interact with it. For
example, keyboard and mouse.
 The Central Processing Unit (CPU) is the brain of the computer. It controls all the
operations of the computer through the control unit.
 The Arithmetic and Logical Unit (ALU) performs arithmetic and logical operations.
 The memory is the place where the operation system, application programs and data are
stored for easy access by microprocessor.
 The monitor is the output device which displays the output or results of a computational
task.

Digital computers rely on binary system of 1’s and 0’s and work on the principles of Boolean
logic, a set of rules devised by a British Mathematician George Boole.

In binary system or Base 2 system we have only two digits 0 and 1. In the popular decimal
system we have ten digits from 0 to 9.

Let us consider an example to convert 1010 in binary to its equivalent in decimal.

4
Each digit in binary which represents a value which is of the power of 2 and 0 represents
zero

Conversion of (1010)2 to (?)10

1 0 1 0
23 22 21 20

i.e., 1 x 23 + 0 x 22 + 1 x 21 + 0 x 20 = 8 + 0 + 2 + 0 = 10

Similarly we can convert a decimal 10 to its equivalent binary. Here we go on dividing the
decimal number with 2. If the division is complete the answer is 0 else it is 1. This process
continues until the quotient of the decimal number is 0.

Dividing Decimal Quotient Remainder Binary Bit


Number Number
2 10 5 0 0 (LSB)
2 5 2 1 1
2 2 1 0 0
2 1 0 1 1 (MSB)

Write the final answer from last – Most Significant Bit (MSB) to first – Least Significant
Bit (LSB).

= 1010

A bit represents a single value as 0 or 1. These bits can be grouped into higher order
values as illustrated in Table 1.1

Table 1.1 Grouping of bits

Unit Name Number of Bits/Bytes


Nibble 4 bits
Byte 8 bits
Kilobytes (KB) 1000 bytes
Megabyte (MB) 1000 Kilobytes
Gigabyte (GB) 1000 Megabyte
Terabyte (TB) 1000 Gigabyte

A computer can be visualized in terms of its hardware and software components.

1.6.1 Hardware

The physical component of a computer is known as the hardware. Examples of hardware


include keyboard, central processing unit, monitor, hard disk, etc. The hardware components
are as listed in Table 1.2.

5
Table 1.2 Hardware components of a computer

Hardware Component Description

Central Processing Unit (CPU) The CPU is called the brain of the
computer. It takes instructions from
the main memory (Random Access
Memory –RAM); executes them.
Input Device – Keyboard Keyboard is an input device that
allows information to be fed to a
computer.
Output Device – Monitor The standard output device which
allows results processed by a CPU to
be displayed.
Main Memory (RAM) This is the place which stores
Operating System (OS), applications
programs and data for easy access to
CPU. This is called volatile memory as
information is stored temporarily here
and is lost when computer is switched
off.
Secondary Storage – Hard disk An electro-mechanical device to store
and retrieve digital data. It is also
called persistent storage as
information stored here is not lost
when a computer is switched off.

1.6.2 Software

Software is defined as programs plus data that enables a compute to perform a specific
task along with the associated documentation. Without software a computer is a dumb machine;
it is the software that brings a computer to life especially the operating system. Examples of
software include operating system, python interpreter, device driver, etc. The software
examples are as listed in Table 1.3.

6
Table 1.3 Computer software examples

Computer Software Description


Operating System (OS) It is called as a resource manager as
it manages all the resources of the
computer like memory, input and
output devices.
Device Driver A device driver is a computer program
that supports a particular device
attached to a computer. It allows the
device to communicate with the
computer. Example hard disk device
driver allows you to read or write from
a computer hard disk.
Application software – Word processor Is a computer program to read, write
and edit text along with additional
formatting options.

Programming languages are defined in terms of syntax and semantics.

 The syntax defines structure or the grammar of the language. Example a date in a
calendar can be represented by DD/DD/DDD.
 The semantics gives the logical meaning of the syntax. Thus for the syntax DD/DD/DDDD
we can have date interpreted as 01/10/2020. Here it could be interpreted as 1 st October
2020 or 10th January 2020 as interpreted in British or American formats.

1.7 Compiler vs Interpreter

Interpreter Compiler

The source code is directly executed The source code is first converted into
by an interpreter. a machine level code and then
executed.
It executes the program step by step. A compiler translates a program
completely before it starts executing.
Debugging is easy in programming Relatively debugging is difficult for a
languages that are designed to be compiled program.
interpreted.
Interpreters do not generate an Compiler generates an intermediate
intermediate code. code.
Example: Perl and Ruby. Example: C and C++.

7
1.8 Syntax vs Semantic Errors

Syntax Error

Syntax - the structure or the grammar of the language.

 The compiler can detect the presence of such errors at compile time itself.
 Thus the programmer based on the error messages can rectify the syntax related
issues of the source program.
 A program will not compile until the syntax errors are eliminated. Syntax errors
are type errors and can be detected easily in the source code.

Semantic Error

Semantics provides the meaning for the syntactical structure.

 Semantic errors are also known as logical errors.


 These errors arise due to the poor understanding of the program logic.
 These errors cannot be detected by the compiler and results in the program
producing incorrect results.
1.9 Procedural vs Object Oriented Programming Paradigm

Table 1.5 Procedural programming vs Object oriented programming

Procedural Programming Concept Object Oriented Programming


Concept
In procedural programming data and In object oriented programming the
operations on data are separated. focus is on the operations of objects
which are a combination of data and
procedures.
Procedural programming does not Object oriented programming
support the concept of data hiding and supports the concept of data hiding
encapsulation. and encapsulation.
Procedural Programming follows top- Object oriented programming follows
down programming approach. bottom-up approach.
Procedural programming has Object oriented programming is
limitations when the size of the useful for developing scalable
program increases. programs.
The usage of global data for sharing Data can easily move between
information between functions is methods and can be controlled
allowed. through access specifiers.
Example: C, Pascal. Example: Java, C++.

Note: Python supports procedural programming as well as object-oriented programming.

8
1.10 The Process of Computational Problem Solving

Computational problem solving is not just a one-time activity but it involves a process. The
steps or phases involved in the process are illustrated in Figure 1.2.

A. The problem analysis and definition phase involves analyzing the problem. After analysis
we write a precise and unambiguous problem statement which clearly identifies the
problem to be solved.
B. The design phase involves identifying the principal data structures and coming up with an
algorithm to solve the problem.
C. The implementation phase involves of implementing the algorithm into a corresponding
programming language. In our case we use python programming language.
D. Testing and debugging involves coming up with test cases to test the program and
removes any bugs found thereby.

Problem
Analysis and
Definition

Design Phase

Implementati
on Phase

Testing and
Deb

Figure 1.2 Computational problem solving process

Example : Tower of Hanoi

9
A. Problem of Analysis

The towers of Hanoi consist of 3 rods. The puzzle start state consists of plates arranged on
one of the towers in ascending order. If we consider 3 plates then we have to make 2 n – 1
move. i.e., 23 – 1 = 7 moves. The rules to be followed in the puzzle are as follows:

a) You are allowed to move only one plate at a time.


b) Each plate movement will necessarily involve moving the topmost plate and placing it on
another plate or an empty tower.
c) The plate which is moved cannot be placed on top of a smaller plate.

All plates stacked on the leftmost tower will be moved to the rightmost tower.

Figure 1.3

10
Problem Statement: Program to solve towers of Hanoi using recursion.

B. Design phase

Important data structures

n an integer value which indicates number of pegs

src_peg peg on source rod

temp_peg peg on temporary rod

target_peg peg on target rod

Algorithm

Algorithm: hanoi (n, src_peg, target_peg, temp_peg)

Step 1: If n==1

Step 1.1: Write “Move disk 1 from peg {0} to peg {1}”, src_peg, target_peg

Step 1.2: return

Step 2: hanoi (n-1, src_peg, target_peg, temp_peg)

Step 3: Write “Move disk 0 from peg {0} to peg{1}”, src_peg, target_peg

Step 4: hanoi (n-1, src_peg, target_peg, temp_peg)

Algorithm: main()

Hanoi (3, “A”, “B”, “C”)

C. Implementation

A python implementation of the algorithm is presented below.


[Link] c:/User/Admin/AppData/Local/Programs/Pyton35/ [Link] (3.5.2)

File Edit Format Run Options Window Help


‘’’
Python program to solve tower of Hanoi problem
‘’’
Def hanoi (n, src_peg, target_peg, temp_peg):
If n==1:
Print (“Move disk1 from peg(0) to peg (1)”. Format (src_peg, target_peg))
return
#move top n-1 disks from A (src_peg) to B(target_peg) using c(temp_peg)
Hanoi (n-1, src_peg, temp_peg, target_peg).
#move remaining disk from A to C
Print (“Move disk (0) from peg (1) to peg (2)”, format (str(n), src_peg, target_peg))
#move n-1 disks from B to C using A as auxilliry
Hanoi (n-1, temp_peg, target_peg, src_peg)

Hanoi (3, “A”, “B”, “C”)

11
D. Test Case

The Python program is tested for cases when n=1 and n=3 and in both cases the results are
correct and thus the test cases pass.

Test Description Expected Result Actual Result Test Case


No. Result
1 To move 1 peg Move disk 1 from Move disk 1 from Pass
pegA to B pegA to pegB
2 To move 3 peg Move disk1 from Move disk1 from Pass
pegA to pegB pegA to pegB
Move disk2 from Move disk2 from
pegA to pegC pegA to pegC
Move disk1 from Move disk1 from
pegB to pegC pegB to pegC
Move disk3 from Move disk3 from
pegA to pegB pegA to pegB
Move disk1 from Move disk1 from
pegC to pegA pegC to pegA
Move disk2 from Move disk2 from
pegC to pegB pegC to pegB
Move disk 1 from Move disk 1 from
pegA to pegB pegA to pegB

1.11 Python Programming Language

Python was conceived in the late 1980’s. Its development began in 1989 by Guido van
Rossum who was working for Centrum voorWiskundeenInformatica (CWI) at Netherlands.
Python drew lot of inspiration from its predecessor language ABC. Guido van Rossum published
the first version of Python (ver.0.9.0) on February 1991.

1.11.1 Salient Features of Python Language

Python Programming language has the following features:

 Easy to Learn: Python with its simple syntax, few keywords and simple structure is easy
to learn.
 Object Oriented: It supports object-oriented programming with classes and multiple
inheritance.
 Standard Library: This large standard library support many computing tasks like
connecting to databases, web servers and performing text operations.
 Extendable: It is easily extendable by adding new modules implemented in languages like
C and C++
 Portable: You can run python programs on Linux Windows and Mac with no changes.
 Embeddable Language: Python code can be embedded as a script in C or C++
 Scalable: You can write large programs with elegant structure.

12
1.11.1 Introduction:
 General-purpose Object Oriented Programming language.
 High-level language
 Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
 It is derived from programming languages such as ABC, Modula 3, small talk, Algol-
68.
 It is Open Source Scripting language.
 It is Case-sensitive language (Difference between uppercase and lowercase letters).
 One of the official languages at Google.
Characteristics of Python:
 Interpreted: Python source code is compiled to byte code as a .pyc file, and this
bytecode can be interpreted by the interpreter.
 Interactive
 Object Oriented Programming Language
 Easy & Simple
 Portable
 Scalable: Provides improved structure for supporting large programs.
 Integrated
 Expressive Language
Python Interpreter:
Names of some Python interpreters are:
 PyCharm
 Python IDLE
 The Python Bundle
 pyGUI
 Sublime Text etc.

There are two modes to use the python interpreter:


i. Interactive Mode
ii. Script Mode

13
i. Interactive Mode: Without passing python script file to the interpreter,
directlyexecute code to Python (Command line).

Example:
>>>6+3

Output: 9

Fig: Interactive Mode

Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\[Link]”).read( ))

ii. Script Mode: In this mode source code is stored in a file with the .py extension and
use the interpreter to execute the contents of the file. To execute the script by the
interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name [Link] , to run the script you have to follow the following
steps:
Step-1: Open the text editor i.e. Notepad
Step-2: Write the python code and save the file with .py file extension.
(Defaultdirectory is C:\Python33/[Link])
Step-3: Open IDLE ( Python GUI) python shell
Step-4: Click on file menu and select the open option
Step-5: Select the existing python file

Step-6: Now a window of python file will be opened


Step-7: Click on Run menu and the option Run Module.
Step-8: Output will be displayed on python shell window.

14
Fig. : IDLE (Python GUI)

Fig: Python Shell

Python Character Set :


It is a set of valid characters that a language recognize.

Letters: A-Z, a-z


Digits : 0-9
Special Symbols
Whitespace

15
1.12.1 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
• Keyword
• Identifier
• Literal
• Operators
• Punctuators
1. Keyword: Reserved words in the library of a language. There are 33 keywords in
python.

False class finally is return break

None continue for lambda try except

True def from nonlocal while in

and del global not with raise

as elif if or yield

assert else import pass

All the keywords are in lowercase except 03 keywords (True, False, None).
2. Identifier: The name given by the user to the entities like variable name, class-
name,function-name etc.

Rules for identifiers:

 It can be a combination of letters in lowercase (a to z) or uppercase (A to Z)


ordigits (0 to 9) or an underscore.
 It cannot start with a digit.
 Keywords cannot be used as an identifier.
 We cannot use special symbols like !, @, #, $, %, + etc. in identifier.
 _ (underscore) can be used in identifier.
 Commas or blank spaces are not allowed within an identifier.

16
3. Literal: Literals are the constant value. Literals can be defined as a data that is given in
a variable or constant.

Literal

String Literal
Numeric Boolean Special
Collections

int float complex

True False None

A. Numeric literals: Numeric Literals are immutable.


Eg. 5, 6.7, 6+9j
B. String literals:

String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.
Eg:

"Aman" , '12345'

Escape sequence characters:


\\ Backslash
\’ Single quote
\” Double quote
\a ASCII Bell
\b Backspace
\f ASCII Formfeed
\n New line charater
\t Horizontal tab

17
C. Boolean literal: A Boolean literal can have any of the two values: True or False.

D. Special literals: Python contains one special literal i.e. None.

None is used to specify to that field that is not created. It is also used for end of lists in
Python.

E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.

4. Operators: An operator performs the operation on operands. Basically there are


twotypes of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator

A. Unary Operator: Performs the operation on one operand.


Example:
+ Unary plus
- Unary minus
~ Bitwise complement
not Logical negation
B. Binary Operator: Performs operation on two operands.

5. Separator or punctuator : , ; , ( ), { }, [ ]

1.13 Mantissa and Exponent Form:

A real number in exponent form has two parts:


 mantissa
 exponent
Mantissa : It must be either an integer or a proper real constant.
Exponent : It must be an integer. Represented by a letter E or e followed by integer value.

18
Valid Exponent form Invalid Exponent form
123E05 2.3E (No digit specified for exponent)
1.23E07
0.24E3.2 (Exponent cannot have fractional part)
0.123E08
23,455E03 (No comma allowed)
123.0E08
123E+8
1230E04
-0.123E-3
163.E4
.34E-2
4.E3

1.14 Basic terms of a Python Programs:


A. Blocks and Indentation
B. Statements
C. Expressions
D. Comments

A. Blocks and Indentation:


 Python provides no braces to indicate blocks of code for class and function definition
orflow control.
 Maximum line length should be maximum 79 characters.
 Blocks of code are denoted by line indentation, which is rigidly enforced.
 The number of spaces in the indentation is variable, but all statements within the
blockmust be indented the same amount.
for example –
if True:

print(“True”)
else:
print(“False”)
19
B. Statements
A line which has the instructions or expressions.

C. Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.

D. Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.

There are two types of comments in python:


i. Single line comment
ii. Multi-line comment

i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values

ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’

20
Multiple Statements on a Single Line:

The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)

1.15 Variable/Label in Python:


Definition: Named location that refers to a value and whose value can be used and processed
during program execution.
Variables in python do not have fixed locations. The location they refer to changes every time
their values change.

21
Creating a variable:

A variable is created the moment you first assign a value to it.

Example:

x=5

y = “hello”

Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.

x = 4 # x is of type int
x = "python" # x is now of type str
print(x)

Rules for Python variables:

A variable name must start with a letter or the underscore character



 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and underscore (A-z, 0-
9,and _ )
 Variable names are case-sensitive (age, Age and AGE are three different variables)
Python allows assign a single value to multiple variables.

Example: x=y=z=5

You can also assign multiple values to multiple variables. For example −

x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12

22
Lvalue and Rvalue:
An expression has two values. Lvalue and Rvalue.
Lvalue: the LHS part of the expression
Rvalue: the RHS part of the expression
Python first evaluates the RHS expression and then assigns to LHS.
Example:
p, q, r= 5, 10, 7
q, r, p = p+1, q+2, r-1
print (p,q,r)
Now the result will be:
6 6 12

Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.
 If you want to know the type of variable, you can use type( ) function :
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
 If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x del y, z

23
1.16 Input from a user:
input( ) method is used to take input from the user.
Example:
print("Enter your name:")
x = input( )
print("Hello, " + x)

 input( ) function always returns a value of string type.

1.17 Type Casting:


To convert one data type into another data type.

Casting in python is therefore done using constructor functions:


 int( ) - constructs an integer number from an integer literal, a float literal or a string

literal.

Example:

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

 float( ) - constructs a float number from an integer literal, a float literal or a string literal.

Example:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

 str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
24
Example:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Reading a number from a user:


x= int (input(“Enter an integer number”))

1.18 OUTPUT using print( )


statement:Syntax:
print(object, sep=<separator string >, end=<end-string>)
object : It can be one or multiple objects separated by comma.
sep : sep argument specifies the separator character or string. It separate the objects/items. By
default sep argument adds space in between the items when printing.
end : It determines the end character that will be printed at the end of print line. By default it
has newline character( ‘\n’ ).
Example:
x=10
y=20
z=30
print(x,y,z, sep=’@’, end= ‘ ‘)
Output:
10@20@30

25
DATA HANDLING

1.19 Data Types in Python:


Python has Two data types –

1.19.1 Primitive Data Type (Numbers, String)


1.19.2 Collection Data Type (List, Tuple, Set, Dictionary)

Data Types

Primitive Collection
Data Type Data Type

Number String

List Tuple Set Dictionary


int float complex

1. Primitive Data Types:


a. Numbers: Number data types store numeric values.

There are three numeric types in Python:

 int
 float
 complex

Example:
w=1 # int
y = 2.8 # float
z = 1j # complex

26
 integer : There are two types of integers in python:
 int
 Boolean

 int: int or integer, is a whole number, positive or negative, without decimals.


Example:

x=1
y = 35656222554887711
z = -3255522
 Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:

>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True

 float : float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:

x = 1.10y = 1.0

z = -35.59
a = 35e3
b = 12E4
c = -87.7e100

27
 complex : Complex numbers are written with a "j" as the imaginary part.
Example:

>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>[Link]
5.0
>>>[Link]
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.

b. String: Sequence of characters represented in the quotation marks.


 Python allows for either pairs of single or double quotes. Example: 'hello' is the
sameas "hello" .
 Python does not have a character data type, a single character is simply a string with
alength of 1.
 The python string store Unicode characters.
 Each character in a string has its own index.
 String is immutable data type means it can never change its value in place.

2. Collection Data Type:


 List
 Tuple
 Set
 Dictionary

28
1.20 MUTABLE & IMMUTABLE Data Type:
 Mutable Data Type:
These are changeable. In the same memory address, new value can be stored.
Example: List, Set, Dictionary
 Immutable Data Type:
These are unchangeable. In the same memory address new value cannot be stored.
Example: integer, float, Boolean, string and tuple.

1.21 Basic Operators in Python:

i. Arithmetic Operators
ii. Relational Operator
iii. Logical Operators
iv. Bitwise operators
v. Assignment Operators
vi. Other Special Operators
o Identity Operators
o Membership operators

i. Arithmetic Operators: To perform mathematical operations.

RESULT
OPERATOR NAME SYNTAX
(X=14, Y=4)
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
/ Division (float) x/y 3.5
// Division (floor) x // y 3
% Modulus x%y 2
** Exponent x**y 38416

Example:

>>>x= -5 >>>x**2 >>> -25

29
ii. Relational Operators: Relational operators compare the values. It
eitherreturns True or False according to the condition.

RESULT
OPERATOR NAME SYNTAX
(IF X=16, Y=42)

False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y

iii. Logical operators: Logical operators perform Logical AND, Logical OR and LogicalNOT
operations.

OPERATOR DESCRIPTION SYNTAX


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if operand is false not x

Examples of Logical Operator:

The and operator: The and operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands

30
a. Relational expressions as operands:

X Y X and Y
False False False
False True False
True False False
True True True

>>> 5>8 and 7>3


False
>>> (4==4) and (7==7)
True

b. numbers or strings or lists as operands:


In an expression X and Y, if first operand has false value, then return first operand X as a
result, otherwise returns Y.
X Y X and Y
>>>0 and 0 false false X
0 false true X
>>>0 and 6 true false Y
0 true true Y
>>>‘a’ and ‘n’
’n’
>>>6>9 and ‘c’+9>5 # and operator will test the second operand only if the first operand
False # is true, otherwise ignores it, even if the second operand is wrong

The or operator: The or operator works in two ways:


a. Relational expressions as operands
b. numbers or strings or lists as operands

a. Relational expressions as operands:

X Y X or Y
False False False
False True True
True False True
True True True

>>> 5>8 or 7>3


True
>>> (4==4) or (7==7) True

31
b. numbers or strings or lists as operands:
In an expression X or Y, if first operand has true value, then return first operand X as a
result, otherwise returns Y.

X Y X or Y
false false Y
false true Y
true false X
true true X

>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand
True # is false, otherwise ignores it, even if the second operand is wrong

The not operator:

>>>not 6
False
>>>not 0
True
>>>not -7
False

Chained Comparison Operators:


>>> 4<5>3 is equivalent to >>> 4<5 and 5>3
True True

32
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.

OPERATOR DESCRIPTION SYNTAX


& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Examples:
Let Output:
a = 10
0
b=4

print(a & b) 14

-11
print(a | b)
14
print(~a)
2
print(a ^ b)
print(a >> 2) 40

print(a << 2)

33
v. Assignment operators: Assignment operators are used to assign values to the variables.

OPERA
TOR DESCRIPTION SYNTAX

= Assign value of right side of expression to left side operand x=y+z


Add AND: Add right side operand with left side operand and a+=b
+=
then assign to left operand a=a+b
Subtract AND: Subtract right operand from left operand and then a-=b a=a-
-=
assign to left operand b
Multiply AND: Multiply right operand with left operand and then a*=b
*=
assign to left operand a=a*b
Divide AND: Divide left operand with right operand and then a/=b
/=
assign to left operand a=a/b
Modulus AND: Takes modulus using left and right operands and a%=b
%=
assign result to left operand a=a%b
Divide(floor) AND: Divide left operand with right operand and a//=b
//=
then assign the value(floor) to left operand a=a//b
Exponent AND: Calculate exponent(raise power) value using a**=b
**=
operands and assign value to left operand a=a**b
Performs Bitwise AND on operands and assign value to left a&=b
&=
operand a=a&b
Performs Bitwise OR on operands and assign value to left a|=b
|=
operand a=a|b
Performs Bitwise xOR on operands and assign value to left a^=b
^=
operand a=a^b
Performs Bitwise right shift on operands and assign value to left a>>=b
>>=
operand a=a>>b
Performs Bitwise left shift on operands and assign value to left a <<=b a=
<<=
operand a << b
vi. Other Special operators: There are some special type of operators like-

a. Identity operators- is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are
equaldoes not imply that they are identical.

34
is True if the operands are identical
is not True if the operands are not identical

Example:
Let a1
=3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]

print(a1 is not b1)


print(a2 is b2) # Output is False, since lists are mutable.
print(a3 is b3)

Output:
False
True
False
Example:

>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False

35
b. Membership operators- in and not in are the membership operators; used to
testwhether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}

print('D' in x)

print('digital' not in x)

print('Digital' not in x)

print(3 in y)

print('b' in y)

Output:
TrueTrueFalseTrueFalse

36
37

You might also like