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

Class XI

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

3. Use of continue statement:


The continue keyword in Python is used to skip certain iterations of a loop. It is invariably used along with an if
statement like break. When the continue statement is run, it skips the execution of the remaining part of the loop
and returns the control to the beginning of the loop for the next iteration. It is mainly used in programs, where you
need to skip full or part of the code in a loop body for some conditions.
Printing all the alphabets from capital A to small z.
The loop runs from 65 (ASCII for ‘A’) and goes up to 122 (ASCII for ‘z’). The
range of capital alphabets is from 65 to 90 and that of small alphabets from 97
to 122. Hence, there is a gap of 6 numbers in between. The if statement is
True only for these 6 numbers, and the continue statement skips remaining
part of loop body and takes control to beginning of the loop again for the next
when not iteration. Hence print () statement is not run for these values in between.
an alphabet

Printing the alternative form of the Fibonacci Series: 1, 1, 2, 3, 5, 8, 13, …


As the first two terms of the series are 1, 1, hence when the for loop
runs, for i<=2, the if condition is True and the program prints the value
1 each time. The continue statement inside the if block then takes the
program control back to the beginning of the loop by skipping the
portion after the if block.
For i>2, the condition i<=2 is False and the if block is not entered.
when Hence the continue statement is also not executed and the program
i>2 when i<=2
control executes the part after the if statement and calculates the
next term by adding the previous two terms.

REMEMBER: Code using continue can be replaced by proper use of


if-elif-else statements. Hence it is not something which is essential.
4. Use of loop else:
The loop else runs when an entire loop is executed without forcibly coming out of the loop using a break code. It is
aligned with the loop header with same indentation. The statements under the loop else get executed in case no
exception is found while running the original loop body and the loop runs fully till the end. Hence if break statement
executes, loop else will not execute and if break statement does not execute, loop else will execute.
Program to print first multiple of 12 in a range or print the number does not have a multiple of 12 in the range.
When a multiple is present in the range then
the if statement within the for loop becomes
True and prints the first multiple and breaks
out of loop as there is no need to check the
remaining numbers. Here loop-else does not
run. When no multiple is present in range,
then loop runs fully without running the break
statement. In that case the loop-else runs and
prints ‘No multiple in range’
Program to check if a number is prime or not.
The loop range is taken from 2 to num. Hence the factors generated will
be from 2 to (num-1). This eliminates 1 and itself for checking of prime.
The input number is divided by all numbers from 2 to (num-1). If num is
non-prime, then it will get divided by one of the numbers and give a 0
remainder. In that case the if block prints ‘Non-Prime’ and breaks out of
the loop as there is no need to check further. Loop-else does not run.
For a prime number, no factor will divide num and the if condition will
never be True. Hence the loop will run fully without running break. In
that case the loop-else will run and print ‘Prime number’.

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

Program to find Factorial of a Number using while loop


The program finds the factorial of a number using while loop. Unlike
for loop, the loop counter count is separately initialised to 1 by
count=1 statement. The fact variable is also initialised to 1 to start
with. The program is basically a series product of 1*2*3*4*…
When the loop runs, first the loop condition count<=num is checked. If
True the loop body is executed. There the count value is multiplied
with the present fact value to get the next fact value.
After that the loop counter is manually incremented by 1 by the
count+=1 statement and the control goes back to the beginning of the
loop and checks the condition again. This continues till the value of
count is less than or equal to num. Hence the loop runs a total of num
times. The final factorial is printed outside the loop.
Menu Driven Program: Simple Calculator Program that runs multiple times based on option input

The code while True gives a universally True


condition and the loop will run infinitely as
long as user gives option except 0. When
option given is 0, the break statement will
end the loop.
Program to input a marks value between 0 and 70 and print the percentage of marks received out of 70. The
program will not accept the input as long as the value is not within the range 0 to 70. THE PROGRAM IS USED TO
TEST FOR VALID INPUT

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.

Program to find the HCF of 2 numbers.


Algorithm to find HCF of two numbers using a while loop: Process to find the HCF of 55 and 20

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.

6. Getting individual digits of a whole number using while loop:


