[go: up one dir, main page]

0% found this document useful (0 votes)
14 views50 pages

Revision Tour XI - Strings - Loops HH

The document provides a comprehensive overview of Python programming concepts for Class XII, including iterative computation, control flow, loops, and string operations. It covers various types of loops (terminating and non-terminating), flowcharts, and examples of using loops for calculations and string manipulations. Additionally, it introduces nested loops and exercises for calculating simple and compound interests.
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)
14 views50 pages

Revision Tour XI - Strings - Loops HH

The document provides a comprehensive overview of Python programming concepts for Class XII, including iterative computation, control flow, loops, and string operations. It covers various types of loops (terminating and non-terminating), flowcharts, and examples of using loops for calculations and string manipulations. Additionally, it introduces nested loops and exercises for calculating simple and compound interests.
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/ 50

Computer Science

CLASS-XII (Code No. 083)


Revision of the basics of Python covered in Class XI

2021-2022 PART-2
Unit 1: Computational Thinking and Programming - 2
REVIEW PART-2
Revision of the basics of Python covered in Class XI.

● Notion of iterative computation and control flow: for(range(),len()), while,


using flowcharts, suggested programs: calculation of simple and compound
interests, finding the factorial of a positive number etc.

● Strings: Traversal, operations – concatenation, repetition, membership;


functions/methods–len(), capitalize(), title(), upper(), lower(), count(),
find(), index(), isalnum(), islower(), isupper(), isspace(), isalpha(), isdigit(),
split(), partition(), strip(), lstrip(), rstrip(), replace(); String slicing.

2
Loops
Repetition of a statement or a set of statements, finite or infinite number of
times is known as a loop. We can also use the term terminating loop for the
loop, which allows the statement/statements to execute finite number of times
and non-terminating loop, which allows a statement/statements to execute
infinite number of times.

Happening of Morning -> Noon -> Evening -> Night again and again without
termination is an example of non-terminating loop.

Digging a 10 Feet deep hole by a labourer. Dig -> Measure -> 10 Feets?
It is an example of terminating loop. NO YES
STOP

3
Flow Chart - Loop
START N=1 START N=int(input("N:"))
ASSIGN
while True: INPUT
C=1
N as 1 print(N) N while C<=N:
N=N+1 print(C)
PRINT ASSIGN
N C as 1 C=C+1

N ← N+1 IS
C<=N? STOP
NO
YES
PRINT Printing integers 1 to N
C

C ← C+1
Printing integers 1 onwards 4
while loop Printing first N number of
Even numbers
SYNTAX CODE 1.1

while <Condition>: N=int(input("N:"))


N:3
<Statement1> C=1 2
<Statement2> while C<=N: 4
6
: print(2*C)
<StatementN> C=C+1 Printing 5 times of N till N is
not assigned as 0
else:
<Statement_1> while True:
<Statement_2> N=int(input("N:")) N:3
15
: if N==0: N:7

PS KP
break 35 R
N:0
print(5*N) D
OPTIONAL
5
while loop Find N:60
multiples of x Five
CODE 1.2 5 and N:23
terminate Re-Try
while True: with 0 N:0 Printing Common
N=input("N:") x Fives over Factors of N and
if N=="0": M integers
break
elif int(N)%5==0: CODE 1.3
print("x Five") N:16
N=int(input("N:"))
else:
M=int(input("M:")) M:24
print("Re-Try")
I=1 1
print("x Fives over") 2
while I<=min(N,M):
if N%I==0 and M%I==0: 4
print(I) 8
I=I+1
6
while loop Checking if the number
CODE 1.5 N is Prime or Not Prime
CODE 1.4
N=int(input("N(>1):")) If the loop
N=5346 C=2 continues till the
while N!=0: while C<N: last step and
print(N%10) if N%C==0: terminates with
N//=10 condition C<N,
print("Not Prime") statement with else
break will get executed

