XI Computer Science Gist-01

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Class XI

Computer Science
Gist-1 of Lessons covered between 16/04/2024 to 28/06/2024
Introduction to Programming:
Program:
• Programs are a set of codes that generally take some input, process the input and produce the desired
output. This is called the IPO Cycle.
• A Programming Language is used to write a program code
• Though codes generated depend upon type of computer language used, but the procedure should be a
set of general rules to solve the given problem and should be independent of the language
• This general rule is meant to solve a given problem stepwise, based on some procedure or logic

Definition of Algorithm:
An Algorithm is:
• A sequence of precise and unambiguous instructions
• Designed in such a way that if the instructions are executed in the specified sequence
• The desired result is obtained within a finite number of steps
Example-1: Algorithm to find the average of three numbers:
1. Input the three numbers A, B, C
2. Add the numbers to get sum: Sum = (A+B+C)
3. Divide the Sum by 3, to get average:
Avg = Sum/3
4. Display the average Avg
5. End
Example-2: Algorithm to find the Cost of fencing a garden of length L and breadth B, with rate R taken per unit
length of fencing:
1. Input the length : L
2. Input the breadth : B
3. Input rate of fencing: R
4. Get perimeter of the garden: Peri = 2 * (L + B)
5. Get the total price: Price = Peri * R
6. Display Price
7. End
Example-3: Algorithm for finding the absolute value of any number:
1. Input the number to check: Num
2. If Num < 0, then
a. AValue = (–1) * Num
3. Else
a. AValue = Num
4. Print the result Avalue
5. Stop

Example-4: Algorithm to print the first N natural numbers:


1. Input the number of terms to print: N
2. To count the number of terms printed, Initialise counter by 1, Count = 1
3. If Count <= N, then
a. Print the value of the current term Count
b. Increment count-value by 1: Count = Count + 1
c. Go to Step3
4. Stop
Definition of Flowchart:
When an algorithm is expressed in a pictorial manner with special symbols to indicate the different types of
instructions, then it is called a Flowchart
In a Flowchart:
• The actual instructions are written inside boxes of different shapes, indicating different functions
• Solid lines with arrows indicating the flow of control are then used to connect the boxes
• Once the flowchart is complete, the flowchart logic is then transferred to the programming language

Symbols Used in a Flowchart

Basic Processes Represented by Flowcharts

Example-1: Sequence Example-2: Sequence


Example-3: Branching

Example-4: Branching

Example-5: Branching

Example-6: Looping
Example-7: Looping

Example-8: Flowchart to check if a number is +ve, -ve, or zero

Example-9: Flowchart to get sum of numbers from 1 to N


Example-10: Flowchart to check if a number is +ve, -ve, or zero (nested branching)

Example-11: Multiple Conditions and Nested Branching (OR)

Example-12: Multiple Conditions and Nested Branching (AND)


Example-13: Flowchart to get the Product of the first N natural numbers

Example-14: Flowchart to get sum of digits of a number

Example-14: Flowchart to get sum of digits of a number


Introduction to Python

Uses of print() function:


Uses of sep and end parameters with print() function

Components of a Programming Language