As we do not know beforehand how many digits are there in a number, we can use a while loop to extract the digits
one-by-one from the right till we reach the leftmost digit.
Algorithm to follow, to get the digits of a number, like num=268:
a. Extract the rightmost digit of number by doing modulo division by 10, and taking the remainder
Example: digit = num%10 = 268 % 10 → 8 (right-most digit extracted from the number)
b. Use this digit for the various calculations involved as per the problem given, like printing the digit
Example: print( digit ) → 8 (the digit can then be used for various operations and calculations)
c. Reduce the original number by doing a FLOOR DIVISION on the number by dividing it by 10
Example: next num = num//10 = 268 // 10 → 26 (reduced number with one digit less)
d. Repeat the process and go to step (a) with the reduced number as long as it is non-zero
Program to get the sum of the digits of any number:
For input number 485, the loop works as:

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.

The code first makes a copy of the number num to test,


in the variable copy. The number is then reversed and
stored in the variable sum using the copied value.
Finally, the reversed number in sum is compared with
the original number num. If they are same, then the
number is a palindrome. Otherwise, it is not.
Input a number and check if it is an ARMSTRONG NUMBER or not. An Armstrong number is a 3-digit number which
is equal to the sum of the cube of the digits of the number:

The code first makes a copy of the number num to test,


in the variable copy. The loop then extracts each digit
from the number, cubes it and adds it to the
summation variable sum using the copied value.
Finally, the sum is compared with the original number
num. If they are same, then the number is an
Armstrong number. Otherwise, it is not.
Note: The original number is copied as the number get
reduced to zero when the loop ends and hence cannot
be used for comparison after the loop 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:

1. Working of a nested loop:


Every time the outer loop runs
once, the inner loop runs fully.
Hence when the outer i-loop
runs once the inner j-loop runs 4
times and prints the pattern line
4 times.
As the outer i-loop runs a total
of 3 times, the 4-line pattern
gets printed 3 times as shown in
the output on the left.
Hence the combined loop-
system runs a total of 3*4 = 12
times.
2. Problems on nested loops:
Printing all prime numbers within a given range of numbers

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.

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.

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).

This checks if the user has input 0 for the variable


dvd. In that case the break statement ends the
outer loop. Before that, it stores the last divisor
into the variable hcf as the final hcf value.
The first number is input into the variable
This loop calculates the hcf of the two dvr before the loop. The second value dvd is
numbers stored in dvd (the dividend)
input inside the outer while loop.
and dvr (the divisor). The final hcf is
stored in the variable dvr. To stop the input, the user has to enter the
value 0 inside the loop, when the break
statement is executed to end the outer loop.
The second (nested) while loop is used to find the hcf between the values dvd and dvr and accordingly repeat the
division process till the remainder is 0 (the inner loop condition). The corresponding divisor dvr at the end when the
inner loop stops, will contain the latest hcf. Hence when the outer while loop starts again, the next value is input within
the variable dvd. The existing value of dvr (that contains the last calculated hcf) and the input value of dvd are then used
to calculate the next hcf.
7. Nested Loops: Printing Triangular Patterns using Nested Loop

Left Aligned STAR Triangle:

• 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

Left Aligned NUMBER Triangle-1:

• 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.

Upright STAR Pyramid:


• With a small change we can draw a Pyramid Shape by using the same code that we had learnt for the upright
shapes
• Simply change the inner loop header range for the right aligned upright triangle code keeping everything else
same, and the same code will work:
• The number of stars in a line goes as 1, 3, 5, 7, 9 etc. i.e. an A.P. series whose ith term is 2*i-1

Inverted STAR Pyramid:


• With a small change in the upright Pyramid code we can draw the for the inverted pyramid
• Simply change the outer loop header range for the upright pyramid code keeping everything else same, and
the same code will work:
STAR Diamond:
Printing a diamond with total n lines, where n>=3 and n is odd

• 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.

Method-1: Without using string Method-2: Using string index.


index. river = ‘Ganges’
river = ‘Ganges’ for i in range( len(river) ):
for c in river: print( river[ i ] )
print( c )

Working with Negative Index


A negative index system can also be used to work with a string
• The last character is given a negative index of -1
• The index decreases from right to left up to the first character, which has an index of –(string length)
• When Python sees a negative index, it adds the length of the string to the negative index to get the positive index

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)

You might also like