ience
6 C=C+1 and if it breaks with
4 else: if statement with
print("Prime No.") else will not get
3
executed
5
Printing digits of N N:16 N:31
in reversed order Not Prime Prime No. 7
for loop
Printing first N number
SYNTAX CODE 2.1 of Even numbers

for <v> in <collection>: N=int(input("N:")) N:3


<Statement1> for C in range(N): 2
<Statement2> 4
print(2*(C+1)) 6
:
<StatementN> CODE 2.2 N:10
else: 1
<Statement_1> N=int(input("N:")) 4
for C in range(1,N+1,3): 7
<Statement_2>
print(C) 10
:

Printing a Sequence 1,4,7,...


OPTIONAL till an integer N
8
for loop
CODE 2.3 CODE 2.4

for I in range(4,0,-1): for I in range(4,0,-1):


print(I) print(5-I,I)

4 1 4
3 2 3
2 Printing increasing and 3 2
1 decreasing numbers 4 1

for I in range(1,5):
Printing a Sequence print(I,5-I)
4,3,2,... till an integer N>

9
for loop
CODE 2.5 CODE 2.6

for I in range(40,0,-8): for I in range(5,0,-1):


print(I) print(8*I)

40 40
32 32
24 24
16 16
8 8

Printing a Sequence Printing a Sequence


40 32 24 16 8 40 32 24 16 8
(Alternative 1) (Alternative 2) 10
for loop
CODE 2.7 CODE 2.8

for C in range(65,69): for C in range(0,4):


print(chr(C)) print(chr(65+C))

A A
B Printing Sequence of B
C alphabets in ascending order C
D D

Printing Sequence of TWO


alphabets in ascending order ALTERNATIVES
11
for loop
CODE 2.9 CODE 2.10

for C in range(5): for C in range(5):


print('*'*(C+1)) print('*'*(5-C))

* *****
** ****
*** ***
**** **
***** *

Printing triangle of * Printing triangle of *


ascending descending
12
for loop
CODE 2.11 CODE 2.12

N=int(input("N:")) N=int(input("N:"))
S=0 S=0
for I in range(1,N+1): for I in range(1,N+1):
S+=I S+=(2*I-1)
print("Sum=",S) print("Sum=",S)

N:5 N:5
Sum= 15 Sum= 25

Finding & printing Sum of Series Finding & printing Sum of Series
1+2+3+ … + N 1+3+5+ … till Nth Term
13
for loop
CODE 2.13 CODE 2.14

N=int(input("N:")) N,M=input("N:"),input("M:")
F=1 P=1
for I in range(1,N+1): N,M=int(N),int(M)
F*=I for I in range(1,M+1):
print(N,"!=",F) P*=N
print(N,"^",M,"=",P)
N:7 N:4
7 != 5040 M:5
4 ^ 5 = 1024
Finding & printing
Finding & printing N raised to
Factorial of N
power M using for loop 14
for loop
CODE 2.15 CODE 2.16

N=int(input("N:")) N=int(input("N:"))
F,S=1,0 U=int(input("U:"))
for I in range(1,N+1): T,S=1,0
F*=I for I in range(1,N+1):
S+=F T*=U
print("Sum=",S) S+=T
print("Sum=",S) N:4
N:4 U:2
Sum= 33 Sum= 30

Finding & printing sum of series Finding & printing sum of series
1!+2!+3!+...+ N! U1+U2+U3+...+ UN 15
for loop
CODE 2.17 CODE 2.18 Finding HCF/GCF and LCM of
2 integers N and M
N=int(input("N:")) N=int(input("N:"))
for C in range(1,N+1): M=int(input("M:"))
if N%C==0: HCF=1
print(C,end=",") for C in range(1,min(N,M)+1):
if N%C==0 and M%C==0:
HCF=C
print("HCF=",HCF)
Finding and printing
print("LCM=",N*M/HCF)
all the factors of N
N:8 N:30
N:54
M:20 M:12
1,2,3,6,9,18,27,54,
HCF=4 HCF=6
LCM=40 LCM=60
16
for loop Finding & printing first N
terms of fibonacci series
CODE 2.19 CODE 2.20

