0% found this document useful (0 votes)
3 views39 pages

Control Structure (Flow of Control)[1]

The document outlines the flow of control in programming, detailing three main constructs: Sequence, Selection, and Loops/Iteration. It explains the use of conditional statements in Python, including Simple if, if..else, Multiple if..elif..else, and Nested if..if..else, along with examples for each. Additionally, it provides various programming tasks to demonstrate these constructs, focusing on user input and decision-making processes.

Uploaded by

Neelam Malviya
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)
3 views39 pages

Control Structure (Flow of Control)[1]

The document outlines the flow of control in programming, detailing three main constructs: Sequence, Selection, and Loops/Iteration. It explains the use of conditional statements in Python, including Simple if, if..else, Multiple if..elif..else, and Nested if..if..else, along with examples for each. Additionally, it provides various programming tasks to demonstrate these constructs, focusing on user input and decision-making processes.

Uploaded by

Neelam Malviya
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/ 39

FLOW OF CONTROL

1. SEQUENCE 2. SELECTION 3. LOOPS / ITERATION

start / REPETITIONS

input a)SIMPLE if b) SIMPLE if.. else c) MULTIPLE d) NESTED


if..elif..else if..if..else for loop while loop

process / calculations

Nested Loops
Output (concept)

stop
1.)SEQUENCE: This is the simplest type of programming construct which flows in a single direction and executes the commands
and statements one after the other in a sequence. It starts at one point, accepts Input, process’s it, display’s the output and ends at
the other point.
Note: This construct does not include any conditional statements.

Python Blocks and Indentation:


Python uses indentation for block as well as for nested block structures. Leading whitespace (spaces and tabs) at the beginning of a
statement is called indentation. In Python, the same level of indentation associate statements into a single block of code. The
interpreter checks indentation levels very strictly and throws up syntax errors if indentation is not correct. It is a common practice to
use a single tab for each level of indentation. Indentation of code always is followed up after a colon (:) symbol on the next line and
every statement within the same block should be at the same indentation level.

Note: For every additional nested block, it includes an extra tab (indentation)

Four types of Selection tools in Python are as follows:

2.) SELECTION: This construct of programming is mainly used along with conditional statements where in the user will chose out
of one to many choices available and python will execute the specific block of statement. It is comparatively more complex than the
Sequence construct. It provides 4 types of conditional statements as follows:

a) Simple if: It executes the Block of statements only if the specified condition evaluates to true, otherwise it does nothing.
Syntax:
if <condition>:
--------- block of statements (BOS)
---------
Example
if avgmarks>=90:
print(“Scholarship Granted”)
b) Simple if..else : It executes the Block of statement 1, if the specified condition evaluates to true, otherwise it executes the
Block of Statement 2.
Syntax:
if <condition>:
--------- BOS 1
---------
else:
---------- BOS 2
----------

Example:
if avgmarks>=90:
print(“Scholarship Granted”)
else:
print(“Scholarship Not Granted”)

c.) Multiple if..elif..else: In this construct, BOS1 shall be executed when condition1 evaluates to True, similarly BOS2 or BOS3
or so on shall be executed if condition 2 or condition 3 or so on evaluate to True respectively. “If” is used only with the
condition 1, and hence forth for all remaining conditions we use “elif”. If none of the above specified conditions evaluate
to True then the final BOSn shall be executed from the “else” block.
Syntax:
if <condition1>:
--------- BOS 1
---------
elif <condition2>:
---------- BOS 2
----------
elif <condition3>:
---------- BOS3
----------
.
.
else:
--------- BOS n
---------

Programs to be done using Multiple if..elif..else construct


