Professional Documents
Culture Documents
XI Computer Science Gist-03
XI Computer Science Gist-03
Computer Science
Gist-3 of Lessons covered between 25/08/2023 to 03/11/2023
1. Loop (for loop continued):
Program to print the factors of a number:
The loop starts running from 1 and goes up to half the number (as
no factor can be more than half the number). Hence the for loop
is used to generate the numbers from 1 to num/2.
One by one the numbers from the range are used to divide num
and the remainder is checked. Whenever the remainder becomes
0, it means it is a factor, and that factor is printed.
Input a number and check if it is a perfect number. For a perfect number, the sum of the factors of the number
(including 1) is equal to the number itself. The program will print if it is a perfect number or not
The for loop starts running from 1 and goes up to half the number
num and generates the numbers from 1 to num/2.
When a factor is found (similar to the last problem) is added to the
sum. The final sum is compared with the number and if it is same,
then it is a perfect number.
Program to print the Fibonacci Series:
The first two terms of the series are fixed. Third term onwards, the terms are calculated by adding the previous two
terms of the series. The code starts with term1=0 and term2=1 i.e. the first two terms of the series. When the loop
runs, for i=1, the first fixed term i.e. term1 is printed and for i=2 the second fixed term i.e. term2 is printed. For i>2,
the term term3 is calculated by adding term1 and term2 and printed.
Next, both term1 and term2 are redefined for generating the next term of the series. Hence the next term1 is
formed by assigning the present term2 value and the next term2 is formed by assigning the present term3 value and
the loop continues to print the terms.
Remember: term1 = term2 = term3 for generating the next set of term1 and term2 values.
2. Use of break statement:
The break keyword in Python is used to forcibly come out of a loop. It is invariably used along with an if statement.
When the condition of the if statement is found to be True, the break statement is executed to come out of a loop
from that point. It is mainly used in programs, where you need to come out of a loop when some conditions get
satisfied within the body of the loop.
Input a range from LL to UL. Next print the first multiple of 7 in that range of numbers.
The loop starts running from lower limit LL
and every time checks if the loop value is
divisible by 7. The moment the if condition is
found True, the if block statement prints the
first multiple of 7 and breaks out of the loop
i.e. comes out of the loop and the loop stops
5. USING while LOOP: Normally used when the number of iterations is not known beforehand
The structure of while loop is shown below: Working of while loop
• When the loop starts, the condition of the loop is
checked
• If the condition is found to be True, the loop BODY (the
indented bock below the loop header) is executed
• When the end of the BODY is reached, the control goes
back to the loop header to check the condition
• If the condition is again found to be True, then BODY is
executed again
• This continues, till the condition becomes False
• The loop ends after checking the condition then
The code while True runs infinitely as long as user inputs an invalid value
which is not in the given range. When a valid value in range is input, the
if condition becomes True and the loop breaks out.
Required HCF
In this calculation, the final HCF is derived when the result of the division gives a zero remainder. In that case, the
corresponding divisor is the HCF. Otherwise, if the remainder of division is non-zero, the dividend and divisor are re-
defined and the division is repeated. For the next division, the current divisor is made the next dividend and the
current remainder is made the next divisor.
To start with, the while loop condition tests the first remainder. If it is non-zero, the loop condition is True and
indicates that the final HCF is not found. Hence, within the body of the loop, remainder is calculated and the next
dividend and divisor are re-defines as stated above.
The final divisor will give the required HCF as shown above. Note that the order in which the numbers are input is
not important. You will get the same result.
The above while loop runs as long as the value of the number is more than 0. Every time the loop runs, one digit
from the right of the number is extracted and then the right-most digit is removed using the floor division. In this
way the number gets reduced in value every time the loop runs and finally becomes 0. Then the loop condition
becomes False and the loop ends. In this type of application, no loop counter is used to count the iterations.
The program inputs a number and reverses it.
For input number 258, the loop works as follows:
The above while loop runs as long as the value of the number is more than zero as before. Every time the loop runs,
one digit from the right of the number is extracted and then the right-most digit is removed using the floor division.
The extracted digit is added to a summation variable named rev after multiplying the summation variable rev by 10.
The variable rev is used to build the reverse number with every run of the loop.
The working on the loop for the number 258 is shown above. It shows how the reversed number is formed within the
variable rev.
Input a number and check if it is PALINDROME number or not. A palindrome number reads same from both ends.
Nested Loops:
• When a given loop is placed inside another loop, it is called a nested loop
• The inner loop is placed in the body of the outer loop as is called the nested loop
• You can place any type of loop within any other type of loop to form a nested loop as shown below:
j
Here the outer for loop generates the numbers from
lower limit LL to upper limit UL. The inner for loop then
takes a number from the outer loop and checks if it is
prime or not. If so, only then it prints the prime number.
Input a number and check if it is such that the number is equal to the sum of the factorial of the digits of the
number or not.
Program to find all Armstrong Numbers within a range of numbers (while within for).
Here the outer for loop generates the numbers from 100 to 999.
Each number is stored in num. The inner while loop then takes num
from the outer loop and checks if it is an Armstrong number or not.
An Armstrong number is a number where the cube of the digits of
a number add up to the number. The while loop extracts one digit
at a time from the number and adds the cube of the digit to the
Sum variable. When all the digits are extracted, it is checked if the
sum formed is equal to the original number. If so, it is printed.
Program to find the hcf of a set of numbers (while within while).
• The outer loop counts the number of lines using i. As there are n lines,
hence i goes from 1 to n
• The inner loop counts the number of stars in a line
• Number of stars in a line is equal to the line number
• As the line number is given by i, hence the inner loop runs i number of times. Hence j goes from 1 to i
• Here the outer loop counts the number of lines using i. As n lines are to be printed, hence i goes from 1 to n
• The inner loop prints the digits in a line and number of digits in a line is equal to the line number
• Hence the inner loop runs i number of times and j goes from 1 to i
• As the digit that gets printed is same as line number, hence we print the value of i
Left Aligned NUMBER Triangle-2
The following code inputs the number of lines n and prints the number pattern:
• Here also the outer loop counts the number of lines using i. As n lines are to be printed hence i goes from 1 to n
• The inner loop prints the digits in a line and number of digits in a line is equal to the line number. Also the digits
that get printed are from 1 to the line n umber i
• Hence the inner loop runs i number of times and j goes from 1 to i
• As value of j is same as the digit that gets printed, hence we print the value of j
Left Aligned ALPHABET Triangle
• Here also the outer loop counts the number of lines using i. As n lines are to be printed hence i goes from 1 to n
• The inner loop prints alphabets in a line and number of alphabets in a line is equal to line number. Hence inner
loop runs i number of times and j goes from 1 to i
• As the ASCII value of ‘A’ is 65 and the alphabets are same in a line, hence we have to take i and use the ASCII
value in the loop range for the inner loop
Right Aligned STAR Triangle:
• The outer loop counts the number of lines using loop variable i
• The first inner loop, the k loop, is used to count and print the blank spaces
• The second inner loop, the j loop as usual counts and prints the stars
NOTE: All the shapes discussed for left aligned triangles can be done for right aligned triangles by simply including
the k loop for printing the spaces before the j loop in each of those codes.
Inverted STAR Triangle:
• With a small change we can draw all the inverted shapes using the same code that we had learnt for the
upright shapes
• Simply change the outer loop header range for the corresponding upright triangle code keeping everything else
same, and the same code will work:
NOTE: All the shapes discussed for left aligned and right aligned triangles can be done for inverted triangles by
simply changing the i loop range to range(n, 0, -1). The remaining code will remain the same.
• A diamond can be printed by first printing an upright pyramid, followed by the code for an inverted pyramid.
• So, if n lines are to be printed, print the upright pyramid with n//2+1 number of lines (p here), and print the
inverted pyramid with n//2 number of lines (q here).
• While drawing the inverted pyramid, an extra blank space is to be added before the symbols. Hence the k loop
for the inverted shape has range as range(1, q-i+2).
STRING HANDLING
1. Some General Properties of Strings:
• Python stores a sequence of characters as a string within a pair of single or double quotes like ‘abc’ or “abc”
• String is an immutable data type. You cannot change a string in place. When a string is changed, a new string is created
• An index system is used to access each character in the string. The index of the first
character is zero (0) and the index of the last character is 1 less than the string length
• You put the index in a pair of square brackets [ ] to access a character
• Strings can be single line or multiline
2. Traversing a String:
Traversing means accessing every character of a string from one end to the other.
river = ‘Ganges’
for i in range( -1, -len(river)-1, -1 ):
print( river[ i ] )
3. Basic String Operations:
Two basic operations possible on a string.
String Concatenation: The + Operator is used to join two strings side by side. It creates a New String by joining the two strings
Examples: s1 = ‘Da’ + ‘Vinci’ s1 = ‘DaVinci’
s2 = ‘221’ + ‘B’ s2 = ‘221B’
s3 = ‘12’ + ‘45’ s3 = ‘1245’
You cannot add a number to a string. You have to convert a number to a string before you can add it to a string.
Examples: s4 = ‘Year’ + 2020 Will produce ERROR
s5 = ‘Year’ + ‘2020’ s5 = ‘Year2020’
s6 = ‘Year’ + str(2020) s5 = ‘Year2020’
String Replication: The * Operator is used to replicate a string side by side. It creates a New String by repeating a string.
Examples: s1 = ‘Ta’ * 4 s1 = ‘TaTaTaTa’
s2 = 3 * ‘Rat’ s2 = ‘RatRatRat’
s3 = ‘ABC’ * 0 s3 = "" (null string)
s4 = ‘12’ * 5 s4 = ‘1212121212’ (not 60)
s5 = ‘ABC’ * ‘PQR’ ERROR, as you cannot multiply 2 strings
4. Using Membership Operator:
There are two string membership operators in and not in. Operator in returns True if a substring is present in a string. Operator
not in returns True if a substring is NOT present in a string
Examples: ‘a’ in ‘India’ True (as ‘a’ is present in ‘India’)
‘rat’ in ‘rattle’ True (as ‘rat’ is present in ‘rattle’)
‘in’ in ‘beginning’ True (as ‘in’ is present in ‘beginning’)
‘M’ in ‘Sodium’ False (case does not match for ‘m’ and ‘M’)
‘bat’ not in ‘tribunal’ True (as ‘bat’ is not present in ‘tribunal’)
‘by’ not in ‘goodbye’ False (as ‘by’ is present in ‘goodbye’)
Examples: s = ‘therefore’
sub = ‘re’
sub in s True (here the values in the variables are compared)
Example: Program to count the number of vowels in a string.
The for loop extracts all the characters one by one from the input string word and
assigns them to the loop variable c. The character c is then compared with each of
the characters in the string ‘AEIOUaeiou’. If a match is found, then the condition
becomes True and the counter count is incremented by 1. The final count value is
5. String Comparison Operators printed outside the loop.
Python compares strings using the dictionary order. The ASCII value of characters in a string is used to decide upon the order.
A → Z has ASCII values 65 → 90 and a → z has ASCII values 97 → 122.
Strings that will occur lower in the dictionary are given a lower value compared to strings that occur higher in the dictionary.
Hence CAPITAL letters are considered lesser than small letters. Accordingly, the string ‘Great’ is considered less than ‘great’.
Examples: print ( ‘top’ == ‘tap’ ) False
print ( ‘Bat' < ‘Mat' ) True
print ( ‘cattle' < 'catch’ ) False
print ( 'cat’ < 'catch’ ) True
print ( 'bat' < 'Battle' ) False
print ( ‘23' < ‘125' ) False
6. Use of ord() and chr() Functions:
• ord( ): This function is used to get the ASCII value of a character
• chr( ): This function is used to get the character for a given ASCII value
Examples showing the use of ord() and chr() functions.
Example: Program to modify a string by getting a character replaced by another character which is 2 characters ahead of the
given character.
The for loop extracts all the characters one by one from the input string word
and assigns them to the loop variable c. The ord(c) function then gets the ASCII
value of the character in c and adds 2 to it to get the ASCII value of the
character 2 characters ahead of the character in c. The chr() function then
reconverts the ASCII value to a character and adds it to the new string variable
newWord.
7. The use of String Slicing
Slice: A slice is a part of the string from the original string
Range: The slice is formed using a range of index. The slice starts from a starting index and takes all characters up to 1 less than
the ending index. The index used to get the range can be both +ve / -ve
Step: A third step parameter can be provided to skip values while choosing the elements of a slice. A positive step value skips
characters from left to right, while a negative step value skips characters from right to left of a string
Some examples of string slicing:
Note:
• When the starting index is not
given, it means index 0
• When the ending index is not
given, it means the length of the string
• When step value is not given, it means the default step value of +1
LOGIC GATES
• Modern circuits, based on Boolean logic, use different voltage levels to represent binary ‘0’ and ‘1’
• Usually, a 5V or a 12V DC supply is used to drive such circuits (available as ICs), with two different voltage
ranges used to represent ‘0’ and ‘1’
• When designed using electrical or electronic circuits, the logic functions are represented by specific block
diagrams known as logic gates
• Different Boolean operations are represented by different circuits
• Each such circuit is represented on paper using a specific symbol
• A logic gate has a single output whereas the inputs can vary from one (for NOT gate) to many
The Circuit Symbols and corresponding Truth Tables of different Logic Gates are given below:
There are two special types of gates called NAND gate and NOR gate. These are called UNIVERSAL GATES as any
digital circuit can be designed by using either NAND gates or NOR gates only.
Digital Circuits:
Representing a Boolean Sum Of Products (SOP) expression using the Basic Gates:
Example-1: F1 = AC + BC + AB
Representing a Boolean Product Of Sums (POS) expression using Basic Gates: Example-2: F2 = (A+B̅ ).(A
̅+B).(A+C)
Draw the following SOP circuit: Draw the following POS circuit
Draw the logic gate equivalent of the Boolean Draw the logic gate equivalent of the Boolean
̅C+A
function given by: f = A B ̅BC ̅+ABC ̅ ̅+B
function given by: f = (A+C)(A ̅ +C)(B+C)