, >=, <, <=, ==, !=) are used to compare values and return True or False. - Strings can be compared alphabetically based on dictionary order and ASCII values. Capital letters are considered lower than lowercase. - Lists and tuples can be compared based on the values within them, with the first unequal values determining the outcome. Data types must match for values to be compared. - Floating point numbers may not compare accurately using == due to binary representation approximations.">, >=, <, <=, ==, !=) are used to compare values and return True or False. - Strings can be compared alphabetically based on dictionary order and ASCII values. Capital letters are considered lower than lowercase. - Lists and tuples can be compared based on the values within them, with the first unequal values determining the outcome. Data types must match for values to be compared. - Floating point numbers may not compare accurately using == due to binary representation approximations.">
[go: up one dir, main page]

0% found this document useful (0 votes)
31 views30 pages

XI Computer Science Gist-02

This document summarizes key concepts around relational operators covered between July 1st and August 24th, including: - Relational operators (>, >=, <, <=, ==, !=) are used to compare values and return True or False. - Strings can be compared alphabetically based on dictionary order and ASCII values. Capital letters are considered lower than lowercase. - Lists and tuples can be compared based on the values within them, with the first unequal values determining the outcome. Data types must match for values to be compared. - Floating point numbers may not compare accurately using == due to binary representation approximations.

Uploaded by

shreyammanna101
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)
31 views30 pages

XI Computer Science Gist-02

This document summarizes key concepts around relational operators covered between July 1st and August 24th, including: - Relational operators (>, >=, <, <=, ==, !=) are used to compare values and return True or False. - Strings can be compared alphabetically based on dictionary order and ASCII values. Capital letters are considered lower than lowercase. - Lists and tuples can be compared based on the values within them, with the first unequal values determining the outcome. Data types must match for values to be compared. - Floating point numbers may not compare accurately using == due to binary representation approximations.

Uploaded by

shreyammanna101
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
You are on page 1/ 30

Class XI

Computer Science
Gist-2 of Lessons covered between 01/07/2023 to 24/08/2023
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

Logical Operators
• These operators are used for joining multiple conditions in a program and for negating a given
condition
• The output of these logical operators can be the Boolean values True or False, or other data types,
depending upon the particular operation. There are three different Logical Operators. These are:
• not (highest priority)
• and
• or (lowest priority)
• When an expression contains arithmetic, relational, and logical operators, then BY DEFAULT, these are
executed in the order Arithmetic first, Relational second, Logical third
• While using Logical Operations, Python considers the null values None, False, 0, 0.0, 0j, '', [ ], ( ), { } as
False. All other values (both positive and negative for numeric data) are considered as True
Tables Showing the Results of Different Logical Operators:

Working of not Operator