1.) Program to accept any 3 nos and display the greatest among them.
2.) Program to accept any 2 numbers and an arithmetic operator (+,-,*,/,%,//,**) and display the calculated result. Also
display an error message if the user enters a wrong operator.
3.) Program to accept a digit (0 to 9) from the user and display it in words.
4.) Program to accept name and marks in any 5 subjects of a student from the user and calculate the total marks , average
marks and grade as follows:
Avg Grade
>=90 A
75-89 B
60-74 C
40-59 D
33-39 E
<33 F
5.) Program to accept marks in any 5 subjects from the user and calculate the total, average marks and result as follows:
No. of subjects Failed Result
0 Pass
1 Compartment
>1 Fail
6. Program to accept any 3 numbers from the user and display the highest number, middle number and the lowest number.
7. Program to accept a number from the user and display if it is a Positive, Negative or a Neutral number.
8. Program to accept the year and month (1-12) from the user and display the number of days in the month.
Solved Multiple if Program Source Code:
Program 1: Greatest of 3 numbers
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
if a>b and a>c:
print(a, "is the greatest number.")
elif b>a and b>c:
print(b, "is the greatest number.")
elif c>a and c>b:
print(c, "is the greatest number.")
else:
print("Any 2 or more numbers are equal")

Program 2: Arithmetic Calculator


n1=int(input("Enter first number:"))
n2=int(input("Enter second number:"))
op=input("Enter an arithmetic operator(+,-,*,/,%,//,**):")
if op=="+":
res=n1+n2
print("Sum of", n1, "and", n2, "is", res)
elif op=="-":
res=n1-n2
print("Difference of", n1, "and", n2, "is", res)
elif op=="*":
res=n1*n2
print("Product of", n1, "and", n2, "is", res)
elif op=="/":
res=n1/n2
print("Division of", n1, "and", n2, "is", res)
elif op=="%":
res=n1%n2
print("Modulus of", n1, "and", n2, "is", res)
elif op=="//":
res=n1//n2
print("Floor Division of", n1, "and", n2, "is", res)
elif op=="**":
res=n1**n2
print("Exponentiation of", n1, "and", n2, "is", res)
else:
print("Invalid Operator!!!")

Program 3: Digit to Word


dig=int(input("Enter a digit(0-9):"))
if dig==0:
print("ZERO")
elif dig==1:
print("ONE")
elif dig==2:
print("TWO")
elif dig==3:
print("THREE")
elif dig==4:
print("FOUR")
elif dig==5:
print("FIVE")
elif dig==6:
print("SIX")
elif dig==7:
print("SEVEN")
elif dig==8:
print("EIGHT")
elif dig==9:
print("NINE")
else:
print("Invalid DIGIT!!!")
Program 4: Grade Calculator
name=input("Enter your name:")
IP=int(input("Enter marks in Info:"))
BS=int(input("Enter marks in B.St.:"))
EC=int(input("Enter marks in Economics:"))
AC=int(input("Enter marks in Accounts:"))
ENG=int(input("Enter marks in English:"))
total=IP+BS+EC+AC+ENG
avg=(total/500) *100
if avg>=90:
grade="A"
elif avg>=75 and avg<=89:
grade="B"
elif avg>=60 and avg<=74:
grade="C"
elif avg>=40 and avg<=59:
grade="D"
elif avg>=33 and avg<=39:
grade="E"
else:
grade="F"
print("Total Marks obtained by", name, "is", total)
print("Average Marks obtained by", name, "is", avg)
print("Grade obtained by", name, "is", grade)

Program 5: Result Calculator


name=input("Enter your name:")
Acc=int(input("Enter marks in Accounts:"))
Eco=int(input("Enter marks in Economics:"))
Inf=int(input("Enter marks in IP:"))
Bst=int(input("Enter marks in B.St.:"))
Eng=int(input("Enter marks in English:"))
Total = Acc + Eco + Inf + Bst + Eng
avg=(total/500) *100
print()
print("Total Marks obtained by", name, "is", total)
print("Average Marks obtained by", name, "is", avg)
cnt=0
if Acc<33:
cnt=cnt+1
if Eco<33:
cnt=cnt+1
if Inf<33:
cnt=cnt+1
if Bst<33:
cnt=cnt+1
if Eng<33:
cnt=cnt+1

if cnt==0:
result="Pass"
elif cnt==1:
result="Compartment"
else:
result="Failed"
print("Result of", name, "is" ,result)

Program 6: Highest, Middle & Lowest Number


a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
c=int(input("Enter third number:"))
high =low= mid=0
if a>b and a>c and b>c:
high=a
mid=b
low=c
elif a>b and a>c and c>b:
high=a
mid=c
low=b
elif b>a and b>c and a>c:
high=b
mid=a
low=c
elif b>a and b>c and c>a:
high=b
mid=c
low=a
elif c>a and c>b and a>b:
high=c
mid=a
low=b
elif c>a and c>b and b>a:
high=c
mid=b
low=a
else:
print("Either 2 or all the 3 numbers are equal")
print("Highest number", high)
print("Middle number", mid)
print("Lowest number", low)