There are specific naming rules for these identifiers:
✓ An identifier can contain all the alphabets in upper and lower case
✓ Can contain the digits from 0 to 9 and the underscore character
✓ However, it cannot start with a digit
✓ No other characters are allowed to form identifiers, including blank
✓ A keyword cannot be used to form an identifier
E.g. of valid identifier names are: radius, x, val, PI, Interest_Rate, prog5, _2ndLane
E.g. of invalid identifier names are: return, 3rdPos, five#, total time, if, 222B
Different categories of literals are:
• STRING Literals: These can be single line strings like user prompts within an input() function, single line
comments, text which is a part of a print statement etc. You can have multiline strings like multiline
comments within triple quotes.
• NUMERIC Literals: These are fixed numbers present in a program, like:
o Signed Numbers like decimal, octal and hexadecimal numbers, Floating Point literals, and Complex
literals expressed in the form A+Bj
o BOOLEAN Literals are the two Boolean values True and False that can be used in a program
o SPECIAL Literal includes the None value that is used to represent nothing
Different categories of Operators are:
• There are numerous operators in Python that are divided into various categories like:
o Arithmetic ( + , - , / , // , * , % , ** )
o Relational ( > , >= , < , <= , == , != )
o Logical ( not, and, or )
o Compound Assignment ( += , -= , *= , /= , %= , **= )
Concept of Variable in Python

In Python, a VARIABLE represents a NAMED MEMORY LOCATION in the RAM, where a value is stored.

Python internally creates the following LABELS referring to these values as shown below:
Data Types in Python:
• Not every object we see around us behaves in the same manner.
• Each material has its own properties and needs to be stored and used accordingly
• In a similar manner, depending upon the nature of the value used in a program, Python categorises data
into the following categories or types, for proper and efficient handling of data
• Also, the operations possible on each category of data may be different based on the nature of the data

Different Data Types:

Numeric Data Types: Integers Type


• The int class represents an integer or a whole number
• Values like 1284, -24, 0, 321723119, etc. are treated as integers
• These are basically +ve or –ve whole numbers, including zero
Integers can also be represented in other number systems like:
• Binary (base 2 with digits 0, 1)
• Octal (base 8 with digits 0, 1, 2, 3, 4, 5, 6, 7)
• Hexadecimal (base 16 with digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F)

Numeric Data Types: Floating Point Type


• The float class represents number that contains a decimal point
• Such a number is called a floating point number or real number
• Such numbers are represented in Python as a double precision number (size 64 bits) with a precision of
up to 15 places after decimal point i.e. it can be correctly stored up to 15 decimal places
• Examples of floating point values are:
▪ X = 324.75 # This is Fractional Form
▪ y = 0.0 # ZERO in floating point form
▪ Z = 5.6E4 # Exponent Form. E4 means 104
▪ W = -2.8E3 # Values can be both +ve / -ve
▪ P = 1.835E-5 # Here E-5 means 10-5
▪ Q = 0.25E-3
Numeric Data Types: Complex Type Data
• Numbers that have an imaginary part (i.e. involving √-1) are called complex numbers. In Python √-1 is
represented by the letter j
• These are represented in Python as a complex class type data as: x + yj
• Internally Python represents such numbers as a pair of floating point numbers
• All numeric operations perform complex maths when applied to complex
numbers
• Examples of complex values are:
▪ X = 3+4j # Real & imaginary parts integers
▪ y = 2.0+5.0j # Real & imaginary parts floats
▪ W = 5j # Only imaginary part
Numeric Data Types: Boolean Type
• Boolean is a sub-type of integer type data
• The bool class represents a Boolean type data
• It represents the two values True and False
• True (represented by numeric value 1 during a calculation)
• False (represented by numeric value 0 during a calculation)

The type function can be used to see the data type of an object:

String Type Data


• Python stores a sequence of characters as a string
• The class str represents such data
• A string is represented by enclosing the sequence of
characters within a pair of single or double quotes
• Strings can be:
o single line: A single-line string is formed by
enclosing a sequence of characters within a pair of
single or double quotes like ‘abc’, “abc”, “123”,
‘abc 123’ etc.
o multiline: A multiline string is formed by enclosing
string with 3 single or double quotes. Such multiline
strings can be used to write comments in a program in the script mode. Example of a multiline string is
shown below (code written in Script Mode):
'''line-1
line-2
line-3'''
String type data can be printed using following methods:
• >>> 'Satyen Bose' #will display the string within quotes
'Satyen Bose'
• >>> print('Satyen Bose') #Using print function displays without quotes
Satyen Bose
String type data can be joined using following methods:
• >>>'Satyen' 'Bose' #Strings can be joined writing them side by side
'SatyenBose'
• >>>'Satyen' + 'Bose' #Strings can also be joined using + operator
'SatyenBose‘ #Observe NO Space inserted between two strings
String data can be repeated side by side using following methods:
• >>> ‘Abc' * 4 #Strings can be repeated using * symbol
‘AbcAbcAbcAbc'
• >>> 3 * ‘Abc’ #Number and string can be written in any order
‘AbcAbcAbc'
• >>> ‘Test’ * (-1) # Empty string formed i.e. string without any character in case number is
negative
'' # Output is a Null String
• >>> ‘Test’ * 0 # Empty string formed in case number is 0
'' # Output is a Null String
String Type Data: Joining strings with number
The ‘+’ operator cannot be used to add a string with a numeric value.
• >>> 'B' + 287 # This is invalid code and will give error message
• >>> '123' + 456 # This is also invalid code and will give error message
The problem can be overcome by using the str() function as shown:
• >>> 'B' + str (287) # Correct code. 287 converted to string type using str
'B287'
• >>> '55' + str (66) + '77' # Correct code, converting everything to string
'556677‘ # This is a string data and NOT a numeric data

List Type Data:


A List is a comma separated, mutable sequence of ordered values of any data type
• These values are put within a pair of square brackets [ ]
• The values in a list can be modified or changed in place without the requirement to create a new list
• Example of a list: L = [ 8.5, 9, 5, ‘south’, ‘road’, 10 ]
• Lists use 0 based addressing, i.e. the first element of the list is given an index of 0.
• An element of a list can be accessed using a pair of square brackets as:
print ( L[2] ), where 2 is the index of the list element accessed. Here L[2] = 5 for the above list
• When an element of a list is itself a list, then it is called a nested list
• Example of a nested list: L = [ 2, 4, [ 7, 3, 9 ], 8 ]
Tuple Type Data:
A Tuple is a comma separated, immutable sequence of ordered values of any data type
• These values are put within a pair of first brackets ( )
• The values in a tuple cannot be modified or changed. You have to create a new tuple to incorporate the
changes
• Example of a tuple: T = ( 8.5, 9, [2, 7, 5], ‘point’, (3, 5) )
• Tuples also use 0 based addressing, i.e. the first element of the tuple is given an index of 0.
• An element of a tuple is accessed using a pair of square brackets as:
print( T[2] ), where 2 is the index of the tuple element accessed. Here T[2] = [2,7,5] for the above tuple
• When an element of a tuple is itself a tuple, it is called a nested tuple:
• Example of Nested Tuple: T = ( 2, 4, ( 7, 3, 9 ), 8 )
Dictionary Type Data:
A dictionary is an unordered mutable sequence of key-value pairs.
• Each key should be a unique immutable data
• Values of a dictionary can be of any data type
• Example of a dictionary: D = { 4 : 2, ‘abc’ : 3, 5.6 : [2,3,6], (2,5) : 7 }
Operators:
Arithmetic Operators
Arithmetic operators are used for doing calculations. The different Arithmetic Operators are:
• () changing priority e.g. z = (w-x)*y hence 9*(4+3) → 9*7 → 63
• ** exponentiation e.g. z = x**y hence 2**3 → 8
• * multiplication e.g. z = x*y hence 6*5 → 30
• / true division e.g. z = x/y hence 8/5 → 1.6
• // floor division e.g. z = x//y hence 8//5 → 1
• % remainder/modulo div. e.g. z = x%y hence 10%4 → 2
• + addition e.g. z = x+y hence 6+8 → 14
• – subtraction e.g. z = x-y hence 12-7 → 5
Priority Rules
• In an expression that has a mixture of these operators, the calculation is carried out based on a set of
priority rules that signify which operation is to be carried out first
• The operators with higher priority execute earlier compared to operators with lower priority
• Of these, some operators may have the same priority as that of some other operators
• The operators’ priorities are listed below:
1. ( ) Highest Priority
2. x**y
3. –x, +x Same Priority
4. x*y, x%y, x/y, x//y Same Priority
5. x+y, x-y Lowest Priority
Hence in the expression shown below the calculation will take place step-by-step in the order shown
z = a – b ** c / d
= a – b ** c / d
= a – [ result of b**c ] / d
= a – [ result of b**c/d ]
Associativity Rules
• We have seen that in case there is a mixture of operators, then Python follows the Priority Rules to carry
out the calculations
• However, a calculation can have operators with the same priority in an expression. In such a case, the
Associativity Rule comes into action
• ASSOCIATIVITY rule states that in case there are more than one operators with the same priority and
these operators occur in consecutive positions, then normally the operation is carried out from left to right
• EXCEPTION: However, for exponentiation operation it is associated from right to left when multiple such
operations are placed side by side
PLEASE DO NOT USE THE BODMAS RULE OF MATHS IN PROGRAMS

Calculation example-1: Calculation example-2: Calculation example-3:


z = 5+4/2*3-16 z = 8+2**3**2//4 z = 10-(2+18/6)*3/5
= 5+4/2*3-16 = 8+2**3**2//4 =10-(2+18/6)*3/5
= 5+2.0*3-16 = 8+2**9//4 =10-(2+3.0)*3/5
= 5+6.0-16 = 8+512//4 = 10-5.0*3/5
= 11.0-16 = 8+128 = 10-15.0/5
= -5.0 = 136 = 10-3.0
= 7.0
See BODMAS rule is NOT followed here, and
Multiplication is done before Division as per
Associativity rule
Arithmetic Operators: Types of Division
There are two types of divisions possible in Python. These are:
• Normal Division
• Floor Division
Normal Division
• The operator / performs normal division in Python.
• As per the rules of normal division, the actual quotient is produced if you divide two numeric values of
any type (i.e. int or float).
E.g. 10 / 4 = 2.5, 1 / 2 = 0.5, 15 / 5 = 3.0
6.5 / 4 = 1.625, 8.4 / 3.2 = 2.625, 8 / 2.5 = 3.2
NOTE: For Normal Division the result is always expressed as a float
Floor Division:
• The operator // performs floor division
• It works for both integers and floating point numbers. In both cases, it returns the whole number part
of the quotient, by truncating the fractional part
• The result is expressed as an integer if both numerator and denominator are integers
▪ E.g. 8//5 = 1 10//4 = 2 1//2 = 0 15//5 = 3
• The result is expressed as a float if either or both numerator and denominator are floats
▪ E.g. 6.5//4 = 1.0 8.4//3.2 = 2.0 8//2.5 = 3.0
NOTE: For Floor Division the result can be integer or float
Modulo Division (Remainder)
• The Modulo Operation is used to get the remainder of dividing two numbers
• The modulo operation is expressed by the % symbol
• Examples:
▪ 11 % 3 = 2 # As the remainder of dividing 11 by 3 is 2
▪ 28 % 7 = 0 # As the remainder of dividing 28 by 7 is 0
▪ 5%8=5 # As the remainder of dividing 5 by 8 is 5
▪ 6%2=0 # If a number divided by 2 gives 0 remainder, then it is EVEN
▪ 7%2=1 # If a number divided by 2 gives 1 remainder, then it is ODD
Arithmetic Operators: Division with negative numbers
The result of floor division when either or both the numbers involved are negative can be confusing. Let us see
some examples to make things clear.
E.g.: -8 / 5 = -1.6
8 / (-5) = -1.6
-8 / (-5) = 1.6
These 3 results are as expected from maths
When carrying out Floor Division with negative numbers, let us see some examples:
E.g.: -8 // 5 = -2 # The result is the floor of the number -1.6 i.e. the nearest integer to the left of -1.6
8 // (-5) = -2 #The result is the floor of the number -1.6 i.e. the nearest integer to the left of -1.6
-8 // (-5) = 1 #The result is same as 8//5 = 1 as in mathematics

Arithmetic Operators: Modulo operation with floating point and negative numbers
The modulo operator works on BOTH integer and float numbers
Examples on Floats: i. 8 % 4.2 = 3.8 ii. 9.5 % 4 = 1.5 iii. 8.5 % 2.5 = 1.0
To get the above results remember the following points:
• remember that while doing the division do not put a point after the quotient and continue with the division
• Stop the division when you reach the last digit of the whole number portion
• After carrying out the final subtraction, whatever is left behind, will give you the remainder
To get the result of modulo division when either or both the numbers involved are negative, REMEMBER that
the quotient part for such an operation is similar to floor division. The remainder can then be calculated using
this quotient as shown below:
The following examples and their explanations in the following slides will make things clear:
E.g. -8 % 5 = 2 8 % (-5) = -2 -8 % (-5) = -3

Some Definitions:
ATOM
o In programming, an ATOM means something that has a value
o E.g. Identifiers, Literals, Strings, Lists, Tuples, Sets, Dictionaries
EXPRESSION
o Any valid combinations of Operators and Atoms and composed of one or more Operations
o Expressions can be of the following types:
▪ Arithmetic E.g. 12 * 6.5
▪ String E.g. ‘Multi’ + ’level’
▪ Relational E.g. 5<8
▪ Logical E.g. 5<8 or 6<8
▪ Compound E.g. a+b > c and c*b-d != b-c
Lvalue and Rvalue:
o Lvalue: It means Locator Value. These represent some objects in memory. Generally, they occur on the
LEFT side of the assignment operator (=) and represent a variable. They can also occur on the RIGHT of
assignment (=)
o Rvalue: Expressions that are not L-Values and do not occupy some memory location. They come on RIGHT
hand side of an assignment (=) operator and represents an expression generally.
▪ Vol = side*side*side : Vol is LValue, side*side*side is RValue
▪ Peri = 2 * (length + width) : Peri is LValue, 2*(length+width) is RValue
▪ Y=Z : Y and Z both LValue
▪ 3.5 = A + B : Incorret use of LValue
TYPE CASTING
• The explicit conversion of an operand to a specific type
• It is a user defined conversion that forces an expression to be of a different type
▪ It is performed by using an expression like: New_Value = <New_Data_Type> ( Expression )
▪ Examples: a = 8.5 → Indicates a to be a float type data
b = int (a) → Will convert 8.5 to integer type 8
x=6 → Indicates x to be an int type data
y = float (x) → Will convert 6 to float type 6.0
Examples of typecasting between float and integers.

Examples of different Typecasting are given below:

Copying and Exchanging Values


Dynamic Typing
• Python uses a concept called Dynamic Data Typing to assign data to a variable
• It means that the data type of an assigned object is automatically detected at run-time i.e. when the
program is running
• Hence VARIABLES in Python have NO DATA TYPES. They are simply labels. The data type is associated
with the data object itself.
• The example below shows that the same variable name is used to store different types of values and
Python automatically detects the correct data type as indicated by the type() function.

Concept of Mutable & Immutable


Depending upon the way you can modify the content of a variable, variables in Python can be placed under two
broad categories. These are:
• Immutable data types
These refers to those data types whose values CANNOT be changed in place i.e. cannot be modified
without changing the variable itself. If you try to modify the content of an immutable data type, Python
will not allow you to do so. You have to change the variable itself to modify it.
Different immutable data types are: int, float, string, tuple
You can check the change in memory address by using the id( ) function
in the way shown on the right.
Initially both a and b point to the address 1690264816 of the value 10.
But after the modification of a, it now points to the address of 13, i.e.
1690264864.
Whereas b continues to point at the old address of 10 i.e. 1690264816.
• Mutable data types
These refers to those data types whose values CAN be changed in place
i.e. you can modify the content of a mutable data type without the
need to change the variable or create a new variable. If you try to
modify the content of a mutable data type, Python will allow you to
modify the values of such data types
Different mutable data types are: list, dictionary
You can check the memory address of L1 by using the id( ) function like
the previous example
Initially list L1 point to the address 55773624
Note that after the modification of L1, it still points to the same address
55773624
Use of input() function to input data from the user
The input( ) is used in Python to input any type of data. You can input data from the user using the input()
function. By default, the input() function inputs data as a string. You have to use the int or bool or float
functions to convert the data for appropriate use as shown on the right.
Some examples of use of input() function:

EXAMPLES: Using input( ) function to write programs


1. Program to find the average of two numbers.

2. Program to find the density of an object.

3. Program to find the capacity of a box.

4. Program to find the volume of a cone = 1/3  r2 h


Relational Operators
• Sometimes you may need to compare values to arrive at a conclusion
• For example:
▪ We may have an online program that checks whether a person is above 18 years of age, before
offering a driving-test date for licence
▪ We may have a program embedded into a digital petrol dispensing system, that dispenses petrol as
long as the dispensed petrol is not equal to the set amount
▪ We may need to check if the colour of a food item label is ‘red’ or ‘green’ during billing using an
automated digital billing machine
• All such checking is done in programming using a set of operators called the Relational Operators. These
operators are used for Comparing Values
Different Relational Operators
Take a=18, b=10
• > greater than e.g. a>b → 18 > 10 → True
• >= greater than or equal to e.g. a >= b → 18 >= 10 → True
• < lesser than e.g. a<b → 18 < 10 → False
• <= lesser than or equal to e.g. a <= b → 18 <= 10 → False
• == equal to e.g. a == b → 18 == 10 → False
• != not equal to e.g. a != b → 18 != 10 → True
Properties of Relational Operators:
• The output of these relational operators are the Boolean values True or False
• The result is True if the outcome of the comparison is valid
• The result is False if the outcome of the comparison is invalid
• If these True & False values are taken for any calculation or comparison, then they are treated as 1 and 0
• One can use a cascade (series) of relational operators one after the other also
• When Arithmetic Operators and Relational Operators are together present in an expression, then as
Arithmetic Operators have a higher priority over Relational Operators
• Hence automatically Arithmetic Operators are executed first, followed by Relational Operators
• It is advisable to avoid comparing floating point values using == operator as It may give wrong results
Comparing Numeric Values:
>>> print( 12 > 3 ) → True
>>> print( 5 >= 9 ) → False
>>> print( 5 == 5 ) → True
>>> print( 5 != 5 ) → False
Comparing Results of Numeric Expressions:
REMEMBER: Arithmetic has higher priority than Relational
a+b>c-d is same as (a+b) > (c-d)
a+b>c-d is NOT same as a + (b>c) - d
>>> print ( 2+7 < 4*2 ) → False # As, 9 < 8 = False, First calculation done, then condition checked
>>> print ( 8-2*3 <= 4-12//6 ) → True # As 2<=2 = True, First calculation done, then condition checked
Comparing Results of Relational Operations
>>> print ( (6>2) > (7>1) ) → False # ( (6>2) > (7>1) ) → True > True → 1 > 1 → False
>>> print ( (5<3) != (8>6) ) → True # ( (5<3) != (8>6) ) → False != True → True

Doing Calculations with Results of Relational Operations


>>> print ( (2+7 > 4*2) * 2 ) →2 # (2+7 > 4*2) * 2 → (9 > 8) * 2 → (True) * 2 → (1) * 2 → 2
>>> print ( (4*3 != 6*2) + 5 ) →5 # (4*3 != 6*2) + 5 → (12 != 12) + 5 → (False) + 5 → (0) + 5 → 5
Comparing True / False values with Numbers
>>> print ( True > False ) → True # As True is equivalent to 1 and False is equivalent to 0
>>> print ( 3 == True ) → False # As True is equivalent to 1
>>> print ( 3 > True ) → True # As True is equivalent to 1
Comparing Floating Point Numbers
• While comparing floating point numbers, Python automatically removes all trailing 0’s after the decimal
point from a number before comparing
• However, while converting floating point numbers to binary, an approximation may be made
• E.g.: The binary equivalent of 0.3, 0.7 etc. are not exactly equal in value to the original decimal numbers
• This may give rise to certain anomalies. Hence it is better to avoid comparing floating point values using
the == operator
>>> print ( 3.0 == 3.0 ) → True
>>> print ( 3 == 3.0 ) → True #Because Python removes all trailing 0’s before comparing
>>> print ( 0.625 == 0.125 + 0.5 ) → True #No approximation is made for 0.625, 0.125, and 0.5
>>> print ( 0.6 == 0.2 + 0.2 + 0.2 ) → False #Approximations made for 0.6 & 0.2, hence incorrect result
Cascading of Relational Operators
• When multiple relational operations are made in a single statement, it is called cascading of relational
operators
• The relations are actually compared in pairs and all these pairs are joined by an and operation.
• In such a case, only when all the individual conditions are True, the overall result will be True
• In case any of the conditions is False, the final result is False
Thus a > b <= c != d is same as: a > b and b <= c and c != d
The overall condition is True, only when all the individual conditions are True
>>> print ( 4*3 < 5+9 <= 7*3 ) → True # 4*3 < 5+9 <= 7*3 → 12 < 14 <= 21 → 12<14 and 14<=21 →
# True and True → True
>>> print ( 1 != 4 > 5 == 5 ) → False # 1 != 4 > 5 == 5 → 1 != 4 and 4 > 5 and 5 == 5 →
# True and False and True → False and True → False
Representation of Strings
• Strings are represented in memory as one or more characters enclosed by a pair of single or double
quotes
• Each character in a string is given an index, with which you can access a particular character in the string
• The index of the first character is 0 and it is followed by the index values 1, 2, 3, 4, etc.
• The following example shows the index values for the string ‘THURSDAY’
Index: 0 1 2 3 4 5 6 7
Character: T H U R S D A Y
Strings and ASCII Values
• Internally everything is represented as binary numbers in a computer
• Hence, each character on the keyboard is also represented internally as a number
• These numeric values are called ASCII (American Standard Code for Information Interchange) values for
the characters
• Each ASCII value is a 7 digit binary value, which is written as a decimal number for convenience
• For example, The letter ‘A’ is represented by the binary number, 1000001, which in decimal is same as 65
and the letter ‘a’ is represented by the binary number, 1100001, which in decimal is same as 97
ASCII Values (in decimal) of the Alphabets and Digits

Comparing Strings
• Python compares strings using the dictionary order
• Strings that will occur lower in the dictionary are given a lower value compared to strings that occur
higher in the dictionary. Thus, the string ‘camera’ is considered less than the string ‘eye’
• CAPITAL letters are considered lesser than small letters. Thus ‘Great’ is considered less than ‘great’
• Actually, the ASCII value of the characters in the string are taken while deciding upon the order
Examples:
>>> print ( 'abc' < 'pqr' ) → True # As ‘abc’ will occur in a dictionary before ‘pqr’
>>> print ( 'bat' < 'mat' ) → True # As ‘bat’ will occur in a dictionary before ‘mat’
>>> print ( 'Bat' < 'bat' ) → True # As Capital Letters are considered lower in dictionary
>>> print ( 'bat' < 'battery' ) → True # As 'bat' will occur lower in the dictionary than 'battery'
>>> print ( 'Bat' < 'battery' ) → True # As 'B' occurs lower in the order than 'b'
Comparing Lists / Tuples
• Two lists or tuples are considered identical if these have the same values in the same order
• For inequality, a list / tuple with the first larger value from the left is considered larger in value
• However, when considering the values during comparison, the pair of values that decide the result
during comparison, should be of the same data type
>>> print( [2, 4, 6] == [2, 4, 6] ) → True #As both lists are identical
>>> print( [2, 4, 8] > [2, 4, 6] ) → True #As first two values are same, but for third value 8>6
>>> print( [5, 3] > [2, 8, 9] ) → True #As first value 5>2; number of elements is NOT considered
>>> print ( [2, 4, 6] < [2, 4, 6, 8] ) → True #First 3 elements same. But second list has one more value
>>> print ( [7, 4, 6] < [2, 4, 6, 8] ) → False #As first value 7>2, the remaining values are not considered
>>> print ( ['bat', 'mat', 'rat'] == ['bat', 'mat', 'rat'] ) → True #As both the lists are identical
>>> print ( ['bat', 'mat', 'rat'] < ['bat', 'pat', 'rat'] ) → True #As 'mat' < 'pat' in dictionary order
>>> print ( [ 'abc', 'pqr', 'zyk‘ ] < [ 2, 5, 3 ] ) → ERROR #As str and int can’t be compared
>>> print ( [ 2, 'ab', 4 ] < [ 2, 5, 'pq‘ ] ) → ERROR
#As first values are identical, hence second values are compared and 'ab' (str) and 5 (int) are different types
>>> print ( ( 1, 'ab', 4 ) < ( 2, 5, 'pq‘ ) ) → True #As first values in the tuple are of same data
type and different, hence 'ab' and 5 not checked
>>> print( ( [ 4, 7, 3 ] , ‘pqr’, 45 ) < ( [ 6, 8, 2 ] , ‘abc’, 66 ) ) → True
#The first element in each tuple is a list, and 4 in [4, 7, 3] is less than 6 in [6, 8, 2]
>>> print( [ [5, 8] , [2, 7] , 4 ] > [ [5, 8] , [9, 3] , 4 ] ) → False
#As first values are identical, hence second values are compared and 2 in [2, 7] is less than 9 in [9, 3]
>>> print( [ [‘abc’, 8] , [2, 7] , ‘mno’ ] > [ [5, 8.2] , [9, 3] , 4 ] ) → ERROR
#First values compared ‘abc’ and 5 are of different data types. Hence error
Comparing Dictionaries
• As dictionaries are unordered sequence, hence these are compared based on the key:value pairs
• The order in which the key:value pairs occur is not considered
• Only equality (==) and non-equality (!=) operators are used with dictionaries
• Other type of comparisons cannot be done on dictionaries
>>> print ( { 'a':2, 'b':7, 'c':5 } == { 'a':2, 'b':7, 'c':5 } ) → True #As both dictionaries are identical
>>> print ( { 'a':2, 'b':7, 'c':5 } == { 'a':2, 'c':5, 'b':7 } ) → True # Order of elements does not matter in
dictionaries
>>> print ( { 'a':2, 'b':7, 'c':5 } == { 'a':2, 'c':3, 'b':7 } ) → False #As different key:value pairs
>>> print ( { 'a':2, 'b':7, 'c':5 } != { 'a':2, 'c':3, 'b':7 } ) → True #As different key:value pairs

Computer Organisation
Computer System: It consists of:
• Central Processing Unit (CPU)
✓ Control Unit (CU)
✓ Arithmetic & Logic Unit (ALU)
• Input Devices: Taking data into the computer
✓ Keyboard, Mouse, Scanner, Mic, Tablet, OMR, OCR, MICR
• Output Devices: Taking data out of the computer
✓ VDU, Printer (DMP, Inkjet, Laser), Plotter, Speaker
• Primary Memory: For storing the working data
✓ Random Access Memory (RAM) & Read Only Memory (ROM)
• Cache Memory: Fast memory between CPU and RAM
• Secondary Memory: For storing data permanently. E.g. HDD, CD, DVD, BD
• Bus: For communication
✓ Data Bus, Address Bus, Control Bus
Some Definitions
Scanner: A scanner is an input device which can be used to input or scan images and documents and store
them in a digital format in the computer
Barcode Reader: A barcode reader is used to scan ready product information from product labels. It is used in
supermarkets, shops, libraries, post offices and other places
Touch Screen: A touch screen is a special display screen where the user can enter data by touching the screen
at specific locations. It is a display, which can detect the presence and location of a touch within the display area
OMR: Optical Mark Reader is an input device used to read and process data from pre-printed document-forms
marked by humans.
OCR: Optical Character Reader is a technology used to optically scan pages containing text and then to identify
and save the scanned data as a text file instead of an image file
MICR: Magnetic Ink Character Recognition technology is used mainly by banking systems for faster processing
of large volumes of cheques. The bank’s data are pre-printed using a special magnetic ink.
VDU: A visual display unit (VDU), or commonly a video monitor is the most widely used output device. Two
types of VDU are Cathode Ray Tube or CRT displays, Liquid Crystal Displays (LCDs), Light Emitting Diode (LED)
displays
Dot Matrix Printer (DMP): These printers are impact printers and are similar to mechanical typewriters. They
use a set of pins of very small radius to print dots on paper
Inkjet Printer: An inkjet printer is a non-impact printer. It prints by ejecting microscopic drops of ink through
tiny ink nozzles in the print head to produce a particular character or image.
Laser Printer: These non-impact type printers use dry powder ink (called toner) to print text or images on
paper, similar to a photocopy machine.
Plotter: A plotter is similar to an inkjet printer, but is used for printing on larger papers or continuous paper
rolls.
CPU: Central Processing Unit is the brain of any computer system and is made up of two basic components,
namely the Control Unit (CU) and the Arithmetic and Logic Unit (ALU)
ALU: Arithmetic and Logic Unit is the place where the actual execution of the instructions takes place during
data processing. It executes arithmetic calculations and comparisons of data
CU: Control Unit acts like a supervisory unit in the CPU and is responsible for issuing control instructions to
carry out different functions of the CPU
Primary Memory: The primary memory is the main memory of the computer and a computer cannot run
without it. Two types of primary memory are Random Access Memory (RAM) and Read Only Memory (ROM).
ROM: Read Only Memory is a non-volatile permanent memory, the contents of which can be only read but
cannot be altered. It is also called firmware, which permanently stores the basic information needed by the
computer during start-up. Different types of ROM are:
▪ ROM: These are the first semiconductor ROMs that contained a pre-programmed set of data or
instructions.
▪ PROM (Programmable ROM): It is purchased in an un-programmed state. Special equipment like a device
programmer is used to write data into the PROM by applying an electrical charge to the input pins of the
chip.
▪ EPROM (Erasable and Programmable ROM): It is programmed in exactly the same manner as a PROM.
Unlike a PROM, EPROMs can be erased using strong ultraviolet (UV) light and reprogrammed repeatedly.
▪ EEPROM (Electrically Erasable and Programmable ROM): Internally, they are similar to EPROMs, but
instead of using UV light, the erase operation is done electrically (it is also pronounced as E2 PROM)
RAM: Random Access Memory is treated as the main working memory of the computer. However, RAM is
volatile in nature and it’s content are lost when power is switched off. The different types of RAM are:
▪ Dynamic RAM (DRAM): Dynamic RAM is a volatile memory with a very short data lifetime. The
electrical charge stored in each memory cell needs to be periodically refreshed to retain its data.
Hence, it is called dynamic RAM. DRAM is available in the form of IC chips of 2GB, 4GB, 8GB capacity
▪ Static RAM (SRAM): Static RAM is also a volatile memory, but unlike DRAM, it does not require any
refreshing of charges to retain its data. Hence these are called static RAM. It can retain its data as long
as its electrical power is on. These are costlier than DRAM and are used in smaller quantities like 512
KB, 1 MB, or 2 MB
Secondary Memory: To store large volumes of data permanently we need a secondary storage device. The
secondary memory is a permanent memory, where the results of data processing are stored from the RAM for
future use.
Memory Unit:
Main unit of memory is byte consisting of 8 binary digits or bits. Several bytes can be taken together to form
the following units:
✓ Kilo Byte or KB: 1 KB = 1024 Bytes = 210 Bytes
✓ Mega Byte or MB: 1 MB = 1024 KB = 210 Kilo Bytes
✓ Giga Byte or GB: 1 GB = 1024 MB = 210 Mega Bytes
✓ Tera Byte or TB: 1 TB = 1024 GB = 210 Giga Bytes
✓ Peta Byte or PB: 1 PB = 1024 TB = 210 Tera Bytes

You might also like