>>> print ( not (12>3) ) → False # First relational operator checks 12>3 as True, not(True) = False
>>> print ( not ( [ ] ) ) → True # Empty list is taken as False, hence not(False) = True
>>> print ( not ( '' ) ) → True # Empty string '' is taken as False, hence not(False) = True
>>> print ( not ( 0.0 ) ) → True # Numeric 0 or 0.0 is taken as False, hence not(False) = True
>>> print ( not ( 5 ) ) → False # Numeric value other than 0 is True, hence not(5) = not(True) = False
>>> print ( not ('a') ) → False # Not null string is taken as True, hence not('a') = not(True) = False
>>> print ( not (False) ) → True # Here we have the Boolean value False. Hence not(False) = True
>>> print ( not (False) * 5 ) → True # * works first to get (False)*5 = 0*5 = 0 = False. Then, not(False) = True
>>> print( ( not (False) ) * 5 ) → 5 # ( ) makes ( not (False) ) work first to get True. Then, True*5 = 1*5 = 5
>>> print ( not (False) + 5 ) → False # + works first to get (False)+5 = 0+5 = 5 = True. not(True) = False
>>> print ( ( not (False) ) + 5 ) → 6 # ( ) makes (not(False)) work first to get True. Then, True+5 = 1+5 = 6
Properties of and Operator
While using and operator REMEMBER that:
• The conditions connected by and operators are checked one by one from left to right till a condition is
found to be False.
• No further conditions will get checked after that condition, and the overall result will be taken as False.
• Only when all the connected conditions are True, the overall condition will be True
>>> print( 5 < 8 and 6 >= 3 ) → True # True and True = True
>>> print( 2 != 5 and 7 < 4 ) → False # True and False = False
>>> print( 4 < 2 and 3 >= 1 ) → False # False and True = False
>>> print( 3 < 1 and 4 != 4 ) → False # False and False = False
>>> print( 3 < 1 and 1/0 != 0 ) → False # False and Error = False, The 2nd part 1/0 != 0 is not checked
>>> print( 4>2 and 6<3 and 8!=7 ) → False # True and False and True = False and True = False
>>> print( 6>8 and 7<4 and 4!=9 ) → False # False and False and True = False
>>> print( 3>1 and 4==4 and 5!=7 ) → True # True and True and True = True and True = True (all parts
checked)
Properties of or Operator
While using or operator REMEMBER that:
• The conditions connected by or operators are checked one by one from left to right till a condition is
found to be True
• No further conditions will get checked after a True condition and the result will be taken as True
• Only when all the conditions are False, the overall condition will be False
>>> print( 5<8 or 6>=3 ) → True # True or True = True
>>> print( 3<1 or 4!=4 ) → False # False or False = False
>>> print( 3 > 1 or 1/0 != 0 ) → True # True or Error = True, The 2nd part 1/0 != 0 is not checked
>>> print( 3>1 or 4==4 or 5!=7 ) → True # True or True or True = True
>>> print( 5<=3 or 6!=6 or 7<=9 ) → True # False or False or True = False or True = True (all parts checked)

Logical Operators Applied directly on Data:


Using numbers, strings, lists, tuples with and/or Operators
When using different data types as operands for and & or operators, two rules are followed:
▪ In an expression X or Y:
o If X has a value equivalent to False, then result is Y
o Else result is X
▪ In an expression X and Y:
o If X has a value equivalent to False, then result is X
o Else result is Y
Remember: 0, 0.0, 0j, '', [ ], ( ), { }, None are considered as equivalent to False for logical operations.
Using OR operator directly on different types of data:
>>> print( 'abc' or 'xyz' ) → abc # First value is non null, hence first value
>>> print( '' or 'xyz' ) → xyz # First value is null (string), hence second value
>>> print( [ ] or 'xyz' ) → xyz # First value is null (list), hence second value
>>> print( [2,5] or 'xyz' ) → [2,5] # First value is non null, hence first value
>>> print( [2,5] or '' ) → [2,5] # First value is non null, hence first value
>>> print ( 6 or [ 2, 9 ] ) →6 # First value is non null, hence first value
>>> print ( '' or [ ] ) →[] # First value is null (string), hence second value
>>> print ( (2, 5) or [ ] or [1,3] ) → (2, 5) # First value is not-null tuple, hence first value
>>> print ( '' or [ ] or ( ) or { } ) →{} # Last value, as all previous values are null in value

Using AND operator on different types of data:


