CPP Lab Manual
CPP Lab Manual
Ex. NoNo 1B
1A SUM OF FIRST
TO CHECK N NATURAL
WHETHER THENUMBERS
NUMBER IS
ODD OR EVEN
Date
Date
AIM:
To develop a problem analysis chart, algorithm, pseudocode and flow chart to check the number is odd
or even.
Phase Details
PSEUDOCODE :
BEGIN
INPUT number
IF number MOD 2 = 0 THEN
PRINT "The number is Even"
ELSE
PRINT "The number is Odd"
ENDIF
END
RESULT:
Thus, a problem analysis chart, algorithm, pseudocode, and flowchart are designed to check whether a
number is odd or even.
1
Ex. No 1C ELECTRICITY BILL
Date
AIM:
To draw a problem analysis chart, algorithm, pseudocode and flow chart to find the sum of first N
natural numbers.
Phase Details
PSEUDOCODE :
BEGIN
INPUT n
SUM = (n * (n + 1)) / 2
OUTPUT SUM
END
RESULT:
Thus, a problem analysis chart, algorithm, pseudocode, and flowchart are designed to find the sum of the
first N natural numbers.
2
AIM:
To develop a problem analysis chart, algorithm, pseudocode and flow chart for generating Electricity
bill.
Phase Details
To calculate the total electricity bill based on the number of units
Problem
consumed using slab-wise tariff rates.
ALGORITHM:
Step1: Start
Step 2: Declare total unit consumed by the customer using the variable unit.
Step 3: If the unit consumed less or equal to 100 units, calculates the total amount of electricity
Consumed = units*1.5.
Step 4: If the unit consumed between 100 to 200 units, calculates the total amount of electricity
Consumed = (100*1.5) + (unit-100) *2.5)
Step 5: If unit consumed between 200 to 300 units, calculates total amount of electricity
consumed = ((100*1.5) + (200-100) * 2.5+(units-200) *4).
Step 6: If unit consumed between 300-350 units, calculates total amount of electricity
consumed = ((100*1.5) + (200-100) * 2.5+(300-200) *4+(units-350) * 5)
Step 7: If the unit consumed above 350 units, fixed charge - 1500/-
Step 8: End
PSEUDOCODE :
3
BEGIN
READ unit
IF unit <= 100 THEN
amount ← unit * 1.5
ELSE IF unit <= 200 THEN
amount ← 150 + (unit - 100) * 2.5
ELSE IF unit <= 300 THEN
amount ← 150 + 250 + (unit - 200) * 4
ELSE IF unit <= 350 THEN
amount ← 150 + 250 + 400 + (unit - 300) * 5
ELSE
amount ← 1500
ENDIF
PRINT "Electricity Bill = ", amount
END
RESULT:
The problem analysis chart, algorithm, pseudocode, and flowchart have been developed to generate an
electricity bill.
4
VIVA QUESTIONS
1. How does designing an algorithm help detect logical errors before coding? (TCS)
An algorithm breaks the problem into small, testable steps before coding. This helps find missing
conditions or wrong assumptions early.
2. What are the advantages of using a flowchart in a complex billing system? (Infosys)
Flowcharts show the flow of calculations, decisions, and loops clearly. They make complex logic
easier to understand, debug, and discuss.
3. Why is it important to handle boundary conditions in electricity billing flowcharts?
(Capgemini)
Correct slab selection at unit boundaries (like 100, 200 units) avoids billing errors, customer
complaints, and legal issues.
4. How can loops be represented in a flowchart for retail billing with multiple items? (Cognizant)
By drawing an arrow from a decision block (“more items?”) back to item entry, repeating until no
more items are left.
5. Explain how decision blocks help compute three-phase AC current differently for star and
delta. (Accenture)
The decision block checks connection type; based on yes/no, applies the correct formula for either
star or delta.
6. What is the difference between sequential and conditional flow? (Wipro)
Sequential flow follows steps one after another. Conditional flow adds decision points, so the path
can branch based on conditions.
7. How can modular flowcharts help in large systems? (IBM)
Breaking a large system into smaller flowcharts makes design clearer, easier to test, and reuses
common sub-processes.
8. Why do we use iteration in scientific problems like sine series? (HCL)
The series adds multiple terms; iteration naturally shows repeated addition until the required
accuracy or term count.
9. Give an example of parallel processes in a billing flowchart. (Tech Mahindra)
Calculating discount and tax separately, then adding both to the subtotal before the final bill.
10. What challenge might appear when turning flowcharts into code? (Mindtree)
Flowcharts may not show low-level details like variable types, error checks, or data validation,
which must be added in code.
5
Ex. No 2A SWAP THE VALUES OF TWO VARIABLES
Date
AIM:
To write a Python program for exchange the values of two variables.
ALGORITHM:
Step 1: Start
Step 2: Input two variables a and b
Step 3: Swap values using tuple unpacking: a, b = b, a
Step 4: Output swapped values of a and b
Step 5: End
PROGRAM:
# Swapping without a temporary variable
a=5
b = 10
print("Before swap:")
print("a =", a)
print("b =", b)
# Swap
a, b = b, a
print("After swap:")
print("a =", a)
print("b =", b)
OUTPUT:
Before swap:
a=5
b = 10
After swap:
a = 10
b=5
RESULT:
Thus the program for swapping the values of two variables have been written and executed
successfully.
6
Ex. No 2B CIRCULATE THE VALUES OF N VARIABLES
Date
AIM:
To write a python program for circulating the values of n variables using function.
ALGORITHM:
Step 1: Start
Step2: Define a List named list.
Step 3: Get the input n value to rotate the values.
Step 4: Perform the following Step b=a[n:]+a[:n], using slice operator
Step 5: Print the rotated values.
Step 6: Stop
PROGRAM:
list=[1,2,3,4,5]
print ("Original list",list)
n=int(input("Enter the shift location")) #Shift 2 location
rotate_list=list[n:]+list[:n]
print("Rotate list",rotate_list)
OUTPUT:
Original List = [1, 2, 3, 4, 5]
Enter the shift location 2
Rotate list= [3, 4, 5, 1,2]
RESULT:
Thus the program for circulating the values of n variables has been written and executed successfully.
7
Ex. No 2C DISTANCES BETWEEN TWO POINTS
Date
AIM:
To write a python program for calculating the distance between two points.
ALGORITHM:
Step 1: Start
Step 2: Take a two points as an input from a user.
Step 3: Calculate the difference between the corresponding X-coordinates
Step 4: X2 - X1 and Y-coordinates. Y2 - Y1 of two points.
Step 5: Print the values
Step 6: Stop
PROGRAM:
import math
a=input("Enter first coordinate : ")
p1 = a.split(",")
b=input("Enter second coordinate : “)
p2 = b.split(",")
distance = math.sqrt( ((int(p1[0])-int(p2[0]))**2)+((int(p1[1])-int(p2[1]))**2) )
print("Distance between ", a,"and", b, "is",distance)
OUTPUT:
Enter first coordinate: 4,0
Enter second coordinate: 6,6
Distance between 4,0 and 6, 6 is 6.324555320336759
RESULT:
Thus the program for circulating the values of n variables has been written and executed successfully.
8
VIVA QUESTIONS
1. Explain why multiple assignment (a,b = b,a) works in Python but not in some languages.
(Infosys)
Python packs values into a tuple and unpacks them in one step, while some languages require a
temporary variable.
2. What happens if user input isn’t converted before calculations? (TCS)
Input returns strings; adding them joins them as text, e.g., '2'+'3'→'23' instead of numeric 5.
3. Why is floating point precision important in distance calculations? (Capgemini)
Small floating-point errors can matter in scientific or engineering applications where precise
distance is critical.
4. How do you handle exchanging values of more than three variables? (Wipro)
Use slicing or unpacking: a,b,c = c,a,b or lst = lst[1:] + lst[:1] to rotate values efficiently.
5. Give an example where using expression instead of statement helps. (IBM)
max_val = x if x>y else y replaces multi-line if-else with a concise expression.
6. What does dynamic typing allow when swapping variables? (Cognizant)
The same code can swap ints, floats, or strings without specifying types, thanks to Python’s
flexibility.
7. Explain difference between input() and raw_input() in Python 2. (HCL)
raw_input() returned a string; input() evaluated as Python code. Python 3 kept only the safe version.
8. How to avoid division by zero when calculating distance? (Accenture)
Add a check: if denominator or divisor is zero, handle separately or skip calculation.
9. Why is operator precedence important in expressions like a+b*c? (Tech Mahindra)
Multiplication has higher precedence, so b*c runs before adding to a. Wrong grouping changes the
result.
10. What happens if you mix string and number in an expression? (Mindtree)
Python raises a TypeError, because it can’t directly add or multiply different types without
conversion.
9
Ex. No 3A NUMBER PATTERNS
Date
AIM:
To write a Python Program for displaying the number pattern.
ALGORITHM:
Step 1: Start
Step2: Define the depth value.
Step 3: Outer loop will print number of rows.
Step 4: Inner loop will print the value of i for each iteration.
Step 5: Print number.
Step 6: Line after each row to display pattern correctly.
Step 7: Stop.
PROGRAM:
depth = 6
for number in range(depth):
for i in range(number):
print(number, end=" ")
print()
OUTPUT:
1
22
333
4444
55555
RESULT:
Thus the program for displaying the number pattern has been written and executed successfully.
10
Ex. No 3B INCREMENTING NUMBER PATTERN
PROBLEMS
Date
AIM:
To write a Python program for displaying the incrementing number pattern.
ALGORITHM:
Step 1: Start
Step 2: Initialize x=0 and perform the operation
Step 3: Reassign it x=x+1 to increment a variable value by 1.
Step 4: Print x then the output will appear
Step 5: The value of x is incremented by 1
Step 6: Stop
PROGRAM:
depth = 6
for number in range(1, depth):
for i in range(1, number + 1):
print(i, end=' ')
print( )
OUTPUT:
1
12
123
1234
12345
RESULT:
Thus the program for displaying the incrementing number pattern has been written and executed
Successfully.
11
Ex. No 3C PYRAMID PATTERN PROBLEMS WITH STARS
Date
AIM:
To write a python program for displaying pyramid pattern with star.
ALGORITHM:
Step 1: Start
Step 2: rows = input("Enter the number of rows: ")
Step 3: # Outer loop will print the number of rows.
Step 4: for i in range(0, rows):
Step 5: # This inner loop will print the stars.
Step 6: for j in range(0, i + 1):
Step 7: print("*", end=' ')
Step 8: # Change line after each iteration.
Step 9: print(" ")
Step 10: Stop
PROGRAM:
def pyramid(n):
for m in range(0, n):
for i in range(0, m+1):
print("* ",end="")
print("\n")
n=5
pyramid(n)
OUTPUT:
*
**
***
****
*****
RESULT:
Thus the program for displaying pyramid pattern with star has been written and executed successfully.
12
13
Ex. No 3D INVENTED SEMI-PYRAMID PATTERN
PROBLEM WITH DESCENDING ORDER OF
Date NUMBERS
AIM:
To write a program for printing invented semi-pyramid pattern problem with descending order of
numbers.
ALGORITHM:
Step 1: Start
Step 2: Define the depth value
Step 3: Reversed loop for downward inverted pattern
Step 4: Increment in count after each iteration
Step 5: Print number
Step 6: Start
PROGRAM:
depth = 5
for i in range(depth,0,-1): n = i
for j in range(0, i):
print(n, end=' ')
print("\n")
OUTPUT:
55555
4444
333
22
1
RESULT:
Thus the program for printing invented semi-pyramid pattern problem with descending order of
numbers has been written and executed successfully.
14
Ex. No 3E STAR PATTERN
Date
AIM:
To write a python program for displaying star pattern.
ALGORITHM:
Step 1: Start
Step 2: Read the n value
Step 3: Find k is used to print the space
Step 4: Outer loop to print number of rows
Step 5: Inner loop is used to print number of space
Step 6: Decrement in k after each iteration
Step 7: This inner loop is used to print stars
Step 8: Downward triangle Pyramid
Step 9: Output for downward triangle pyramid
Step 10: Inner loop will print the spaces
Step 11: Increment in k after each iteration
Step 12: This inner loop will print number of stars
Step 13: Stop
PROGRAM:
15
OUTPUT:
*
**
***
****
*****
******
*****
****
***
**
*
RESULT:
Thus the program for displaying star pattern has been written and executed successfully.
16
Ex. No 3F RIGHT-ANGLED TRIANGLE PATTERN
WITH SAME CHARACTER
Date
AIM:
To write a python program for displaying right angles triangle pattern with same character.
ALGORITHM:
Step 1: Start
Step 2: First, we get the height of the pyramid rows from the user.
Step 3: In the first loop, we iterate from i = 0 to i = rows.
Step 4: In the second loop, we print numbers starting from 1 to j, where j ranges from 0 to i.
Step 5: After each iteration of the first loop, we print a new line.
Step 6: Stop
PROGRAM:
def letter_range(start, end):
for i in range(start, end):
for j in range(65, i + 1):
print(f"{chr(j)}", end="")
print("")
letter_range(65, 75)
OUTPUT:
A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI
ABCDEFGHIJ
RESULT:
Thus the program for displaying right angles triangle pattern with same character has been written and
executed successfully.
17
18
Ex. No 4A IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USING LISTS
Date
VIVA QUESTIONS
AIM:
To write a python program for implementing real time/technical application using list.
19
ALGORITHM:
Step 1: Start
Step 2: Perform list operations like concatenation(+), repetition(*), membership(in) and slicing.
Step 3: Insert new element in list by using append() method.
Step 4: Insert another collection like list by using extend() method.
Step 5: Remove an element from list by using remove ().
Step 6: Clear the list by using list.clear() method.
Step 7: Stop.
PROGRAM:
list1=["newspaper","articles","books"]
list2=["e-paper","journals"]
print(list1+list2)
print(list1*2)
print("book" in list1)
item=input("Enter the new item to add to list")
list1.append("Magazines")
print("List after appending is",list1)
item=input("Enter the item to be removed from list")
list1.remove(item)
print("List after removing is",list1)
list1.extend(list2)
print("List after extending is",list1)
list1.pop()
print("List after popping is",list1)
list2.clear() print(list2)
OUTPUT:
['newspaper', 'articles', 'books', 'e-paper', 'journals']
['newspaper', 'articles', 'books', 'newspaper', 'articles', 'books'] False Enter the new item to add to
listmagazines
List after appending is ['newspaper', 'articles', 'books', 'Magazines'] Enter the item to be removed from
Listarticles
20
Ex. No 4B IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USING TUPLES
Date
RESULT:
Thus the above program to perform list operations was done and output was verified successfully.
AIM:
To write a python program for implementing real time/technical application using tuples.
21
ALGORITHM:
Step 1: Start
Step 2: Perform tuple operations like concatenation(+), repetition(*), membership(in) and slicing.
Step 3: Perform indexing in tuple by using index() method.
Step 4: Return number of elements in tuple by using count() method.
Step 6: Clear the tuple by using tuple.clear() method.
Step 7: Stop.
PROGRAM:
tuple1=("accelerator","brake","clutch") tuple2=("gear","mirror") print(tuple1+tuple2) print(tuple1*3)
print("brakes" in tuple1)
print("slicing in tuple",tuple1[1:]) item=input("Enter the element name")
print("total no of times",item,"is found in tuple2",tuple2.count(item)) print("Element",item," is found
in
tuple1 at",tuple2.index(item))
OUTPUT:
('accelerator', 'brake', 'clutch', 'gear', 'mirror')
('accelerator', 'brake', 'clutch', 'accelerator', 'brake', 'clutch', 'accelerator', 'brake', 'clutch')
False
slicing in tuple ('brake', 'clutch')
Enter the element namegear
total no of times gear is found in tuple2 1 Element gear is found in tuple1 at 0
RESULT:
Thus the above program to perform tuple operations was done and output was verified successfully.
22
VIVA QUESTIONS
23
Ex. 5A IMPLEMENTING REAL TIME /TECHNICAL
No APPLICATION USING SET
Date
AIM:
To write a python program for implementing real time/technical application using set.
ALGORITHM:
Step 1: Start
Step 2: Perform set operations like concatenation(+), repetition(*), membership(in).
Step 3: Insert new element in set by using add() method.
Step 4: Insert another collection like set by using update() method.
Step 5: Remove an element from set by using remove ().
Step 6: Clear the set by using set.clear() method.
Step 7: Stop.
PROGRAM:
set1={"perl","Python","C"}
set2={"C#","BASIC","C"} tuple1=("FORTRAN","COBOL")
print(set1|set2) print(set1&set2) print(set1-set2) item=input("Enter the new data") set1.add(item)
print("set after adding new item",set1) set1.update(tuple1)
print("set after updation",set1) item=input("Enter item to be removed") set1.remove(item) print(set1)
set1.clear() print(set1)
OUTPUT:
{'C', 'C#', 'perl', 'BASIC', 'Python'}
{'C'}
{'perl', 'Python'}
Enter the new datajava
set after adding new item {'C', 'perl', 'java', 'Python'}
set after updation {'FORTRAN', 'Python', 'C', 'COBOL', 'perl', 'java'} Enter item to be removedperl
{'FORTRAN', 'Python', 'C', 'COBOL', 'java'}
set()
RESULT:
Thus the above program to perform set operations was done and output was verified successfully.
24
Ex.No 5B IMPLEMENTING REAL TIME
/TECHNICAL APPLICATION USING
Date DICTIONARIES
AIM:
To write a python program for implementing real time/technical application using dictionaries.
ALGORITHM:
Step 1: Start
Step 2: Perform dictionary operations like adding new element to dictionary.
Step 3: Update dictionary with another collection of data.
Step 4: Display the items in dictionary using items() method.
Step 5: Search an element in dictionary by using key value.
Step 6: Stop.
PROGRAM:
dict1={1:"gear",2:"brake",3:"clutch"}
dict2={5:"mirror"}
print(dict1.items())
flag=0
for key,value in dict1.items():
print(key,"->",value)
print("Adding new value")
key=input("Enter new key")
value=input("Enter new value")
dict1[key]=value print("Dictionary after adding new item",dict1.items())
print("Updating dictionary")
dict1.update(dict2)
print("Dictionary after updation",dict1.items())
key1=input("Enter key to search")
for key,value in dict1.items():
if(key==key1):
flag=1
print(key,"->",value)
if(flag==0):
print("Search item not found")
dict1.update({7:"glass"})
print(dict1.items())
print(dict1.keys())
25
dict1.pop(2)
print(dict1.items())
print(dict1.clear())
OUTPUT:
dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch')])
1 -> gear
2 -> brake
3 -> clutch Adding new value Enter new key6
Enter new value wheel
Dictionary after adding new item dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch'), ('6', 'wheel')])
Updating dictionary
Dictionary after updation dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch'), ('6', 'wheel'), (5, 'mirror')])
Enter key to search 7
Search item not found
dict_items([(1, 'gear'), (2, 'brake'), (3, 'clutch'), ('6', 'wheel'), (5, 'mirror'), (7, 'glass')])
dict_keys([1, 2, 3, '6', 5, 7])
dict_items([(1, 'gear'), (3, 'clutch'), ('6', 'wheel'), (5, 'mirror'), (7, 'glass')]) None
RESULT:
Thus the above program to perform dictionary operations was done and output was verified
successfully.
26
27
VIVA QUESTIONS
1. Why are sets useful for storing unique items? (TCS)
Sets automatically remove duplicates, ensuring each item appears only once.
28
Ex. No 6A FACTORIAL OF A NUMBER
Date
AIM:
To write a python program for finding factorial of number using function.
ALGORITHM:
Step 1: Start
Step 2: Read a number n
Step 3: Initialize variables: i = 1, fact = 1
Step 4: if i<= n go to Step 4 otherwise go to Step 7
Step 5: Calculate fact = fact * i
Step 6: Increment i by 1 (i=i+1) and go to Step 3
Step 7: Print fact
Step 8: Stop
PROGRAM:
def factorial(num):#function definition fact=1
for i in range (1, num+1):#for loop for finding factorial
fact=fact*i return fact
number=int(input("Please enter any number to find factorial: "))
result=factorial(number)
print("The factorial of %d = %d"%(number,result))
OUTPUT:
Please enter any number to find factorial: 6
The factorial of 6 = 720
RESULT:
Thus the program for finding factorial of number has been written and executed successfully.
29
Ex. No 6B AREAS OF SHAPES
Date
AIM:
To write a python program for finding areas of shapes.
ALGORITHM:
Step 1: Start.
Step 2: Get the input shape name from user.
Step 3: Call the function with specified shape name.
Step 4: Display the calculated result.
Step 5: Stop
PROGRAM:
def calculate_area(name):
name = name.lower()
if (name == "rectangle"):
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l*b
print(f"The area of rectangle is {rect_area}.")
elif(name == "square"):
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"The area of square is {sqt_area}.")
elif(name == "triangle"):
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area =0.5 * b * h
print(f"The area of triangle is {tri_area}.")
elif(name == "circle"):
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print(f"The area of circle is {circ_area}.")
elif(name == 'parallelogram'):
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
para_area = b * h
print(f"The area of parallelogram is {para_area}.")
else:
print("Sorry! This shape is not available")
30
print("Calculate Shape Area")
shape_name=input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find: square
Enter square's side length: 4
The area of square is 16.
RESULT:
Thus the program for finding area of shapes has been written and executed successfully.
31
Ex. No 6C LARGEST NUMBERS IN A LIST
Date
AIM:
To write a python program for finding the largest number in a list using function.
ALGORITHM:
Step 1: Get inputs from the user
Step 2: Assign first element into variable max
Step 3: initialize i=0.
Step 4: if (i<len(list)) then goto Step 5 else goto step 7
Step 5: if (list[i]>max) then max=list[i]
Step 6: increment i value by 1 and goto step 4
Step 7: Print the output
Step 8: End
PROGRAM:
def max_num_in_list( list ):
max = list[ 0 ]
for i in range(0,len(list)):
if list[i] > max:
max = list[i] return max print(max_num_in_list([8,105,63,7]))
OUTPUT:
105
RESULT:
Thus the program for finding the largest number in a list has been written and executed successfully.
32
VIVA QUESTIONS
1. Why use functions in Python? (TCS)
They help reuse code, make programs modular, and reduce repetition.
33
Ex. No 7A STRING REVERSE
Date
AIM:
To write a python program for displaying string reverse pattern.
ALGORITHM:
Step 1: Start
Step 2: Read the string from the user
Step 3: Calculate the length of the string
Step 4: Initialize rev = " " [empty string]
Step 5: Initialize i = length - 1
Step 6: Repeat until i>=0:
rev = rev + Character at position 'i' of the string i = i – 1
Step 7: Print rev
Step 8: Stop
PROGRAM:
def reverse_string(str):
str1 = "" for i in str:
str1 = i + str1 return str1
str = "python programming"
print("The original string is: ",str)
print("The reverse string is",reverse_string(str))
OUTPUT:
The original string is: python programming
The reverse string is gnimmargorpnohtyp
RESULT:
Thus the program for displaying string reverse pattern has been written and executed successfully.
34
Ex. No 7B PALINDROMES
Date
AIM:
To write a python program to check given string is palindrome or not.
ALGORITHM:
Step 1: Start
Step 2: Read the string from the user
Step 3: Calculate the length of the string
Step 4: Initialize rev = " " [empty string]
Step 5: Initialize i = length - 1
Step 6: Repeat until i>=0:
Step 6.1: rev = rev + Character at position 'i' of the string
Step 6.2:i = i – 1
Step 7: If string = rev
Step7.1: Print Yes"
Step 8: Else:
Step8.1: Print "No"
Step 9: Stop
PROGRAM:
def isPalindrome(str):
str1=""
for i in range(0,len(str)):
str1=str[i]+str1
if (str==str1):
return True
else:
return False
s = input("Enter the value")
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
OUTPUT:
Enter the value mom Yes
35
RESULT:
Thus the program to check whether given string is palindrome or not has been written and executed
successfully.
36
Ex. No 7C CHARACTER COUNTS
Date
AIM:
To create a python program to count the character in a string.
ALGORITHM:
Step 1: Define a string.
Step 2: Define and initialize a variable count to 0.
Step 3: Iterate through the string till the end and for each character except spaces, increment the count
Step 4: To avoid counting the spaces check the condition i.e. string[i] != ' '.
PROGRAM:
str1 = input("Please Enter your Own String : ") total = 0 for i in range(len(str1)):
total = total + 1
print("Total Number of Characters in this String = ", total)
OUTPUT:
Please Enter your Own String : python
Total Number of Characters in this String =6
RESULT:
Thus the program for counting the character in a string has been written and executed successfully.
37
Ex. No 7D REPLACING CHARACTERS
Date
AIM:
To write a python program to replace the string with another.
ALGORITHM:
Step 1: Start
Step 2: Get one input string from user.
Step 3: Get one character to replace in string from user.
Step 4: Using string replace() change the old character to new one.
Step 5: Print the modified string.
Step 6: Stop.
PROGRAM:
str1 = input("Please Enter your Own String : ")
ch = input("Please Enter your Own Character : ")
newch = input("Please Enter the New Character : ")
str2 = str1.replace(ch, newch)
print("\nOriginal String : ", str1)
print("Modified String : ", str2)
OUTPUT:
Please Enter your Own String: Hello world
Please Enter your Own Character: rl
Please Enter the New Character: r
Original String: Hello world
Modified String: Hello word
RESULT:
Thus the program for replacing the string with another string has been written and executed
successfully.
38
VIVA QUESTIONS
39
Ex. No 8A PANDAS
Date
AIM:
To write a Pandas program to add, subtract, multiple and divide two Pandas Series.
ALGORITHM:
Step 1: Start.
Step 2: Create two pandas series.
Step 3: Perform numeric calculation like adding series, subtracting series, multiplication of series and
dividing series.
Step 4: Print the result.
Step 5: Stop.
PROGRAM:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 9]) ds = ds1 + ds2 print("Add two Series:") print(ds) print("Subtract two
Series:") ds = ds1 - ds2 print(ds)
print("Multiply two Series:") ds = ds1 * ds2 print(ds)
print("Divide Series1 by Series2:") ds = ds1 / ds2 print(ds)
OUTPUT:
Add two Series:
0 3
1 7
2 1
3 1
4 1
0 1
40
1 1
2 1
3 1
4 1
dtype: int64Multiply two Series:
0 2
1 1
0 2.0
2 3 0
0
0
3 0 56
4 0
1 1.3 dtype: int64
3 Divide Series1 by Series2:
3
3
3
3
2 1.2
0
0
0
0 dtype: float64>
0
3 1.1
4
2
8
5
7
4
1.1
1
1
1
1
41
1
RESULT:
Thus the program for creating pandas has been written and executed successfully.
42
Ex. No 8B SCIPY
Date
AIM:
To write a program implementing Scipy Package.
ALGORITHM:
Step 1: Start.
Step 2: Import numpy package.
Step 3: Import io module from Scipy package.
Step 4: Create an array using ones().
Step 5: Create a dictionary.
Step 6: Save the contents to matrix file.
Step 7: Load the file.
Step 8: Print the data.
Step 9: Stop.
PROGRAM:
import numpy as np
from scipy import io as sio arr= np.ones((4, 4))
var={'ar': arr} sio.savemat('example.mat',var )
data = sio.loadmat('example.mat', struct_as_record=True)
print( data)
OUTPUT:
Array ([[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.],
[ 1., 1., 1., 1.]])
RESULT:
Thus the program for creating Scipy has been written and executed successfully.
43
Ex. No 8C MATPLOTLIB
Date
AIM:
To write a Python programming to create a pie chart for the popularity of programming Languages.
ALGORITHM:
Step 1: Start.
Step 2: Import matplot library.
Step 3: Give the input as languages and its popularity.
Step 4: Create piechart by calling function pie() with various parameters.
Step 5: Print the chart.
Step 6: Stop.
PROGRAM:
import matplotlib.pyplot as plt
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b"]
explode = (0.1, 0, 0, 0,0,0)
plt.pie(popuratity, explode=explode, labels=languages, colors=colors, autopct='%1.1f%%',
shadow=True, startangle=140)
plt.axis('equal') plt.show()
OUTPUT:
44
RESULT:
Thus the program for printing plot has been written and executed successfully.
45
Ex. No 8D NUMPY
Date
AIM:
To write a python program with numpy package.
ALGORITHM:
Step 1: Start.
Step 2: Create a numpy array.
Step 3: Use various attributes for numpy array.
Step 4: Print the results.
Step 5: Stop.
PROGRAM:
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] )
print(arr)
print("Array is of type: ", type(arr))
print("No. of dimensions: ", arr.ndim)
print("Shape of array: ", arr.shape)
print("Size of array: ", arr.size)
print("Array stores elements of type: ", arr.dtype)
OUTPUT:
[1 2 3]
[4 2 5]]
Array is of type: <class 'numpy.ndarray'> No. of dimensions: 2 Shape of array: (2, 3) Size of array: 6
Array stores elements of type: int64
RESULT:
Thus the program for to creating Numpy has been written and executed successfully.
46
VIVA QUESTIONS
1. What is a module? (TCS)
A separate Python file containing variables, functions, or classes for reuse in other programs.
47
Ex. No 9A FILE COPY
Date
AIM:
To write a python program to Copy the contents of the source file to destination file using copyfile
module.
ALGORITHM:
Step 1: Start
Step 2: Import the Copyfile module from shutil.
Step 3: Enter the source and destination file names.
Step 4: Copy the contents of the source file to destination file using copyfile module.
Step 5: End.
PROGRAM:
from shutil import copyfile
sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
print("Contents of destination file :")
FileRead = open(destinationfile, "r")
print(FileRead.read()) FileRead.close()
OUTPUT:
Contents of the file "A.txt":
Hello world!
Execution:
Enter source file name: A.txt Enter destination file name: B.txt File copied successfully! Contents of
destination file:
Hello world!
Contents of the file "B.txt" after execution:
Hello world!
RESULT:
Thus the program for copying the contents of the source file to destination file using copyfile module
has been written and executed successfully.
48
Ex. No 9B WORD COUNT
Date
AIM:
To write a python program to count the string in a file.
ALGORITHM:
Step 1: Start.
Step 2: Import the Counter module from collections.
Step 3: Read the file.
Step 4: Split the word using split() function.
Step 5: Count the words using Counter.
Step 6: End.
PROGRAM:
from collections import Counter
FileName = input("Enter the file name : ")
CntFile = open(FileName, 'r')
print("Number of words in the file :")
print(Counter(CntFile.read().split()))
CntFile.close()
OUTPUT:
Contents of the file "test.txt":
hi hello and welcome
Execution:
Enter the file name : test.txt Number of words in the file :
Counter({'hi': 1, 'hello': 1, 'and': 1, 'welcome': 1})
RESULT:
Thus the program for counting the string in a file has been written and executed successfully.
49
Ex. No 9C LONGEST WORD IN FILE
Date
AIM:
To write a python program to create longest word in file.
ALGORITHM:
Step 1: Start.
Step 2: Read the file from which the longest word is to be found.
Step 3: Compare all the words in the file and find the maximum length.
Step 4: Print the longest word.
Step 5: End.
PROGRAM:
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
file_name=input("Enter the file name:")
print(longest_word(file_name))
OUTPUT:
Contents of the file "test.txt": hi hello and welcome Execution:
Enter the file name:test.txt ['welcome']
RESULT:
Thus the program for creating longest word in file has been written and executed successfully.
50
VIVA QUESTIONS
51
Ex. No 10 A IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USING EXCEPTION
Date HANDLING DIVIDE BY ZERO
AIM:
To write a program for implementing real time /technical application using exception handling divide
by zero.
ALGORITHM:
Step 1: We will take inputs from the user, two numbers.
Step 2: If the entered data is not integer, throw an exception.
Step 3: If the remainder is 0, throw divide by zero exception.
Step 4: If no exception is there, return the result.
PROGRAM:
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e: print(e)
OUTPUT 1:
Enter First Number: abc
Invalid input please input integer...
OUTPUT 2:
Enter First Number: 43
Enter First Number: 0
Division by zero
OUTPUT 3:
Enter First Number: 331 2
Enter First Number: 4 83.0
52
RESULT:
Thus the program for implementing real time / technical application using exception handling divide
by
zero has been written and executed successfully.
53
54
Ex. No 10 B IMPLEMENTING REAL TIME /TECHNICAL
APPLICATION USINGEXCEPTION HANDLING
Date VOTER’S AGE VALIDITY
AIM:
To write a python program to for implementing real time /technical application using exception
handling voter’s age validity.
ALGORITHM:
Step 1: Start
Step 2: Accept the age of the person.
Step 3: If age is greater than or equal to 18, then display 'You are eligible to vote'.
Step 4: If age is less than 18, then display 'You are not eligible to vote'.
Step 5: Stop.
PROGRAM:
def main():
try:
age=int(input("Enter your age")) if age>18:
print("Eligible to vote") else:
print("Not eligible to vote")
#display exception's default error message except ValueError as err:
print(err) except:
print("An Error occured") print("rest of the code...") main()
OUTPUT 1:
Enter your age 30 Eligible to vote
OUTPUT 2:
Enter your age thirty
Invalid literal for int() with base 10: ' thirty' Rest of the code.
RESULT:
Thus the program for implementing real time / technical application using exception handling voter’s
age validity has been written and executed successfully.
55
VIVA QUESTIONS
1. What is exception? (TCS)
An error detected during execution, like ZeroDivisionError or ValueError.
2. Why handle exceptions? (Infosys)
To keep program running, show user-friendly message instead of crashing.
3. How to catch divide by zero error? (Capgemini)
Wrap code in try:, handle in except ZeroDivisionError:.
4. What is finally block? (Cognizant)
Code that runs always, whether exception happened or not.
5. Give example of real-time validation using exception. (Accenture)
Check voter's age: raise exception if age < 18, else continue.
6. What happens without exception handling? (Wipro)
Program stops immediately when error occurs, showing traceback.
7. What is custom exception? (IBM)
User-defined exception class for specific, meaningful errors.
8. Explain multiple except blocks. (HCL)
Handle different error types separately, e.g., ZeroDivisionError, ValueError.
9. How to raise an exception manually? (Tech Mahindra)
Use raise Exception("Message") to trigger an error.
10. Difference between error and exception? (Mindtree)
Error usually means serious issue; exception can often be handled in code.
56
Ex. No 11 PYGAME
Date
AIM:
To write a python program for simulate elliptical orbits using pygame.
ALGORITHM:
Step 1: Import the required packages
Step 2: Set up the colours for the elliptical orbits
Step 3: Define the parameters to simulate elliptical orbits
Step 4: Display the created orbits.
PROGRAM:
import pygame import math import sys pygame.init()
screen = pygame.display.set_mode((600, 300))
pygame.display.set_caption("Elliptical orbit")
clock = pygame.time.Clock()
while(True):
for event in pygame.event.get():
if (event.type == pygame.QUIT):
sys.exit()
xRadius = 250
yRadius = 100
for degree in range((0,360,10)):
x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300y1 = int(math.sin(degree * 2 *
math.pi / 360) * yRadius) + 150 screen.fill(0, 0, 0)
pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
pygame.display.flip()
clock.tick(5)
57
OUTPUT:
RESULT:
Thus the program for simulate elliptical orbits using pygame has been written and executed
successfully.
58
VIVA QUESTIONS
59
Ex. No 12 SIMULATING BOUNCING BALL
Date
AIM:
To write a python program for simulate bouncing ball using pygame.
ALGORITHM:
Step 1: Import the necessary files for the implementation of thisPygame.
Step 2: Set the display mode for the screen using window Surface= pygame.
display.set_mode((500,400),0,32)
Step 3: Now set the display mode for the pygame to bouncepygame. display.set_caption("Bounce")
Step 4: Develop the balls with necessary colors.BLACK=(0,0,0)WHITE=(255,255,255)RED=(255,0,0)
GREEN=(0,255,0) BLUE=(0,0,255)
Step 5: Set the display information info=pygame.display.Info()
Step 6: Set the initial direction as down.
Step 7: Change the direction from down to up.
Step 8: Then again change the direction from upto down.
Step 9: Set the condition for quit.
Step 10: Exit from the pygame.
PROGRAM:
import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"import sys, pygame
from pygame.locals import * pygame.init()
speed = [1, 1]
color = (255, 250, 250)
width = 550
height = 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame bouncing ball") ball = pygame.image.load("ball.png")
rect_boundry = ball.get_rect()
while 1:
for event in pygame.event.get():
rect_boundry = rect_boundry.move(speed)
if rect_boundry.left < 0 or rect_boundry.right > width:
speed[0] = -speed[0]
if rect_boundry.top < 0 or rect_boundry.bottom > height:
speed[1] = -speed[1]
60
screen.fill(color)
screen.blit(ball, rect_boundry)
pygame.display.flip()
if event.type == QUIT:
pygame.quit()
sys.exit()
OUTPUT:
RESULT:
Thus the program for bouncing ball using Pygame has been written and executed successfully.
61
VIVA QUESTIONS
62
Ex. No 13 PERFECT NUMBER OR NOT
Date
AIM:
To Write a Python program to find whether a number is perfect number or not.
S
ALGORITHM:
Step 1: Start
Step 2: Get one input number n.
Step 3: Call the function perfect number using n as input.
Step 4: Find the divisors of n by using modulus operator.
Step 5: Find the sum of n divisors.
Step 6: if sum==n, print n is perfect number.
Step 7: Else n is not perfect number.
Step 8: Stop.
PROGRAM:
def perfect_number(n): sum = 0
for x in range(1, n): if n % x == 0:
sum += x return sum == n
n=int(input("Enter a number"))
res=perfect_number(n)
if(res==True):
print(n,"is perfect number")
else:
print(n,"is not perfect number")
OUTPUT 1:
Enter a number 6
6 is perfect number
OUTPUT 2:
Enter a number21
21 is not perfect number
RESULT:
Thus the program to find perfect number or not is written successfully and output is verified
63
64
VIVA QUESTIONS
9. Can this logic be applied to check for abundant and deficient numbers? (Tech Mahindra)
Yes. Sum > number → abundant, sum < number → deficient, sum = number → perfect.
65
Ex. No 14 RIGHT ANGLE TRIANGLE OR NOT
Date
AIM:
To Write a Python program to find whether a triangle is right angled triangle or not.
ALGORITHM:
Step 1: Start
Step 2: Read the values for three sides of triangle.
Step 3: Square the sides of triangle.
Step 4: If (side3)2=(side2)2+(side1)2, print the triangle is right angled.
Step 5: Print the triangle is not right angled.
Step 6: Stop.
PROGRAM:
side1=int(input("Enter the first side:"))
side2=int(input("Enter the second side:"))
side3=int(input("Enter the third side:"))
a=(side2**2)+(side3**2)
b=(side1**2)+(side3**2)
c=(side1**2)+(side2**2)
if (a==side1**2 or b==side2**2 or c==side3**2):
print("This triangle is a right triangle.")
else:
print("This triangle is not a right triangle.")
OUTPUT:
Enter the first side:3
Enter the second side:5
Enter the third side:4
RESULT:
Thus the above program to find right angle triangle or not is written successfully and output was
verified successfully.
66
VIVA QUESTIONS
1. What condition defines a right-angled triangle? (TCS)
If square of the largest side equals the sum of squares of other two sides.
2. Why must we sort the sides before checking? (Infosys)
To make sure we treat the largest side as hypotenuse while applying the Pythagoras rule.
3. Can three sides of any length form a triangle? (Capgemini)
No. They must satisfy the triangle inequality: sum of any two sides > third side.
4. What is Pythagorean triplet? (Cognizant)
A set of three positive integers like 3, 4, 5 that satisfy a² + b² = c².
5. Can a triangle have more than one right angle? (Accenture)
No. The sum of angles in a triangle is always 180°, and two right angles would exceed that.
6. How do floating-point inaccuracies affect the check? (Wipro)
Small errors may occur in square root or exponentiation, so comparisons should use tolerance.
7. Is (5, 12, 13) a right-angled triangle? Prove it. (IBM)
Yes. 5² + 12² = 25 + 144 = 169 = 13².
8. What happens if all three sides are equal? (HCL)
It’s an equilateral triangle, not right-angled; no angle is 90°.
9. Can a triangle be both isosceles and right-angled? (Tech Mahindra)
Yes. A triangle with two equal sides and a 90° angle is possible, like (1, 1, √2).
10. What is the unit of measurement for sides? (Mindtree)
Sides can be in any unit (cm, m, etc.), but all must be in the same unit for correct comparison.
67