X=float(input("X:")) F,S=0,1
N=int(input("N:")) N=int(input("N:"))
S,PX=0,1 for I in range(N):
for I in range(1,N+1):
print(F,end=",")
PX*=X/I
S+=PX F,S=S,F+S
print("Sum=",S)
N:10
X:1.5 0,1,1,2,3,5,8,13,21,34,
N:5
Sum= 3.46171875 Finding sum of series with N Terms
X + X2/2!+X3/3!+....
17
for else loop
Loop Terminated in the middle
so else did not execute
CODE 2.21
I:13
I=int(input("I:")) 13 1
for J in range(1,10,2): 10 3
print(I,J) 7 5
if I==J: 4 7
print("Common Point") I:11 1 9
break 11 1 No common point
I-=3 8 3 Over
else: 5 5
print("No common point") Common Point
print("Over") Over
Loop continued till last
so else got executed
18
Nested loop (Loop inside the Other Loop)
SYNTAX

while <Condition1>: for <Var1> in <Collection1>:


while <Condition2>: for <Var2> in<Collection2>:
<Statement1> <Statement1>

for <Var> in <Collection>:


while <Condition>:
<Statement1>

while <Condition>:
for <Var> in <Collection>:
<Statement1>
19
Nested loop (Loop inside the Other Loop)
CODE 3.1 CODE 3.2

for C in range(1,5): for C in range(1,5):


for R in range(1,5): for R in range(1,5):
print(C,end="") print(R,end="")
print() print()

1111 1234
2222 1234
3333 1234
4444 1234

20
Nested loop (Loop inside the Other Loop)
CODE 3.3 CODE 3.4

for C in range(1,5): for C in range(1,5):


for R in range(1,C+1): for R in range(1,C+1):
print(C,end="") print(R,end="")
print() print()

1 1
22 12
333 123
4444 1234

21
Nested loop (Loop inside the Other Loop)
CODE 3.5 CODE 3.6

for C in range(4,0,-1): for C in range(4,0,-1):


for R in range(1,C+1): for R in range(1,C+1):
print(R,end="") print(C,end="")
print() print()

1234 4444
123 333
12 22
1 1

22
Nested loop (Loop inside the Other Loop)
CODE 3.7

N=int(input("N:")) N:5
for C in range(1,N+1): 1
print(" "*(N-C),end="") 12
for R in range(1,C+1): 123
print(R,end="") 1234
print() 12345

23
Nested loop (Loop inside the Other Loop)
CODE 3.8

while True: N:2


N=int(input("N:")) M:5
M=int(input("M:")) 2-3-4-5-
if N>=M: N:3
print("Stop!") M:7
break 3-4-5-6-7-
for C in range(N,M+1): N:6
print(C,end="-") M:1
print() Stop!

24
Nested loop (Loop inside the Other Loop)
CODE 3.9

while True: N:17