Program 7: Positive, Negative and Neutral Number


num=int(input("Enter any number:"))
if num>0:
print(num, "is positive")
elif num<0:
print(num, "is negative")
else:
print(num, "is neutral")

Program 8: Number of Days in a month (using Multiple if)


Year=int(input("Enter the 4 digit year:"))
Month=int(input("Enter the month(1-12):"))
if Month in [1,3,5,7,8,10,12]:
nod=31
elif Month in [4,6,9,11]:
nod=30
elif Month == 2 and Year % 4 == 0:
nod=29
elif Month == 2 and Year % 4 != 0:
nod=28
else:
nod=0
print("Invalid Month!!!")
print("Number of days in month", Month, "is", nod)

d.) Nested if..if..else: In this programming construct , we have an outer “If” condition which is followed by the inner “if”
condition. It will only execute the inner block (nested if block) only if the outer “if” condition evaluated to “True” otherwise it
will execute the following “elif” condition of the outer “if” and so on. In the below syntax BOS 1 shall be executed when both
<condition> 1 and 2 both evaluate to True. BOS2 shall be executed with <condition1> evaluates to “True” but <condition2>
evaluates to “False”. BOS3 shall be executed when <condidtion1> evaluates to “False” and <condition3 > evaluates to “True”.
Finally BOS n shall be executed when all outer “if” conditions evaluate to “False”.
Syntax:
if <condition1>: #OUTER IF
if <condition2>: #INNER IF
--------- BOS 1 #NESTED BLOCK IN RED
---------
else:
--------- BOS2
---------
elif <condition3>:
---------- BOS 3
----------
.
.
else:
--------- BOS n
---------
Programs to be done using Nested if..if..elif..else construct
Q.1 Program to accept a date from the user and validate it.
Q.2 Program to accept any 3 numbers from the user and display the highest/lowest of them.
Q.3 Program to accept a number from the user and display if it is a positive even number or odd number or if it is
a negative even or odd number, otherwise display the number is Neutral.
Q.4 Program to accept the year and month (1-12) from the user and display the number of days in the month.
#Program 5: To accept the Name, age, gender from the user and display the message as follows:
Gender Age Message
Male <=2 Infant Boy
3 to 12 Boy Child
13 to 19 Teenage Boy
20 to 30 Young Man
31 to 59 Adult Man
>=60 Old Man
Female <=2 Infant Girl
3 to 12 Girl Child
13 to 19 Teenage Girl
20 to 30 Young Girl
31 to 59 Adult Woman
>=60 Old Woman
Other Invalid Gender
#Program 6: To accept the employee name, department, basic salary and sales made from the user. Calculate and
display the commission and the gross salary as follows:
Department Sales Made Commission % of Sales Made

Sales(S) <=5000 5%

5001 to 15000 10%

15001 to 25000 15%

>25000 20%

Marketing(M) <=5000 4%

5001 to 15000 8%

15001 to 25000 12%

>25000 16%

Others Any 2%

Commission= comm/100 * Sales Made


Gross Salary = Basic Salary + Commission
Solved Nested if Program Source Code:
Program 1: Date Validation
d=int(input("Enter dd part of date (dd/mm/yyyy):"))
m=int(input("Enter mm part of date (dd/mm/yyyy):"))
y=input("Enter yyyy part of date (dd/mm/yyyy):")
valid="True"
if len(y)== 4:
if m>=1 and m<=12:
if m==1 or m==3 or m==5 or m==7 or m==8 or m==10 or m==12:
dd=31
elif m==4 or m==6 or m==9 or m==11:
dd=30
else:
if int(y)%4==0:
dd=29
else:
dd=28
else:
valid="False Month"
else:
valid="False Year"

if d<1 or d>dd:
valid="False Date"