>>> print ( 'abc' and 'xyz' ) → xyz # First value is non null, hence second value
>>> print ( '' and 'xyz' ) → # First value is null (string), hence first value (null string cannot be seen)
>>> print ( [ ] and 'xyz' ) →[] # First value is null (list), hence first value
>>> print ( [2, 5] and 'xyz' ) → xyz # First value is non null, hence second value
>>> print ( ('a’, 'b') and [2, 9] ) → [2,9] # First value is non null, hence second value
>>> print ( '' and [ ] ) → # First value is null (string), hence first value (null string)

Using MIXED operators on different types of data:


>>> print ( ‘12a' and ‘16b’ or [1, 2] ) → 16b
# First value is non null, hence second value for and. Then for or first value
>>> print ( ['a', 'b'] or 'cat' and [ ] ) → ['a', 'b']
# First and operation result is [ ]. Then or operation result is [‘a’, ‘b’]
>>> print ( {1:'a', 2:'b'} and 12 and [3, 6] ) → [3, 6]
# As first and second arguments are not-null, hence last argument
>>> print ( (4//2-2) or {3:'man', 5:'can'} and [1, 4] ) → [1, 4]
# First and operation result is second argument list. The or result is also list
>>> print ( 'mat' and (['mat', 'cat'] or { } and ['sat']) and -2.5 ) → -2.5

The IDENTITY Operators:


We had learnt that Python variables are like labels which refer to memory locations containing different value
and Python preloads commonly used values into memory for faster processing

In the previous example the variables a and b, refer to the same value and point to the SAME memory address.
• The identity operators
are used to check if both
operands reference the
same object in memory
• The identity operators
compare memory
locations of two objects and return True or False, depending upon whether they are same or not
Examples of output of Identity Operators

Difference between EQUALITY and IDENTITY Operators


There are certain cases when Python creates two different objects that are storing the same value. These are:
▪ When strings are input from the console/keyboard
▪ Writing very large integers
▪ Writing Floating Point literals
▪ Writing Complex Literals
Under such circumstances, as the values of the objects are same:
▪ The EQUALITY operator will compare them and give the result as True in case their values are same
▪ However, IDENTITY operator will give result as False, as they are occupying different memory locations
Examples of different outputs of Equality and Identity Operators

The BITWISE Operators:


▪ Bitwise operators are similar to Logical Operators
▪ Bitwise Operators work on Binary Representation of Data
▪ To get the result of a bitwise operation, first the numbers need to be converted to binary and then the
operator is to applied bitwise for every vertical pair of bits from the numbers. The final result is given
in decimal
▪ These operators can be used to change individual bits in a value
Note: To understand the working of the
=12 bitwise operators, you need to convert
the decimal numbers to binary to get the
result and then reconvert the result from
=13
binary to decimal as shown in the
examples on the left.
=1

Assignment and Augmented Assignment Operators:


These operators are used to assign results of operations to an object.
1. = Simple Assignment a=6
2. += Augmented Addition a += b → a=a+b
3. -= Augmented Subtraction a -= b → a=a-b
4. *= Augmented Multiplication a *= b → a=a*b
5. /= Augmented Division a /= b → a=a/b
6. //= Augmented Floor Division a //= b → a = a // b
7. %= Augmented Remainder a %= b → a=a%b
8. **= Augmented Exponentiation a **= b → a = a ** b
Examples of use of compound assignment operators:

Use of Set or Membership Operators


• There are two special set or membership operators that can be used to check if a particular value occurs in
a sequence of values or not
• A sequence can include a string, list, tuple or dictionary
• These operators are:
▪ in : It returns True if the search value is present in the sequence. Otherwise, it returns False
▪ not in : It returns True if the search value is NOT present in the sequence. Otherwise, it returns False
Examples:
>>> L = [2, 5, 8, 3, 5, 2, 9]
>>> 5 in L
True
>>> 7 in L
False
>>> 1 not in L
True
>>> s = 'therefore'
>>> 'the' in s:
True
>>> 'p' not in s:
True
Operator Priority of all Operators taken together (Highest to Lowest):
1. () Brackets Used to change priority
2. ** Exponentiation (Binary)
3. ~x Bitwise not (Unary)
4. +x, -x Unary + , - (Unary)
5. *, /, //, % Mult., Div., Floor Div., Rem. (Binary)
6. +, - Addition, Subtraction (Binary)
7. & Bitwise & (Binary)
8. ^ Bitwise xor (Binary)
9. | Bitwise or (Binary)
10. <, <=, >, >=, <>, !=, ==, is, is not Relational, Identity (Binary)
11. not Boolean NOT (Unary)
12. and Boolean AND (Binary)
13. or Boolean OR (Binary)
14. =, +=, -=, *=, /=, //=, **=, %= Assignment (Binary)

BRANCHING
• In some programs all the lines in the code may not get executed every-time
• In such a program, some part of the code may get executed under some conditions and another part of
the code may get executed under certain other conditions
• Such a process is called Branching
• In Branching:
▪ In case a condition is found to be True, a certain block of code is executed
▪ In case the condition is found to be False, then another block of code may be executed
• In Python, branching is executed by using the if-else or the if-elif-else constructs, where if, elif, and else
are keywords
The working of if-else is given below:

The condition is normally formed using the Relational Operators ( >, >=, <, <=, ==, != ) and Logical Operators
Example: Program to find the Absolute Value of a number
Example: Program to check if a number is Even or Odd

Example: Program to print the Smaller of two numbers input

Example: If quantity of item purchased is more than 10, then print “discount 20%”, otherwise print “discount
10%”

Example: Finding Absolute value WITHOUT else


Note that you can also have an if statement in a code, WITHOUT the else statement
There is an alternative way of using an else
statement, even if not required, using pass. The
block of code under else will be simply skipped
due to pass

Example: Program to find the maximum of three numbers

Using Multiple Conditions


• The programs we have discussed so far, used a single condition to arrive at a decision
• There are problems where more than one conditions need to be checked to arrive at a decision
• Such checking is done by extending the basic if-else structure in two different ways:
▪ By using the if-elif-else construct: This is similar to logical or operation
▪ By using the concept of Nested Branching: This is similar to logical and operation
Using if-elif-else

Example: Following program checks if a number entered is negative, zero, or positive. Here at least TWO
conditions need to be checked.
Use of single line if-else statement:
Python lets you write the if-else statement in a single line as per the syntax:

Use of Nested Branching:


• In Nested Branching you can put an if, if-else or if-elif-else
control structure inside the if, elif or else block of another branching control structure
• Any combination is possible. You can put an if or if-else or if-elif-else within the:
▪ if block only
▪ elif block only
▪ else block only
▪ Or within any combination of blocks
• Python does not limit the level of nested conditions in a program and you can have any number of nesting
The working of Nested Branching operation is shown below. Any combination of these is possible.

Example: The following program checks if a point in the Cartesian plane lies exclusively in the First Quadrant
ONLY

• When both conditions x>0 and y>0 are True


• When conditions x>0 is True but and y>0 is False
• When x>0 is False
Example: Program to check if a number lies between 50 and 100 (both inclusive), i.e. within a given range of
values, WITHOUT using cascading relational operators

Example: The following program checks if a number is either a multiple of 5, or 9 or both. It uses nested if-else
in both the if and the else block.

Use of if-elif-else Ladder Logic

Same As

In general, when there are more than two if conditions in if-elif-else statements then it is referred to as an
if-elif-else Ladder. If one of the if / elif condition is True, the rest of the ladder is bypassed.
Example: The program checks if three sides can form a Triangle or not
Example: The program checks if three numbers are Pythagorean or not. The numbers can be input in any order.

Example: To check if a year is a Leap Year or not.


For a year to be a Leap Year:
• If it is a millennium year (like 1800, 1900, 2000, 2100 etc.), it has to be divisible by 400
• If it is a non-millennium year, then it has to be divisible by 4
• For all other cases it is not a Leap Year

1900 not divisible by 400. First condition False


1900 is divisible by 100. This shows that 1900 is a millennium year but
not divisible by 400 hence, it is not a Leap Year as per definition

2012 not divisible by 400. First condition False


2012 not divisible by 100 also. Hence it is not a millennium year.
2012 is divisible by 4, hence it is a Leap Year

1219 not divisible by 400. First condition False


1219 not divisible by 100 also. Hence it is not a millennium year.
1219 not divisible by 4, hence NOT Leap Year

1600 divisible by 400. First condition True


Hence it is a Leap Year

Example: Following program displays ALL POSSIBILITIES in getting the maximum of three numbers…
Use of Membership Operators
Working with Strings.
Example: The following program checks if the letter ‘a’ occurs in a word input by the user

Example: The following program checks if a letter input by the user is a vowel or not

Working with Lists.


Example: The following program checks if a particular amount is available as a currency note.

Use of Logical or Operator (to join conditions and negate a condition):


• In case the output of a logic is True, if at least one condition from a set of conditions is True, then such a
logic can be formed:
▪ Either using an if-elif-else ladder
▪ Or using or operators
• We have seen how to use the if-elif-else with multiple elif constructs to implement this
• The following example shows how the same can be done using Logical or operators

Example: Checking for Pythagorean Triplets using Logical or operator.


Use of Logical and Operator (to join conditions):
• In case the output of a logic is True, if all the conditions from a set of conditions are True, then such a logic
can be formed:
▪ Either using nested if statements
▪ Or using and operators
• We have seen how to use nested if constructs to implement this
• The following example shows how the same can be done using Logical and operators
Example: Finding the grades using logical and operator and the chart shown below:

Use of Logical or & Logical and Operators (to join conditions):


The following program checks if a year is a Leap Year or not using Logical and/or Operators
USING LOOPs
Types of loops:
Whenever certain code needs to be repeated, we require the use of loops and the process is called Iteration.
There are three types of loops used in Python.
• for loop: This is used when the number of iterations is KNOWN beforehand
• while loop: This is used when the number of iterations is NOT KNOWN beforehand
• nested loop: This is used when we need to put one loop inside the body of another loop
Example of Iteration: Flowchart to get sum of numbers from 1 to N
• The value sum is used to store the total sum
• The value count is used to count number of terms added, till it reaches N=5 (in this example)
• The same count value is also added to the sum variable to get the sum of the terms

Use of range() function:


The range( ) function generates a sequence of values. It has following forms:
▪ range( UL ): Will generate sequence from 0 to UL – 1
Example: range( 4 ) will generate the list of values 0, 1, 2, 3
▪ range( L1, L2 ): Will generate sequence from L1 to L2 – 1 in increments of 1
Example: range( 2, 8 ) will generate the list of values 2, 3, 4, 5, 6, 7
▪ range( L1, L2, ST ): Will generate a sequence from L1 to L2  1 in gaps of ST
For +ve step value, numbers will go up from L1 up to L2 – 1 :
Example: range( 3, 19, 4 ) will generate the list of values 3, 7, 11, 15
For -ve step value, numbers will go down from L1 up to L2 + 1 :
Example: range( 16, 2, -3 ) will generate the list of values 16, 13, 10, 7, 4
Examples of use of range() function:
1. range( 0, 5 ) → 0, 1, 2, 3, 4
2. range( 5, 11 ) → 5, 6, 7, 8, 9, 10
3. range( -4, 2 ) → -4, -3, -2, -1, 0, 1
4. range( 0, 8, 3 ) → 0, 3, 6
5. range( 3, 15, 6 ) → 3, 9
6. range( 7, -2, -3 ) → 7, 4, 1
7. range( -10, -3, 3 ) → -10, -7, -4
USING for LOOP
The structure of a for loop is shown below: Working of for loop
• The loop variable (i) one by one takes the
values from the sequence, starting from the
first value in the sequence, up to the last
value
• After taking a value from the sequence into
the loop variable, the Body of the loop is
executed
• After that the next value from the sequence
is taken and the Body of the loop again
executed
• After taking the last value from the
sequence, the Body of the loop is executed
The working of the above for loop is shown below:
for the last time

Example-1: Program to print first n even numbers

Example-2: Program to print even numbers up to num (input by user)


Use of special expression to calculate new terms of any series and get the series summation of any series
To Calculate:
• New Terms of a series (AP, GP, Mixed, e, Sin, Cos, Ln, Factorial, Power)
• To get the Series Sum of a series (AP, GP, Mixed, e, Sin, Cos, Ln)
• To get the Series Product of a series (Factorial, Power)
The form of the expression within the loop body will be:

Thus, for any New Term calculation it will be like:


TERM = TERM  VALUE [  Can be any arithmetic operator like +, -, *, / ]
E.g. Term = Term + CD (for AP series with common difference)
Term = Term * CR (for GP series with common ratio)
• For any Series Sum calculation, it will be: SUM = SUM + TERM
• For any Series Product calculation, it will be: PRODUCT = PRODUCT * TERM
• For any Alternate Sign series calculation, it will be: SIGN = SIGN * (-1)

Example-3: Consider the A.P. series: 3, 7, 11, 15, 19, 23, … up to n terms
First Term = 3 and Common Difference = 4

Example-4: Consider the G.P. series: 2, 6, 18, 54, 162, … up to n terms


First Term = 2 and Common Ratio = 3
Example-4: To get sum of natural numbers:
Sum = 1 + 2 + 3 + 4 + 5 + … + n

Example-5: To calculate a series product like calculating the Factorial of a number:


factorial(n) = 1 * 2 * 3 * … (n-2) * (n-1) * n

Example-6: Printing sum of following series upto n terms: ex = 1 + x1/1! + x2/2! + x3/3! + x4/4! + … up to n terms
Number System
Number Systems
• A Number System deals with counting objects
• It is used to express numbers using symbols
Positional Value System
• In this type of number system, the position of a digit in the number gives the actual value of that digit in
the number.
• The Decimal Number System that you learnt in school is an example of such a system
• For example, consider the decimal number 777
• Here each 7 has a different value based on its position in the number:
▪ The leftmost 7 has the value 700
▪ The middle 7 has the value 70 and
▪ The rightmost 7 has the value 7

Converting from One Number System to Another:


Based on how the counting is done, mathematicians have used different sets of digits to do the counting
• When using such a positional-value system, the number of unique digits present in the number system
is called the BASE or RADIX of the number system
• Based on the BASE value, we have different number systems
• The four common number systems are discussed in the next slide
Converting from Binary to Hex: Fractional Numbers Converting from Hex to Binary: Fractional
Numbers

Converting from Octal to Hexadecimal: Whole Number & Fraction


STEPS: 1. Convert from Octal to Binary
2. Convert from Binary to Hexadecimal
Converting from Hexadecimal to Octal: Whole Number & Fraction
STEPS: 1. Convert from Hexadecimal to Binary
2. Convert from Binary to Octal

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
Software Concepts
Software: Set of instructions necessary to operate the computer hardware

Types of Software: Depending upon the nature of the work, computer software can be divided into two main
categories. These are System Software and Application Software
▪ System software include software that are used to run the computer and manage the different resources
of a computer. These help in the proper and easy use of the computer system and its maintenance. In
general, system software is much closer to the actual hardware than the application prog
▪ Application software are user developed programs that are made to carry out some specific jobs. One can
have application software that can be used to process a payroll file, solve a set of equations for a scientific
application, process language, or used for doing graphic designing. These can be tailor-made software
serving a specific purpose or general-purpose software developed for some general use.
Operating System: It is the most important system software, which acts as a link between the hardware and
the user. The user interacts with application programs, which in turn interact with the computer hardware
through the Operating System (OS). Examples of different Operating Systems are DOS, Windows, Linux, Unix,
MacOS etc.
The different functions of an Operating System are:
1. File Management: Create, Edit, Copy, Move, Rename, Delete Files/Folders
2. Process Management: Manage the simultaneous working of applications
3. Device Management: Manage the working of Input and Output Devices
4. Memory Management: Manage allocation of Memory to different Processes
5. Command Interpretation: Interpret command from apps and take actions
6. Security Management: Securing user accounts using username & password
Library and Utility Programs: These are common set of library programs that are used to do certain utility jobs
that include finding files, compressing files, sorting files, disk defragmenter programs, anti-virus programs etc.
These programs are usually a part of the utility functions provided by an Operating System
Tailor-made software: These are written for specific purposes like stock management, school management, hospital
management, payroll calculation etc.

General purpose software: These include utility software that are used to do common and general jobs. These
software include feature rich packages like MS Office for doing word processing, spreadsheet processing,
database handling, and presentations; Adobe Smart Suite for doing image processing and DTP; AutoCAD for doing
computer aided designs, Electronic Mailing, etc.
Difference between Interpreter & Compiler

BOOLEAN ALGEBRA
Boolean algebra deals with mathematical analysis of logical statements
▪ First a set of initial assumptions are made called postulates
▪ Based on these postulates next a truth table is prepared
▪ The table shows the relation between all possible input logic possibilities and the corresponding output
logic
▪ Based on this Truth Table, a digital circuit may then be designed
▪ Boolean Algebra has two basic values/states i.e. True and False
▪ True is represented by the digit 1
▪ False is represented by the digit 0
▪ It also has a set of basic operators like OR, AND, NOT, that work on these states to give a resultant output
1. Logical OR Operation:
The OR operation is denoted by the ‘+’ operator and is used to indicate Logical Addition. The Output of a logical
OR operation is True if at least one of the conditions involved in the operation is True
For example, Suppose you want to have dinner at a restaurant and you prefer either Chinese or Continental
food only. The following truth table can help us decide if we can visit a particular restaurant or not as per our
choice

2. Logical AND Operation:


The AND operation is designated by the ‘’ (dot) operator and is used to indicate a Logical Multiplication. The
output of a logical AND operation is True if and only if all the conditions involved in the operation are True
For example, you need both Hydrogen and Oxygen to form water. To put the possibility of forming water in a
tabular form:
3. Logical NOT (Complement) Operation: Used to invert a Logic
The NOT or complement operation is designated by a bar ‘ ̅ ’ as A̅ or by a prime as A' placed over the variable
and is used to indicate a Logical Complement. It is a unary operation i.e. needs a minimum of one variable to
act upon.
For example, the logical output for the statement dissimilar charges attract can be given as:

Concept of Truth Tables


• If we represent logical statements with variable names like normal algebra, then we can create Truth
Tables showing the relationship between the possible logical inputs and the corresponding logical
outputs of a compound logical statement.
• A Truth Table of n input variables will have at the most 2n possible combinations of logics and will have 2n
number of rows.
Example: A 4 variable Truth Table will have 24 i.e. 16 number of rows

Drawing Truth Tables


Let us draw the truth table for a compound logical statement with 3 variables, for the following Logical
Expression:
Example-1: F1 = A+B.C [ total variable = 3, hence 23 = 8 rows ]

NOTE: AND operation has higher priority over OR operation. Hence, we have done B.C operation first
̅.C+B.C̅ [ total variable = 3, hence 23 = 8 rows ]
Example-2: F2 = A

Example-3: F3 = A.C + B . ̅̅̅̅̅


A.B [ total variable = 3, hence 23 = 8 rows ]

The following Rules can be used to work with Boolean Expressions:

Proof of Some of the Rules: Proof using Truth Tables


Proof of Some of the Rules: Proof using Algebraic Method

De Morgan’s Rules
• Sum Theorem: The complement of the logical sum of two variables X and Y is equal to the logical product
of the individual complements of the variables.
Thus ̅̅̅̅̅̅
X + Y = X̅ ∙ Y̅ , in general, W
̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅
+X+Y+Z+…=W ̅ ∙ X̅ ∙ Y̅ ∙ Z̅ …

• Product Theorem: The complement of the logical product of two variables X and Y is equal to the logical
sum of the individual complements of the variables.
̅̅̅̅̅̅
Thus X ∙ Y = X̅ + Y̅, in general, W
̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅̅
∙X∙Y∙Z∙…=W ̅ + X̅ + Y̅ + Z̅ + …

Proof of De Morgan’s Rules using Perfect Induction:

De Morgan’s Theorem and Principle of Duality


• De Morgan’s theorems indicate a basic duality in any Boolean expression
• If a Boolean expression can be proved to be true then, its pair or dual obtained by complementing the
expression and using the above theorems to simplify them, will also be true and need not be proved
separately
• This is because each AND operation has its equivalent OR operation and vice versa
• All the Boolean algebra rules show this duality i.e. the product rules can be derived from the sum rules
To find the dual:
• Replace an AND with OR, and an OR with AND
• Next, replace a ‘0’ by ‘1’ and a ‘1’ by ‘0’ i.e. by their complement
• Example-1: The dual of X + 1 = 1 will be X . 0 = 0 [by replacing OR by AND, and 1 by 0]
• Example-2: The dual of X + X̅ = 1 will be X . X̅ = 0 [by replacing OR by AND, and 1 by 0]
• Example-3: Dual of X+X=X will be simply XX=X [by replacing OR symbol by AND symbol]

You might also like