Introduction to Computer Science Concepts
Introduction to Computer Science Concepts
Introduction
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
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.
Step 1: Problem is given a value for radius compute the area of a circle
area = 𝜋 𝑋 𝑟 2
area = 𝜋 𝑋 𝑟 2 ∗ r
Step 1: Start
area = 3.4 ∗ r ∗ r
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
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.
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.
Memory
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.
4
Each digit in binary which represents a value which is of the power of 2 and 0 represents
zero
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.
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
1.6.1 Hardware
5
Table 1.2 Hardware components of a computer
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
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.
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
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
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
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:
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
Algorithm
Step 1: If n==1
Step 1.1: Write “Move disk 1 from peg {0} to peg {1}”, src_peg, target_peg
Step 3: Write “Move disk 0 from peg {0} to peg{1}”, src_peg, target_peg
Algorithm: main()
C. Implementation
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.
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.
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.
13
i. Interactive Mode: Without passing python script file to the interpreter,
directlyexecute code to Python (Command line).
Example:
>>>6+3
Output: 9
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
14
Fig. : IDLE (Python GUI)
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.
as elif if or yield
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.
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
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'
17
C. Boolean literal: A Boolean literal can have any of the two values: True or False.
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.
5. Separator or punctuator : , ; , ( ), { }, [ ]
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
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.
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)
21
Creating a variable:
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)
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)
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:
str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
24
Example:
25
DATA HANDLING
Data Types
Primitive Collection
Data Type Data Type
Number String
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
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.
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.
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
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:
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.
30
a. Relational expressions as operands:
X Y X and Y
False False False
False True False
True False False
True True True
X Y X or Y
False False False
False True True
True False True
True True 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
>>>not 6
False
>>>not 0
True
>>>not -7
False
32
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
| Bitwise OR x|y
~ Bitwise NOT ~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
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]
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