if valid=="True":
print("Your date entered is", d,"/",m,"/",y )
elif valid=="False Date":
print("Your entered day is Invalid" )
elif valid=="False Month":
print("Your entered month is Invalid")
else:
print("Your entered year is Invalid")
Program 2a: Highest of 3 numbers
n1=int(input("Enter first number:"))
n2=int(input("Enter second number:"))
n3=int(input("Enter third number:"))
if n1>n2: # Outer If block
if n1>n3: # Inner If block
print(n1, "is greatest number.")
else:
print(n3, "is greatest number.")
elif n2>n3:
print(n2, "is greatest number")
elif n1==n2 or n1==n3:
print(“Any 2 or more numbers are equal”)
else:
print(n3, "is greatest number”)

Program 2b: Lowest of 3 numbers


n1=int(input("Enter first number:"))
n2=int(input("Enter second number:"))
n3=int(input("Enter third number:"))
if n1<n2: # Outer If block
if n1<n3: # Inner If block
print(n1, "is lowest number.")
else:
print(n3, "is lowest number.")
elif n2<n3:
print(n2, "is lowest number")
else:
print(n3, "is lowest number”)
Program 3: Positive or Negative Even/Odd
num=int(input("Enter a number:"))
if num>0:
if num%2==0:
res="Positive Even"
else:
res="Positive Odd"
elif num<0:
if num%2==0:
res="Negative Even"
else:
res="Negative Odd"
else:
res="Neutral"
print(num, "is", res, "number.")

Program 4: Number of Days in a month (using Nested if)


mon=int(input("Enter the month(1-12):"))
year=int(input("Enter the year(YYYY):"))
if mon==1 or mon==3 or mon==5 or mon==7 or mon==8 or mon==10 or mon==12:
days=31
elif mon==2:
if year%4==0:
days=29
else:
days=28
elif mon==4 or mon==6 or mon==9 or mon==11:
days=30
else:
print("Invalid Month!!!")
days=0
print("Number of days in ",str(mon)+"/"+str(year),"is", days)
Program 5: Name, Gender, Age (Message)
name=input("Enter the name:")
gender=input("Enter your gender(M/m for male and F/f for female):")
age=int(input("Enter your age:"))
if gender=="m" or gender=="M":
if age<=2:
msg="Infant Boy."
elif age<=12:
msg="Boy Child."
elif age<=19:
msg="Teenage Boy."
elif age<=59:
msg="Adult Man"
else:
msg="Old Man"
elif gender=="f" or gender=="F":
if age<=2:
msg="Infant Girl."
elif age<=12:
msg="Girl Child."
elif age<=19:
msg="Teenage Girl."
elif age<=59:
msg="Adult Woman"
else:
msg="Old Woman"
else:
msg="Invalid gender."
print()
print(name, "is" ,age, "years old", msg)
Program 6:
name=input("Enter Employee Name:")
dept=input("Enter S/s for Sales or M/m for Mktg:" )
bs=float(input("Enter Basic Salary:"))
sm=float(input("Enter Sales Made:"))
if dept == "S" or dept == "s":
if sm<=5000:
cp=5
comm=5/100*sm
elif sm<=15000:
cp=10
comm=10/100*sm
elif sm<=25000:
cp=15
comm=15/100*sm
else:
cp=20
comm=20/100*sm
elif dept == "M" or dept == "m":
if sm<=5000:
cp=4
comm=4/100*sm
elif sm<=15000:
cp=8
comm=8/100*sm
elif sm<=25000:
cp=12
comm=12/100*sm
else:
cp=16
comm=16/100*sm
else:
cp=2
comm=2/100*sm
gs = bs + comm
print("Commission obtained by", name, "is", comm, "@", cp,"%")
print("Gross Salary obtained by", name, "is", gs)
3.) ITERATION /LOOPS / REPETITIONS: This programming construct is the most powerful construct of programming as it repeats
a block of statements either till a range is accomplished or a condition is satisfied. Loops which repeat endlessly without
terminating are known as Infinite or Endless loops. There are 2 types of loops supported by Python as follow:
a.) for loop (Range or Sequence)
b.) while loop (condition)
a.) for loop (counting loops): This type of loop is a range or counter based loop which consists of a counter variable which is
initialized to the start value either in a Sequence or the range() function and then updated automatically to its next value in the next
iteration. The loop terminates when it reaches the end of the sequence or the end point in the range() function.
Syntax 1: Using Sequence: This for loop works with only sequence data type values. It will iterate (repeat) the BOS till it finds
characters within a string or elements within a list or tuple.
for <variable> in <sequence> : # A sequence can be a String , Tuple or a List
---------------------------- BOS
----------------------------
E.g.
for x in “PYTHON”:
print(x)
a=10
var= “PYTHON”
PYTHON
It is Incorrect.
In the above example, PYTHON shall be printed vertically and each character in the String is associated with two index numbers each
as demonstrated below
-6 -5 -4 -3 -2 -1 Backward Index
P Y T H O N