N=int(input("N:")) Prime No.
if N<=1: N:14
print("None!") Composite No.
break N:21
for C in range(2,N//2+1): Composite No.
if N%C==0: N:83
print("Composite No") Prime No.
break N:1
else: None!
print("Prime No")
25
Exercise A
To calculate simple interests for given Principle and Rate, with various time in
months in range of 1 month to 6 months

To calculate compound interests for given Principle and Rate, with various time
in months in range of 1 month to 6 months

26
String
String: It is immutable data type in Python. The content of string can be
enclosed inside a pair of single/double quote ' ' OR " ". It is the default type
entered by the user using input() function.

Examples of Strings Contents:


"AMAR"
"We are connected"
"123, ABC Colony"
'Jaya Sood, #34, Cross Junction, 133091'
"DAY + NIGHT = 24 HOURS"
"""WE ARE PART OF
THE GLOBAL AND UNITED WORLD"""
27
String - Input and Traversal
Txt=input("Text:") W E A R E O N E
print(Txt)
0 1 2 3 4 5 6 7 8 9
for T in Txt:
print(T,end=":")
print()
OUTPUT
L=len(Txt)
for i in range(0,L): Text:WE ARE ONE
print(Txt[i],end="*") WE ARE ONE
print() W:E: :A:R:E: :O:N:E:
for i in range(L-1,0,-2): W*E* *A*R*E* *O*N*E*
print(Txt[i],end="#") E#O#E#A#E#

28
String - membership operator

Operator Description Example

in It returns True, if a "E" in "PET"


variable/value is found in the
string.
not in It returns True, if a "BY" not in "BRIGHT"
variable/value is not found in
the string.

29
String - concatenation, repetition, membership

T1=input("Text1:") OUTPUT
T2=input("Text2:")
T3=T1+" "+T2 Text1:TRUTH
print(T3) Text2:WINS
T4=T1*2 TRUTH WINS
print(T1*2) TRUTHTRUTH
if T1 in T3: TRUTH part of TRUTH WINS
print(T1,"part of",T3) WINS not in TRUTHTRUTH
if T2 not in T4:
print(T2,"not in",T4)

30
String - capitalize(), title(), upper(), lower()

T=input("Text:") OUTPUT
T1=T.capitalize()
T2=T.title() Text:love ALL
Love all
T3=T.upper()
Love All
T4=T.lower() LOVE ALL
print(T1) love all
print(T2)
print(T3)
print(T4)

31
String - count()
Method:
count() - To return the number of occurrences of a substring in the given
string.
The count() function has one compulsory and two optional parameters.
Mandatory parameter: <Substring> – string whose count is to be found.
Optional Parameters:
<start> – starting index within the string from where the search starts.
<end> – ending index within the string where the search ends.
Example:
C=T.count("P") #return times of occurrence of P in T
CN=T.count("P",1,15)

32
String - count()

T=input("Story:") OUTPUT
ST=input("What to see?")
CN=T.count(ST) Story:the boy was playing
print(ST,end=" Found") with the dog of the house
print(CN,"Times") What to see?the
L=len(T) the Found 3 Times
CN=T.count(ST,L//2,L) the Found 2 Times
print(ST,end=" Found") in second half
print(CN," Times") of the string
print("in second half")
print("of the string")

33
String - find()
Method:

find() - To find the index of a substring in a string.

<Val>=<Str>.find(<Sub>[,<Start>[,<End>]])

<Start> - default value is 0 and it’s an optional argument.

<End> - default value is length of the string, it’s an optional argument.

# if the string is not found then the function returns -1

34
String - find()

T="ABCD213XYZABMN" OUTPUT
print(T.find('B'))
1
print(T.find('3XY')) 6
print(T.find('YZ', 0, 6)) -1
print(T.find('ZAB', 3)) 9
-1
print(T.find("213",6)) 10
print(T.find("AB",5))

35
String - index()
Method:

The index() method is similar to find() method for strings. The only
difference is that find() method returns -1 if the substring is not found,
whereas index() throws an exception.

<Val>=<Str>.index(<Sub>[,<Start>[,<End>]])

<Start> - default value is 0 and it’s an optional argument.

<End> - default value is length of the string, it’s an optional argument.

36
String - index()

T="ABCD213XYZABMN" OUTPUT
print(T.index('B'))
1
print(T.index('3XY')) 6
print(T.index('ZAB', 3)) 9
print(T.index("AB",5)) 10

ValueError
print(T.index("213",6))

37
String - isalnum(), islower(), isupper(), isspace(), isalpha(), isdigit()
Methods
isalnum() To check if string contains only alphabets/digits or not
islower() To check if string contains at least one lowercase letter and no
uppercase at all. Any alphabet from ‘a’ to ‘z’
isupper() To check if string contains at least one uppercase letter and no
lower case at all. Any alphabet from ‘A’ to ‘Z’
isspace() To check if string contains only space(s) or not
isalpha() To check if string contains only alphabets or not
isdigit() To check if string contains only digits or not
38
String - isalnum(), islower(), isupper(), isspace(), isalpha(), isdigit()
T1=" ";T2="1234" OUTPUT
T3="AB123";T4="ABC"
True False
T5="abc 456" True False
print(T1.isspace(),T5.isspace()) True True
print(T2.isdigit(),T3.isdigit()) True False
print(T3.isalnum(),T5.islower())
print(T4.isupper(),T3.isalpha())

39
String - split()
Method

split() To return a list of strings after breaking the given string with a
given separator.

<List>=<Str>.split(<Separator>[,<Maxsplit>])
Separator : String splits at this specified <Separator>. space is the default
separator.

Maxsplit : A number, to split the string into maximum of provided number of


times. If not provided then there is no limit.

40
String - split()

T='we are the world' OUTPUT


# Splits at space
['we', 'are', 'the', 'world']
print(T.split()) ['w', ' ar', ' th', ' world']
print(T.split('e')) ['w', 'ar', 'th', 'world']
['we a', 'e the wo', 'ld']
print(T.split('e '))
['we', 'the world']
print(T.split('r'))
print(T.split(' are '))

41
String - split()

T='we are the world' OUTPUT


# Splits at space
['we', 'are', 'the', 'world']
print(T.split())
['we are the world']
print(T.split(' ',0)) ['we', 'are the world']
print(T.split(' ',1)) ['we', 'are', 'the world']
['we', 'are', 'the', 'world']
print(T.split(' ',2))
print(T.split(' ',3))

42
String - partition()

Method

partition() To search for a specified string, and split the main string into
a tuple containing three elements.

<Tuple>=<Str>.partition(<Partition String>)

Partition String : A string that will partition the Str into three parts in a tuple.

43
String - partition()
T = "THE WORLD IS ROUND" OUTPUT

# 'IS ' part of T ('THE WORLD ', 'IS ', 'ROUND')


('THE WORLD IS ROUND', '', '')
print(T.partition('IS '))
('THE ', 'WORLD', ' IS ROUND')

# 'NOT' not part of T


print(T.partition('NOT '))

# 'WORLD' part of T
print(T.partition('WORLD'))

44
String - strip(), lstrip(), rstrip()

Methods

strip() To remove leading (spaces at the beginning) and trailing (spaces at


the end) characters. Space is the default leading character to remove

lstrip() To remove leading (spaces at the beginning) characters. Space is


the default leading character to remove

rstrip() To remove trailing (spaces at the end) characters. Space is the


default leading character to remove.

<Str>.strip(<Character>)
45
String - strip(), lstrip(), rstrip()

T=" MY STARS " OUTPUT


print("#",T.strip(),"#")
# MY STARS #
print("#",T.lstrip(),"#") # MY STARS #
print("#",T.rstrip(),"#") # MY STARS #
T="***MY STARS**"
print("#",T.strip("*"),"#") # MY STARS #
print("#",T.lstrip("*"),"#") # MY STARS** #
# ***MY STARS #
print("#",T.rstrip("*"),"#")

46
String - replace()

Method

replace() To replace a portion <Old> of string with another <New>. The


third parameter is optional as Count or number of occurrences to be replaced.
If the third parameter not specified, it will replace all the occurrence of <Old>
with <New>

<New Str>=<Str>.replace(<Old>,<New>,[<Count>])

47
String - replace()
T="Johny Johny Yes Papa" OUTPUT
S1=T.replace("Johny","Tony")
Tony Tony Yes Papa
print(S1) Tony Johny Yes Papa
S2=T.replace("Johny","Tony",1) Johny Johny Yes Daddy
print(S2)
S1=T.replace("Papa","Daddy")
print(S1)

48
String - String Slicing

String slicing helps in extracting a portion of a string with the help


of indexes.

<String>[<Start Index>,<End Index+1>,<Step>]

49
String - Slicing

T="SMILE IS FREE" OUTPUT


print(T[0:3])
SMI
print(T[4]) E
print(T[2:]) ILE IS FREE
SMILE IS
print(T[:9]) EERF SI ELIMS
print(T[::-1]) ML SFE
SMILE IS FREE
print(T[1:13:2])
print(T[::])

50

You might also like