Forward Index 0 1 2 3 4 5

Str1= “Bond 007”


-8 -7 -6 -5 -4 -3 -2 -1
B o n d 0 0 7

0 1 2 3 4 5 6 7
Name= “Shohib”
e h o h i b

0 1 2 3 4 5
Str1= ‘Hello Friend’
H e l l o F r i e n d
0 1 2 3 4 5 6 7 8 9 10 11
E.g.
for y in [‘a’,’e’,’i’,’o’,’u’]:
print(y)
-5 -4 -3 -2 -1 Backward Index
a e i o u
Forward Index 0 1 2 3 4

#Program to accept a string from the user and display the number of characters within the string.
s=input("Enter a String:")
cnt=0
for x in s:
cnt+=1
print(s, "contains", cnt, "characters.")
print()

#Program to accept a string from the user and count the number of vowels and consonants in it.
s=input("Enter a String:")
v=0
c=0
for x in s.lower():
if x in “aeiou”:
v+=1
elif x==" ":
continue
else:
c+=1
print("No. of Vowels is", v)
print("No. of Consonants is", c)
Syntax 2: using range( ) function : This syntax is used with the range() function which evaluates the loop from start value till the stop
value – 1(exit) and by default increments the counter variable by 1. It can increment the counter variable value either by more than
1 or also decrement it.
Syntax:
for <variable> in range( <start>, <stop/exit>, [updation] ) :
--------------------------------- BOS
---------------------------------
E.g.
for x in range(1,11) :
print(x)
for x in range(2,11,2) :
print(x)
for x in range(11,2,-2) :
print(x)
#Program to accept a string from the user and display it in reverse
S=input("Enter a String:")
revS=""
for i in range(len(S)-1,-1,-1):
revS=revS + S[i]
print("The reversed string is", revS)

Working:
S=
Y A S H
0 1 2 3
revS = “”
I revS
3 H
2 HS
1 HSA
0 HSAY
-1------------→ EXIT
# Write a program to accept a range from the user and display the square of odd numbers and cube of even nos within the range.
s=int(input("Enter a start value:"))
e=int(input("Enter a end value:"))
for x in range(s,e+1):
if x%2==0:
print("The cube of", x, "is", x**3)
else:
print("The square of", x, "is", x**2)

# Write a program to accept a range from the user and display the sum of first even and odd numbers within the range.
# E.g. if the range is 1 to 10, then odd numbers between 1 to 10 are 1+3+5+7+9=25 and the even numbers are 2+4+6+8+10=30
s=int(input("Enter a start value:"))
e=int(input("Enter a end value:"))
evensum=0
oddsum=0
for x in range(s,e+1):
if x%2==0:
evensum = evensum + x
else:
oddsum = oddsum + x
print("Sum of Even Numbers is", evensum)
print("Sum of Odd Numbers is ", oddsum)

Working:
s e x evensum oddsum x%2==0
1 10 1 0 0 .F.
2 2 1 .T.
3 6 4 .F.
4 12 9 .T.
5 20 16 .F.
6 30 25 .T.
7 .F.
8 .T.
9 .F.
10 .T.
11 → exit the loop
# Program to accept a positive number from the user and display its factorial
#(E.g. num=5 then factorial = 1x2x3x4x5=120, or 5x4x3x2x1=120)
num=int(input("Enter a Number:"))
if num<0:
print("Cannot get factorial of a negative number!!!")
elif num==0:
print("Factorial of 0 is 1")
else:
f=1
for i in range(num,0,-1):
f *= i
print("The factorial of", num, "is", f)

# Program to accept a end limit from the user and display the following series:
# a.) 0 ,1 ,1 ,2, 3 , 5, 8, 13, 21......, n (Fibonacci series))
n=int(input("Enter the limit:"))
f=-1
s=1
for i in range(1, n+1):
t=f + s
print(t, end=",")
f, s = s, t

Working
n i f s t o/p
6 1 -1 1 0 0,1,1,2,3,5,
2 1 0 1
3 0 1 1
4 1 1 2
5 1 2 3
6 2 3 5
7 3 5
'
# b.) 0 , 6 , 24 , 60 , 120, 210, ......, n
# 1**3-1 , 2**3-2, 3**3-3 , 4**3-4 , 5 6
n=int(input("Enter a Limit:"))
for i in range(1,n+1):
print(i**3-i, end=",")
print()

# c.) 0 , 3 , 8 , 15 , 24 , 35 , 48, ...... , n


# 1**2-1, 2**2-1, 3**2-1, 4**2-1
n=int(input("Enter a Limit:"))
for i in range(1, n+1):
print(i**2-1, end=",")

#Program to display the multiplication table of any number accepted from the user:(using for loop)
num=int(input("Enter a number:"))
for i in range(1,11,1):
print(num, "x", i, "=",num*i)

#Program to accept a number from the user and display if it is Unique, prime or composite. (E.g. 1 is Unique, 3 is Prime and 6 is Composite)
#(Eg 0 is neither prime nor composite.)
num=int(input("Enter a number:"))
if num==0:
print(num, "is neither prime nor composite.")
elif num==1:
print(num, "is unique.")
else:
prime=True
for i in range(2,num):
if num % i == 0:
prime=False
break
if prime==True:
print(num, "is prime.")
else:
print(num, "is composite.")
#Program to accept a range from the user and display the sum of all the numbers divisible by 'n' within the range.
(E.g. Range is 10-20, n is 3, then, 12+15+18=45)
s=int(input("Enter start value:"))
e=int(input("Enter end value:"))
n=int(input("Enter the divisibility number:"))
sum=0
if s<e:
for i in range(s, e+1):
if i % n == 0:
sum += i
print(i, "+")
print("Sum=", sum)
else:
print("Invalid range!!!")
print("Start value should be lesser than end value!!!" )

b.) while loop (condition loop): This is a condition-based loop where in the initialization, condition and updation statements are all
split into 3 different lines. The loop iterates until the conditions evaluates to True and terminates when the condition specified
becomes False. The updation statement is always the last statement in the block of statements within the loop.
Syntax:
<initialization>
while <condition>:
------------ BOS
------------
<updation>
E.g. Program to print 1 to 10
x=1
while x<=10:
print (x)
x=x+1

for x in range(1,11,1):
print(x)
#Program to display the multiplication table of any number accepted from the user:(using while loop)
num=int(input("Enter a number:"))
i=1 #initialization
while i<11: # condition
print(num, "x", i, "=", num*i)
i=i+1 #updation

# Program to accept a number from the user and display the sum of its individual digits (E.g. num=234 then sum = 2+3+4= 9 )
num=int(input("Enter any number:"))
sum=0
while num!=0:
dig=num % 10
sum=sum + dig
num=int(num/10)
print()
print("Sum of individual digits is", sum)

working:
num sum dig num!=0
234 0 4 .T.
23 4 3 .T.
2 7 2 .T.
0 9 .F.

# Program to accept a number from the user & display the product of its individual digits (E.g. num=234 then product = 2*3*4= 24)
num=int(input("Enter any number:"))
prod=1
while num!=0:
dig=num % 10
prod=prod*dig
num=int(num/10)
print("Product of individual digits is", prod)
# Program to accept a number from the user and display it in reverse. (E.g. num=234 the result=432)
num=int(input("Enter any number:"))
rev=0
while num!=0:
dig=num % 10
rev=rev*10+dig
num=int(num/10)
print("Reverse is", rev)

Working
num rev dig num!=0
234 0 4 T
23 4 3 T
2 43 2 T
0 432 F

#Program to accept a number from the user and display if it is a Palindrome or not. (E.g. num=234 result="Not a Palindrome", num=232 result="Palindrome")
num=int(input("Enter any number:"))
temp=num
rev=0
while num != 0:
dig=num % 10
rev=rev*10+dig
num=int(num/10)
print("Reverse of", temp, "is", rev)
if rev==temp:
print(temp, "is a Palindrome.")
else:
print(temp, "is not a palindrome")

#Program to accept a number from the user and display if it is an Armstrong number or not. (E.g. num=153 1**3+5**3+3**3 = 1+125+27=153
result="Armstrong" , num=232 2**3+3**3+2**3 = 8+27+8 =43 result="Not Armstrong")
num=int(input("Enter any number:"))
temp=num
sum=0
while num!=0:
dig=num % 10
sum=sum + dig**3
num=int(num/10)
if temp==sum:
print(temp, "is an Armstrong number.")
else:
print(temp, "is Not an Armstrong number.")

#Program to accept a number from the user and display if it is a Perfect number or not. (6=1+2+3=6 is Perfect no whereas 8 = 1+2+4=7 is not Perfect no.)
num=int(input("Enter any number:"))
sum=0
x=1
while x<=num/2:
if num % x==0:
sum=sum + x
x+=1
print()
if num==sum:
print(num, "is a Perfect number.")
else:
print(num, "is Not a Perfect number.")

Nested loops: A loop may contain another loop inside it. A loop inside another loop is called a nested loop. For every one iteration of the Outer
loop, the inner loop iterates its full range or till the condition is satisfied.

Generalized Syntax:
<outer loop> :
<inner loop> :
-------- inner BOS
-------- outer BOS
__________
__________
E.g. Print the following structure j
*
** 1 2 3 4 5
*** 1 *
**** i 2 * *
*****
3 * * *
for i in range(1,6):
for j in range(1, i+1): 4 * * * *
print("*",end="") 5 * * * * *
print()

i j
1 1
2 → Exit j
2 1
2
3 → Exit j
3 1
2
3
4 → Exit j
4 1
2
3
4
5 →Exit j
5 1
2
3
4
5
6 → Exit j
6 Program terminates → Exit i
# Program to input the character and number of rows and print the following structure using nested loops
ch=input("Enter any character:")
rows=int(input("Enter the number of rows:"))
for i in range(1,rows+1):
for j in range(1,i+1):
print(ch,end="")
print()

1
22
333
4444
55555

for i in range(1,6):
for j in range(1,i+1):
print(i,end="")
print()

1
12
123
1234
12345

for i in range(1,6):
for j in range(1,i+1):
print(j, end="")
print()

54321
4321
321
21
1
for i in range(5,0,-1):
for j in range(i,0,-1):
print(j,end="")
print()

0
12
345
6789

k=0
for i in range(1,5):
for j in range(1,i+1):
print(k,end="")
k+=1
print()

9876
543
21
0

k=9
for i in range(4,0,-1):
for j in range(1,i+1):
print(k,end="")
k-=1
print()

5
45
345
2345
12345
for i in range(5,0,-1):
for j in range(i,6):
print(j,end="")
print()

A
BB
CCC
DDDD
EEEEE

y=1
for x in ["A","B","C","D","E"]:
print(x*y)
y+=1

or

for x in range(65,70):
for y in range(65,x+1):
print(chr(x),end="")
print()

ASCII=American Standard Code for Information and Interchange


A to Z = 65 to 90
a to z = 97 to 122
0 to 9 = 48 to 57

A
AB
ABC
ABCD
ABCDE
for x in range(65,70):
for y in range(65,x+1):
print(chr(y),end="")
print()

a
ab
abc
abcd
abcde

for x in range(97,102):
for y in range(97,x+1):
print(chr(y),end="")
print()

aaaaa
bbbb
ccc
dd
e

abcde
abcd
abc
ab
e

abcde
bcde
cde
de
e
onmlk
jihg
fed
cb
a

k=111
for i in range(5,0,-1):
for j in range(1,i+1):
print(chr(k),end="")
k-=1
print()

eeeee
dddd
ccc
bb
a

a
bc
def
ghij
klmno
pqrstu

k=65
for i in range(1,7):
for j in range(1,i+1):
print(chr(k),end="")
k+=1
print()
JUMP statements:
Statements which move the control to another part of the execution point (statement) from the current statement are knows as Jump
statements. Python provides different types of jump statements as follow:
a.) break
b.) continue
c.) return
d.) pass

a.) break: This keyword is a jump statement which alters the normal flow of execution as it terminates the current loop and resumes execution
of the statement following that loop.
E.g. #Program to demonstrate the use of break statement in loop
num = 0
for num in range(10):
num = num + 1
if num == 8:
break
print('Num has value ' + str(num))
print('Encountered break!! Out of loop')

output:
Num has value 1
Num has value 2
Num has value 3
Num has value 4
Num has value 5
Num has value 6
Num has value 7
Encountered break!! Out of loop

b.) continue: This keyword is also another type of jump statement in which the control skips the execution of remaining statements inside the
body of the loop for the current iteration and jumps to the beginning of the loop for the next iteration. If the loop’s condition is still true, the
loop is entered again, else the control is transferred to the statement immediately following the loop.
# Program to demonstrate the use of continue statement.
num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value ' + str(num))
print('End of loop')
output:
Num has value 1
Num has value 2
Num has value 4
Num has value 5
Num has value 6
End of loop

Find the output of the following code:


i.) sum=0
for x in range(10,0,-2):
if x % 4 == 0:
print(“Increment skipped!!!”)
continue
elif x % 3==0:
print(x)
print(“Loop terminated!!!”)
break
else:
sum=sum+x
print(“Sum=”,sum)
Working:
sum x
0 10
10 8
6
Output
Increment skipped!!!
6
Loop terminated!!!
Sum=10

ii) for x in [“apple”, “orange”, “banana”, “mango”, “grapes”, “pear”]:


if x== “banana”:
continue
elif x== “grapes”:
break
else:
print(x,end= “=>”)

iii) sum=0
for x in (33,11,22,9,12,15,6):
if x%3!= 0:
continue
if x%4 == 0:
break
sum=sum+x
print (sum)
sum x o/p
0 33 42
33 11
42 22
9
12

c.) return: This jump statement is used to return the value back to the calling program from the function or the method and the
control starts executing the following statements in the calling program.
d.) pass: This jump statement is also a keyword which is used to ignore the block of statements from executing anything. It is also
known as an empty statement.

Find the output:


1)
country = 'INDIA'
for i in country:
for j in [3]:
print (i*j,end="")
print()

2)
i = 0; sum = 0
while i < 9:
if i % 4 == 0:
sum = sum + i
i=i+2
print (sum,i)

3)
i = 0; sum = 0
while i < 9:
if i % 4 == 0:
sum = sum + i
i=i+2
print (sum,i)

sum i<9 o/p


0 0 .T. 12 10
2 4 .T.
4 12 .T.
6 .T.
8 .T.
10 .F.
Q2. Find o/p of the following python code: (2)
a,b,c=10,12,15
b%=a
a**=b
X=a//b+c%b+b**2
print(a,b,c,sep=`:`,end= “#” )
print(“X=”,x)

a b c X
10 12 15 55
100 2

o/p
100:2:15 # X=55

Find the o/p:


x,x = 4,7
y,y = x+7,x-7
x,y=y-x,x+y
print(x,y)

x y
7 0
-7 7
o/p
-7 7
Q4. Rewrite the output after removing all the error (2)
S=`pura vida'
S1=S[0:5] => pura_ (“underscore denotes a space”)
S2=S[5:] => vida
S3=S1*S2 =>error (should replace the * with + operator then o/p will be pura vida)
S4=S2+'3’ => vida3
S5=S1+3 => error (should replace 3 with “3” and then o/p will be pura 3)

Q5. Predict and write the output : (2)


L=[`p’ ,'r',[ ],'b','l','e','m']
L[2:3]=[]
print(L) => ‘p’, ‘r’, [ ], ‘b’ , ‘l’ , ‘e’, ‘m’
L[2:5]=[]
print(L) => ‘p’, ‘r’, [ ], ‘e’ , ‘m’

Q7. Find and write the o/p (3)


X=[“F”,66,”QE”,15,”S”,34]
Y=0
Z= “”
A=0
for c in range(1,6,2):
Y+=c
Z=Z+X[c-1]+'$’
A+=X[c]
print(Y,Z,A) ==➔ 9 F$QE$S$ 115
Y A c Z
0 0 1 F$QE$S$
1 66 3
4 81 5
9 115 7

You might also like